Spaces:
Running
Running
axeronis commited on
Commit ·
526e04d
1
Parent(s): 8fe7132
refactor: Frontend + Backend modular AI Core
Browse filesFrontend:
- Extract types to frontend/types/index.ts
- Decompose ChatWindow into sub-components
- Decompose Sidebar with NavItem component
Backend:
- Remove Evolution API (deprecated)
- Modularize ai_core.py into ai_core/ package:
- base.py: AICore facade
- response_generator.py: Response generation
- lead_analyzer.py: Lead analysis + heat scoring
- context_manager.py: RAG, booking, orders
- prompt_builder.py: System prompts
- backend/app/api/channels.py +1 -9
- backend/app/api/evolution_webhook.py +0 -438
- backend/app/core/config.py +0 -4
- backend/app/main.py +1 -2
- backend/app/services/ai_core/__init__.py +17 -0
- backend/app/services/ai_core/base.py +239 -0
- backend/app/services/ai_core/context_manager.py +257 -0
- backend/app/services/ai_core/lead_analyzer.py +373 -0
- backend/app/services/ai_core/prompt_builder.py +235 -0
- backend/app/services/ai_core/response_generator.py +144 -0
- backend/app/services/ai_core/types.py +21 -0
- backend/app/services/{ai_core.py → ai_core_legacy.py} +0 -0
- backend/app/services/whatsapp_qr.py +0 -4
- backend/tests/test_evolution_webhook.py +0 -122
- frontend/components/ChatWindow.tsx +140 -319
- frontend/components/ChatWindow/ChatHeader.tsx +110 -0
- frontend/components/ChatWindow/MessageBubble.tsx +83 -0
- frontend/components/ChatWindow/MessageInput.tsx +85 -0
- frontend/components/ChatWindow/TypingIndicator.tsx +34 -0
- frontend/components/ChatWindow/index.ts +11 -0
- frontend/components/Sidebar.tsx +121 -202
- frontend/components/Sidebar/NavItem.tsx +53 -0
- frontend/components/Sidebar/index.ts +5 -0
- frontend/lib/api.ts +17 -92
- frontend/types/index.ts +217 -0
backend/app/api/channels.py
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
Channels API - Telegram, WhatsApp (
|
| 3 |
"""
|
| 4 |
from typing import List, Dict, Any, Optional
|
| 5 |
from uuid import UUID
|
|
@@ -14,7 +14,6 @@ from app.core.config import settings
|
|
| 14 |
from app.core.logging import get_logger
|
| 15 |
from app.models import User
|
| 16 |
from app.api.deps import get_current_user
|
| 17 |
-
# from app.services.whatsapp_qr import whatsapp_qr_service # DEPRECATED
|
| 18 |
from app.services.whatsapp_cloud import whatsapp_cloud_service
|
| 19 |
from app.services.linkedin_service import linkedin_service
|
| 20 |
|
|
@@ -328,13 +327,6 @@ async def disconnect_linkedin(
|
|
| 328 |
raise HTTPException(status_code=500, detail=str(e))
|
| 329 |
|
| 330 |
|
| 331 |
-
# ==================== WhatsApp QR (Evolution API) ====================
|
| 332 |
-
|
| 333 |
-
# ==================== WhatsApp QR (Evolution API) - DEPRECATED ====================
|
| 334 |
-
# Endpoints removed. Use /whatsapp/connect for Cloud API.
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
# ==================== WHATSAPP CLOUD API ENDPOINTS ====================
|
| 339 |
|
| 340 |
class WhatsAppConnectRequest(BaseModel):
|
|
|
|
| 1 |
"""
|
| 2 |
+
Channels API - Telegram, WhatsApp (Cloud API), LinkedIn Connection
|
| 3 |
"""
|
| 4 |
from typing import List, Dict, Any, Optional
|
| 5 |
from uuid import UUID
|
|
|
|
| 14 |
from app.core.logging import get_logger
|
| 15 |
from app.models import User
|
| 16 |
from app.api.deps import get_current_user
|
|
|
|
| 17 |
from app.services.whatsapp_cloud import whatsapp_cloud_service
|
| 18 |
from app.services.linkedin_service import linkedin_service
|
| 19 |
|
|
|
|
| 327 |
raise HTTPException(status_code=500, detail=str(e))
|
| 328 |
|
| 329 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 330 |
# ==================== WHATSAPP CLOUD API ENDPOINTS ====================
|
| 331 |
|
| 332 |
class WhatsAppConnectRequest(BaseModel):
|
backend/app/api/evolution_webhook.py
DELETED
|
@@ -1,438 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
Evolution API Webhook Handler.
|
| 3 |
-
Handles incoming WhatsApp messages from Evolution API.
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
|
| 7 |
-
from sqlalchemy.ext.asyncio import AsyncSession
|
| 8 |
-
from sqlalchemy import select
|
| 9 |
-
from uuid import UUID
|
| 10 |
-
from datetime import datetime
|
| 11 |
-
import httpx
|
| 12 |
-
|
| 13 |
-
from app.core.database import get_async_session
|
| 14 |
-
from app.models.tenant import Tenant
|
| 15 |
-
from app.models.lead import Lead, Message, Conversation, MessageStatus
|
| 16 |
-
from app.services.ai_core import get_ai_core
|
| 17 |
-
from app.core.logging import get_logger
|
| 18 |
-
from app.core.config import settings
|
| 19 |
-
|
| 20 |
-
logger = get_logger(__name__)
|
| 21 |
-
router = APIRouter(prefix="/webhook/evolution", tags=["Evolution Webhooks"])
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
@router.post("/{tenant_id}")
|
| 25 |
-
async def handle_evolution_webhook(
|
| 26 |
-
tenant_id: UUID,
|
| 27 |
-
request: Request,
|
| 28 |
-
background_tasks: BackgroundTasks,
|
| 29 |
-
session: AsyncSession = Depends(get_async_session)
|
| 30 |
-
):
|
| 31 |
-
"""
|
| 32 |
-
Webhook Message Handler (POST).
|
| 33 |
-
Receives incoming messages from Evolution API (WhatsApp).
|
| 34 |
-
"""
|
| 35 |
-
|
| 36 |
-
# 1. Parse incoming webhook data
|
| 37 |
-
try:
|
| 38 |
-
data = await request.json()
|
| 39 |
-
except Exception as e:
|
| 40 |
-
raise HTTPException(status_code=400, detail=f"Invalid JSON: {str(e)}")
|
| 41 |
-
|
| 42 |
-
logger.info(f"📩 Evolution Webhook: Type={data.get('type')} Keys={list(data.keys())} DataKeys={list(data.get('data', {}).keys())}")
|
| 43 |
-
|
| 44 |
-
# 2. Get tenant
|
| 45 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 46 |
-
if not tenant:
|
| 47 |
-
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 48 |
-
|
| 49 |
-
# 3. Extract message
|
| 50 |
-
try:
|
| 51 |
-
message_data = extract_evolution_message(data)
|
| 52 |
-
|
| 53 |
-
if not message_data:
|
| 54 |
-
# No message to process (could be status update, etc.)
|
| 55 |
-
return {"status": "ok", "message": "No message to process"}
|
| 56 |
-
|
| 57 |
-
except Exception as e:
|
| 58 |
-
logger.error(f"❌ Error extracting message: {e}")
|
| 59 |
-
raise HTTPException(status_code=400, detail=f"Failed to parse message: {str(e)}")
|
| 60 |
-
|
| 61 |
-
# 4. Process message in background
|
| 62 |
-
background_tasks.add_task(
|
| 63 |
-
process_evolution_message,
|
| 64 |
-
tenant_id=tenant.id,
|
| 65 |
-
message_data=message_data
|
| 66 |
-
)
|
| 67 |
-
|
| 68 |
-
return {"status": "ok"}
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
from typing import Optional
|
| 72 |
-
|
| 73 |
-
def extract_evolution_message(data: dict) -> Optional[dict]:
|
| 74 |
-
"""
|
| 75 |
-
Extract message from Evolution API webhook payload.
|
| 76 |
-
"""
|
| 77 |
-
try:
|
| 78 |
-
# Check event type
|
| 79 |
-
event_type = data.get("type")
|
| 80 |
-
if event_type != "messages.upsert":
|
| 81 |
-
return None
|
| 82 |
-
|
| 83 |
-
message_data = data.get("data", {})
|
| 84 |
-
key = message_data.get("key", {})
|
| 85 |
-
|
| 86 |
-
# Skip messages sent by me (fromMe=true)
|
| 87 |
-
if key.get("fromMe"):
|
| 88 |
-
return None
|
| 89 |
-
|
| 90 |
-
# Get sender
|
| 91 |
-
remote_jid = key.get("remoteJid", "")
|
| 92 |
-
sender_id = remote_jid.split("@")[0] if "@" in remote_jid else remote_jid
|
| 93 |
-
|
| 94 |
-
# Get message content
|
| 95 |
-
message_content = message_data.get("message", {})
|
| 96 |
-
|
| 97 |
-
# Text message
|
| 98 |
-
text = ""
|
| 99 |
-
audio_url = None
|
| 100 |
-
|
| 101 |
-
if "conversation" in message_content:
|
| 102 |
-
text = message_content["conversation"]
|
| 103 |
-
elif "extendedTextMessage" in message_content:
|
| 104 |
-
text = message_content["extendedTextMessage"].get("text", "")
|
| 105 |
-
elif "audioMessage" in message_content:
|
| 106 |
-
# Handle Voice Message
|
| 107 |
-
audio_msg = message_content["audioMessage"]
|
| 108 |
-
# Evolution API usually provides a 'url' to download media if configured,
|
| 109 |
-
# or we might need to fetch it via ID.
|
| 110 |
-
# For now checking standard fields.
|
| 111 |
-
# WARNING: Evolution API structure for media often varies.
|
| 112 |
-
# Checking 'url' or 'directPath' or base64
|
| 113 |
-
audio_url = audio_msg.get("url") # Public or accessible URL
|
| 114 |
-
text = "[Voice Message]" # Placeholder
|
| 115 |
-
|
| 116 |
-
if not text and not audio_url:
|
| 117 |
-
return None
|
| 118 |
-
|
| 119 |
-
return {
|
| 120 |
-
"sender_id": sender_id,
|
| 121 |
-
"message_id": key.get("id"),
|
| 122 |
-
"text": text,
|
| 123 |
-
"audio_url": audio_url, # NEW
|
| 124 |
-
"timestamp": message_data.get("messageTimestamp")
|
| 125 |
-
}
|
| 126 |
-
|
| 127 |
-
except (IndexError, KeyError) as e:
|
| 128 |
-
logger.error(f"⚠️ Evolution payload parsing error: {e}")
|
| 129 |
-
return None
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
async def process_evolution_message(
|
| 133 |
-
tenant_id: UUID,
|
| 134 |
-
message_data: dict
|
| 135 |
-
):
|
| 136 |
-
"""
|
| 137 |
-
Background task: Process incoming WhatsApp message.
|
| 138 |
-
"""
|
| 139 |
-
from app.core.database import async_session_maker
|
| 140 |
-
import asyncio
|
| 141 |
-
|
| 142 |
-
sender_id = message_data["sender_id"]
|
| 143 |
-
text = message_data["text"]
|
| 144 |
-
audio_url = message_data.get("audio_url")
|
| 145 |
-
|
| 146 |
-
if not text and not audio_url:
|
| 147 |
-
return
|
| 148 |
-
|
| 149 |
-
logger.info(f"🔄 Processing WhatsApp message from {sender_id}")
|
| 150 |
-
|
| 151 |
-
# STEP 0: Transcribe Audio (if present)
|
| 152 |
-
if audio_url:
|
| 153 |
-
try:
|
| 154 |
-
logger.info(f"🎤 Voice message detected. Downloading from: {audio_url}")
|
| 155 |
-
async with httpx.AsyncClient() as client:
|
| 156 |
-
# Need headers? Usually Evolution media URLs are public or require API key
|
| 157 |
-
headers = {"apikey": settings.EVOLUTION_API_KEY}
|
| 158 |
-
# Note: If URL is internal to Evolution, it might need auth.
|
| 159 |
-
# If it's a public AWS/S3 link (common in cloud ver), no auth needed.
|
| 160 |
-
# Trying with simple get first.
|
| 161 |
-
resp = await client.get(audio_url)
|
| 162 |
-
resp.raise_for_status()
|
| 163 |
-
audio_bytes = resp.content
|
| 164 |
-
|
| 165 |
-
from app.services.llm_client import get_llm_client
|
| 166 |
-
gc = get_llm_client()
|
| 167 |
-
|
| 168 |
-
logger.info("🎤 Transcribing audio...")
|
| 169 |
-
transcription = await gc.transcribe_audio(audio_bytes, mime_type="audio/ogg") # WhatsApp voice is usually OGG
|
| 170 |
-
|
| 171 |
-
logger.info(f"✅ Transcription result: {transcription}")
|
| 172 |
-
text = f"[Voice Message] {transcription}"
|
| 173 |
-
|
| 174 |
-
except Exception as e:
|
| 175 |
-
logger.error(f"❌ Voice transcription failed: {e}")
|
| 176 |
-
text = "[Voice Message] (Не удалось распознать аудио)"
|
| 177 |
-
# Proceed anyway so user knows we tried
|
| 178 |
-
|
| 179 |
-
# STEP 1: Save user message and get IDs
|
| 180 |
-
user_message_id = None
|
| 181 |
-
# ... (Rest of function)
|
| 182 |
-
lead_id = None
|
| 183 |
-
conversation_id = None
|
| 184 |
-
|
| 185 |
-
async with async_session_maker() as session:
|
| 186 |
-
try:
|
| 187 |
-
# Get tenant
|
| 188 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 189 |
-
if not tenant:
|
| 190 |
-
return
|
| 191 |
-
|
| 192 |
-
# Find or create Lead
|
| 193 |
-
stmt = select(Lead).where(
|
| 194 |
-
Lead.tenant_id == tenant.id,
|
| 195 |
-
Lead.whatsapp_id == sender_id # Corrected to use whatsapp_id
|
| 196 |
-
)
|
| 197 |
-
result = await session.execute(stmt)
|
| 198 |
-
lead = result.scalar_one_or_none()
|
| 199 |
-
|
| 200 |
-
if not lead:
|
| 201 |
-
lead = Lead(
|
| 202 |
-
tenant_id=tenant.id,
|
| 203 |
-
name=f"WhatsApp User {sender_id[-4:]}",
|
| 204 |
-
whatsapp_id=sender_id, # Corrected
|
| 205 |
-
status="NEW",
|
| 206 |
-
processing_status="idle"
|
| 207 |
-
)
|
| 208 |
-
session.add(lead)
|
| 209 |
-
await session.flush()
|
| 210 |
-
|
| 211 |
-
lead_id = lead.id
|
| 212 |
-
|
| 213 |
-
# Find or create Conversation
|
| 214 |
-
stmt = select(Conversation).where(
|
| 215 |
-
Conversation.tenant_id == tenant.id,
|
| 216 |
-
Conversation.lead_id == lead.id,
|
| 217 |
-
Conversation.is_active == True
|
| 218 |
-
)
|
| 219 |
-
result = await session.execute(stmt)
|
| 220 |
-
conversation = result.scalar_one_or_none()
|
| 221 |
-
|
| 222 |
-
if not conversation:
|
| 223 |
-
conversation = Conversation(
|
| 224 |
-
tenant_id=tenant.id,
|
| 225 |
-
lead_id=lead.id,
|
| 226 |
-
channel="whatsapp",
|
| 227 |
-
is_active=True,
|
| 228 |
-
started_at=datetime.utcnow()
|
| 229 |
-
)
|
| 230 |
-
session.add(conversation)
|
| 231 |
-
await session.flush()
|
| 232 |
-
|
| 233 |
-
conversation_id = conversation.id
|
| 234 |
-
|
| 235 |
-
# Save user message
|
| 236 |
-
user_message = Message(
|
| 237 |
-
tenant_id=tenant.id,
|
| 238 |
-
conversation_id=conversation.id,
|
| 239 |
-
sender_type="user",
|
| 240 |
-
content=text
|
| 241 |
-
)
|
| 242 |
-
session.add(user_message)
|
| 243 |
-
|
| 244 |
-
# Update lead timestamps
|
| 245 |
-
lead.last_message_at = datetime.utcnow()
|
| 246 |
-
lead.last_activity_at = datetime.utcnow()
|
| 247 |
-
lead.first_message_at = lead.first_message_at or datetime.utcnow()
|
| 248 |
-
lead.processing_status = "analyzing"
|
| 249 |
-
session.add(lead)
|
| 250 |
-
|
| 251 |
-
await session.commit()
|
| 252 |
-
await session.refresh(user_message)
|
| 253 |
-
user_message_id = user_message.id
|
| 254 |
-
|
| 255 |
-
except Exception as e:
|
| 256 |
-
logger.error(f"❌ Error saving message: {e}", exc_info=True)
|
| 257 |
-
return
|
| 258 |
-
|
| 259 |
-
# STEP 2: Debouncing delay (4 seconds)
|
| 260 |
-
await asyncio.sleep(4)
|
| 261 |
-
|
| 262 |
-
# STEP 3: Check for newer messages
|
| 263 |
-
async with async_session_maker() as session:
|
| 264 |
-
try:
|
| 265 |
-
stmt = select(Message).where(
|
| 266 |
-
Message.conversation_id == conversation_id,
|
| 267 |
-
Message.sender_type == "user"
|
| 268 |
-
).order_by(Message.created_at.desc()).limit(1)
|
| 269 |
-
|
| 270 |
-
result = await session.execute(stmt)
|
| 271 |
-
latest_user_message = result.scalar_one_or_none()
|
| 272 |
-
|
| 273 |
-
if latest_user_message and latest_user_message.id != user_message_id:
|
| 274 |
-
logger.info(f"⏭️ Debouncing: Skipping old message {user_message_id}")
|
| 275 |
-
|
| 276 |
-
# Reset status to idle
|
| 277 |
-
lead = await session.get(Lead, lead_id)
|
| 278 |
-
if lead:
|
| 279 |
-
lead.processing_status = "idle"
|
| 280 |
-
session.add(lead)
|
| 281 |
-
await session.commit()
|
| 282 |
-
return
|
| 283 |
-
|
| 284 |
-
except Exception as e:
|
| 285 |
-
logger.error(f"❌ Error checking for newer messages: {e}", exc_info=True)
|
| 286 |
-
return
|
| 287 |
-
|
| 288 |
-
# STEP 4: Generate AI response
|
| 289 |
-
async with async_session_maker() as session:
|
| 290 |
-
try:
|
| 291 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 292 |
-
lead = await session.get(Lead, lead_id)
|
| 293 |
-
|
| 294 |
-
if not tenant or not lead:
|
| 295 |
-
return
|
| 296 |
-
|
| 297 |
-
# Set generating status
|
| 298 |
-
lead.processing_status = "generating"
|
| 299 |
-
session.add(lead)
|
| 300 |
-
await session.commit()
|
| 301 |
-
|
| 302 |
-
# Get conversation history
|
| 303 |
-
stmt = select(Message).where(
|
| 304 |
-
Message.conversation_id == conversation_id
|
| 305 |
-
).order_by(Message.created_at)
|
| 306 |
-
result = await session.execute(stmt)
|
| 307 |
-
messages = list(result.scalars().all())
|
| 308 |
-
|
| 309 |
-
# Get AI Core
|
| 310 |
-
ai_core = get_ai_core()
|
| 311 |
-
|
| 312 |
-
# Generate response
|
| 313 |
-
response = await ai_core.generate_sales_response(
|
| 314 |
-
session=session,
|
| 315 |
-
tenant=tenant,
|
| 316 |
-
lead=lead,
|
| 317 |
-
user_message=text,
|
| 318 |
-
conversation_history=messages
|
| 319 |
-
)
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
# Save AI response
|
| 323 |
-
ai_message = Message(
|
| 324 |
-
tenant_id=tenant.id,
|
| 325 |
-
conversation_id=conversation_id,
|
| 326 |
-
sender_type="ai",
|
| 327 |
-
content=response["text"],
|
| 328 |
-
status=MessageStatus.PENDING, # Init as PENDING
|
| 329 |
-
prompt_tokens=response["prompt_tokens"],
|
| 330 |
-
completion_tokens=response["completion_tokens"],
|
| 331 |
-
model_used=settings.GEMINI_MODEL
|
| 332 |
-
)
|
| 333 |
-
session.add(ai_message)
|
| 334 |
-
|
| 335 |
-
lead.last_message_at = datetime.utcnow()
|
| 336 |
-
lead.processing_status = "idle"
|
| 337 |
-
session.add(lead)
|
| 338 |
-
|
| 339 |
-
await session.commit()
|
| 340 |
-
|
| 341 |
-
# Parse response for images (Visual Commerce) AND Booking
|
| 342 |
-
import re
|
| 343 |
-
response_text = response["text"]
|
| 344 |
-
image_url = None
|
| 345 |
-
booking_slot = None
|
| 346 |
-
|
| 347 |
-
# Extract [PRODUCT_IMAGE: url]
|
| 348 |
-
img_match = re.search(r'\[PRODUCT_IMAGE: (.*?)\]', response_text)
|
| 349 |
-
if img_match:
|
| 350 |
-
image_url = img_match.group(1).strip()
|
| 351 |
-
response_text = response_text.replace(img_match.group(0), "").strip()
|
| 352 |
-
|
| 353 |
-
# Extract [BOOK_SLOT: datetime]
|
| 354 |
-
book_match = re.search(r'\[BOOK_SLOT: (.*?)\]', response_text)
|
| 355 |
-
if book_match:
|
| 356 |
-
booking_slot = book_match.group(1).strip()
|
| 357 |
-
response_text = response_text.replace(book_match.group(0), "").strip()
|
| 358 |
-
|
| 359 |
-
# EXECUTE BOOKING
|
| 360 |
-
try:
|
| 361 |
-
from app.services.booking_service import get_booking_service
|
| 362 |
-
from dateutil.parser import parse
|
| 363 |
-
|
| 364 |
-
booking_dt = parse(booking_slot)
|
| 365 |
-
bs = get_booking_service()
|
| 366 |
-
default_service = await bs.create_default_service(session, tenant.id)
|
| 367 |
-
|
| 368 |
-
await bs.book_appointment(
|
| 369 |
-
session=session,
|
| 370 |
-
service_id=default_service.id,
|
| 371 |
-
lead_id=lead.id,
|
| 372 |
-
start_time=booking_dt
|
| 373 |
-
)
|
| 374 |
-
logger.info(f"✅ BOOKING CREATED for {sender_id} at {booking_dt}")
|
| 375 |
-
|
| 376 |
-
# Inform user it's done
|
| 377 |
-
response_text += "\n✅ Встреча подтверждена в календаре!"
|
| 378 |
-
|
| 379 |
-
except Exception as e:
|
| 380 |
-
logger.error(f"Booking failed: {e}")
|
| 381 |
-
response_text += "\n⚠️ Не удалось автоматически забронировать слот. Менеджер свяжется для подтверждения."
|
| 382 |
-
|
| 383 |
-
# Send response back to user via Evolution API
|
| 384 |
-
# from app.services.whatsapp_qr import whatsapp_qr_service
|
| 385 |
-
|
| 386 |
-
send_success = False
|
| 387 |
-
# try:
|
| 388 |
-
# # ... (Logic disabled due to Evolution API deprecation)
|
| 389 |
-
# pass
|
| 390 |
-
# # 1. Send Text
|
| 391 |
-
# send_success = await whatsapp_qr_service.send_message(
|
| 392 |
-
# tenant_id=str(tenant.id),
|
| 393 |
-
# phone=sender_id,
|
| 394 |
-
# text=response_text
|
| 395 |
-
# )
|
| 396 |
-
|
| 397 |
-
# # Update status
|
| 398 |
-
# if send_success:
|
| 399 |
-
# ai_message.status = MessageStatus.SENT
|
| 400 |
-
# else:
|
| 401 |
-
# ai_message.status = MessageStatus.FAILED
|
| 402 |
-
|
| 403 |
-
# session.add(ai_message)
|
| 404 |
-
# await session.commit()
|
| 405 |
-
|
| 406 |
-
# # 2. Send Image (if found) - Treat as separate action, log errors but don't fail main message
|
| 407 |
-
# if image_url:
|
| 408 |
-
# logger.info(f"📸 Sending product image: {image_url}")
|
| 409 |
-
# # Small delay to ensure text arrives first
|
| 410 |
-
# await asyncio.sleep(1)
|
| 411 |
-
# await whatsapp_qr_service.send_media(
|
| 412 |
-
# tenant_id=str(tenant.id),
|
| 413 |
-
# phone=sender_id,
|
| 414 |
-
# media_url=image_url,
|
| 415 |
-
# caption="Фото товара", # Optional caption
|
| 416 |
-
# media_type="image"
|
| 417 |
-
# )
|
| 418 |
-
# except Exception as e:
|
| 419 |
-
# logger.error(f"❌ Error sending WhatsApp message: {e}")
|
| 420 |
-
# ai_message.status = MessageStatus.FAILED
|
| 421 |
-
# session.add(ai_message)
|
| 422 |
-
# await session.commit()
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
logger.info(f"✅ WhatsApp message processing complete")
|
| 426 |
-
|
| 427 |
-
except Exception as e:
|
| 428 |
-
logger.error(f"❌ Error processing WhatsApp message: {e}", exc_info=True)
|
| 429 |
-
|
| 430 |
-
# Set error status
|
| 431 |
-
try:
|
| 432 |
-
lead = await session.get(Lead, lead_id)
|
| 433 |
-
if lead:
|
| 434 |
-
lead.processing_status = "error"
|
| 435 |
-
session.add(lead)
|
| 436 |
-
await session.commit()
|
| 437 |
-
except:
|
| 438 |
-
pass
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/app/core/config.py
CHANGED
|
@@ -56,10 +56,6 @@ class Settings(BaseSettings):
|
|
| 56 |
TELEGRAM_NOTIFICATION_TOKEN: Optional[str] = "7734361434:AAGGKvlHN6BaND61F1Lr-0TQiBPsRWdmrRo"
|
| 57 |
TELEGRAM_WEBHOOK_URL: Optional[str] = None
|
| 58 |
|
| 59 |
-
# Evolution API / Baileys (WhatsApp)
|
| 60 |
-
EVOLUTION_API_URL: Optional[str] = None
|
| 61 |
-
EVOLUTION_API_KEY: str = "your-secret-key"
|
| 62 |
-
|
| 63 |
# AI Settings
|
| 64 |
MAX_CONTEXT_MESSAGES: int = 30 # Increased to 30 (will be trimmed by tokens in LLM client)
|
| 65 |
TEMPERATURE: float = 0.7
|
|
|
|
| 56 |
TELEGRAM_NOTIFICATION_TOKEN: Optional[str] = "7734361434:AAGGKvlHN6BaND61F1Lr-0TQiBPsRWdmrRo"
|
| 57 |
TELEGRAM_WEBHOOK_URL: Optional[str] = None
|
| 58 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
# AI Settings
|
| 60 |
MAX_CONTEXT_MESSAGES: int = 30 # Increased to 30 (will be trimmed by tokens in LLM client)
|
| 61 |
TEMPERATURE: float = 0.7
|
backend/app/main.py
CHANGED
|
@@ -7,7 +7,7 @@ from app.core.config import settings
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
-
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team,
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
|
@@ -168,7 +168,6 @@ app.add_middleware(RequestIDMiddleware)
|
|
| 168 |
app.include_router(auth.router, prefix="/api/v1")
|
| 169 |
app.include_router(webhook.router, prefix="/api/v1") # Email webhook
|
| 170 |
app.include_router(meta_webhooks.router, prefix="/api/v1") # Official Meta API (WA/IG)
|
| 171 |
-
# app.include_router(evolution_webhook.router, prefix="/api/v1") # DEPRECATED: Evolution API
|
| 172 |
app.include_router(telegram_webhook.router, prefix="/api/v1") # Telegram webhook
|
| 173 |
# app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
|
| 174 |
app.include_router(leads.router, prefix="/api/v1")
|
|
|
|
| 7 |
from app.core.database import init_pgvector
|
| 8 |
from app.core.logging import configure_logging, get_logger
|
| 9 |
from app.middleware.request_id import RequestIDMiddleware
|
| 10 |
+
from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, telegram_webhook, partners, notifications, products, bookings, jobs, system, meta_webhooks, voice, google_calendar, websocket_voice
|
| 11 |
|
| 12 |
# ... (omitted lines)
|
| 13 |
|
|
|
|
| 168 |
app.include_router(auth.router, prefix="/api/v1")
|
| 169 |
app.include_router(webhook.router, prefix="/api/v1") # Email webhook
|
| 170 |
app.include_router(meta_webhooks.router, prefix="/api/v1") # Official Meta API (WA/IG)
|
|
|
|
| 171 |
app.include_router(telegram_webhook.router, prefix="/api/v1") # Telegram webhook
|
| 172 |
# app.include_router(linkedin_webhook.router, prefix="/api/v1") # LinkedIn webhook (TODO: Implement)
|
| 173 |
app.include_router(leads.router, prefix="/api/v1")
|
backend/app/services/ai_core/__init__.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Module
|
| 3 |
+
|
| 4 |
+
Modular AI orchestration for MicroFunnel.
|
| 5 |
+
|
| 6 |
+
This package contains:
|
| 7 |
+
- base: Main AICore class (facade)
|
| 8 |
+
- response_generator: AI response generation
|
| 9 |
+
- lead_analyzer: Lead analysis and scoring
|
| 10 |
+
- context_manager: Context retrieval (RAG, booking, orders)
|
| 11 |
+
- prompt_builder: System prompt construction
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from .base import AICore, get_ai_core
|
| 15 |
+
|
| 16 |
+
# Export main class and factory
|
| 17 |
+
__all__ = ['AICore', 'get_ai_core']
|
backend/app/services/ai_core/base.py
ADDED
|
@@ -0,0 +1,239 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Base Module
|
| 3 |
+
|
| 4 |
+
Contains the base AICore class with initialization and core dependencies.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import List, Dict, Any, Optional
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
+
|
| 11 |
+
from app.services.llm_client import get_llm_client
|
| 12 |
+
from app.services.vector_store import get_vector_store
|
| 13 |
+
from app.models.lead import Lead, Message, Psychotype, LeadHeat
|
| 14 |
+
from app.models.tenant import Tenant
|
| 15 |
+
from app.models.sales_stage import SalesStage
|
| 16 |
+
from app.models.ai_training import AITrainingExample, AILearningRule
|
| 17 |
+
from app.models.booking import Service
|
| 18 |
+
from sqlmodel import select
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class AICore:
|
| 22 |
+
"""
|
| 23 |
+
The BRAIN of MicroFunnel.
|
| 24 |
+
Orchestrates all AI operations: RAG, response generation, analysis.
|
| 25 |
+
|
| 26 |
+
MODULAR ARCHITECTURE (Refactored):
|
| 27 |
+
- response_generator: Generates sales responses
|
| 28 |
+
- lead_analyzer: Analyzes leads and updates heat scores
|
| 29 |
+
- context_manager: Manages RAG context, booking, orders
|
| 30 |
+
- prompt_builder: Builds system prompts
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self):
|
| 34 |
+
"""Initialize AI Core with LLM and Vector Store clients."""
|
| 35 |
+
self.llm = get_llm_client()
|
| 36 |
+
self.vector_store = get_vector_store()
|
| 37 |
+
|
| 38 |
+
# =========================================================================
|
| 39 |
+
# Response Generation (from response_generator.py)
|
| 40 |
+
# =========================================================================
|
| 41 |
+
|
| 42 |
+
async def generate_sales_response(
|
| 43 |
+
self,
|
| 44 |
+
session: AsyncSession,
|
| 45 |
+
tenant: Tenant,
|
| 46 |
+
lead: Lead,
|
| 47 |
+
user_message: str,
|
| 48 |
+
conversation_history: List[Message]
|
| 49 |
+
) -> Dict[str, Any]:
|
| 50 |
+
"""
|
| 51 |
+
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
| 52 |
+
|
| 53 |
+
Delegates to response_generator module.
|
| 54 |
+
"""
|
| 55 |
+
from .response_generator import generate_sales_response_impl
|
| 56 |
+
return await generate_sales_response_impl(
|
| 57 |
+
self, session, tenant, lead, user_message, conversation_history
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
# =========================================================================
|
| 61 |
+
# Lead Analysis (from lead_analyzer.py)
|
| 62 |
+
# =========================================================================
|
| 63 |
+
|
| 64 |
+
async def analyze_lead(
|
| 65 |
+
self,
|
| 66 |
+
session: AsyncSession,
|
| 67 |
+
lead: Lead,
|
| 68 |
+
conversation_history: List[Message]
|
| 69 |
+
) -> Dict[str, Any]:
|
| 70 |
+
"""
|
| 71 |
+
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
| 72 |
+
|
| 73 |
+
Delegates to lead_analyzer module.
|
| 74 |
+
"""
|
| 75 |
+
from .lead_analyzer import analyze_lead_impl
|
| 76 |
+
return await analyze_lead_impl(self, session, lead, conversation_history)
|
| 77 |
+
|
| 78 |
+
# =========================================================================
|
| 79 |
+
# Reactivation (from lead_analyzer.py)
|
| 80 |
+
# =========================================================================
|
| 81 |
+
|
| 82 |
+
async def evaluate_reactivation(
|
| 83 |
+
self,
|
| 84 |
+
session: AsyncSession,
|
| 85 |
+
lead: Lead,
|
| 86 |
+
conversation_history: List[Message]
|
| 87 |
+
) -> Dict[str, Any]:
|
| 88 |
+
"""
|
| 89 |
+
Evaluate if a stale lead should be reactivated and generate a message.
|
| 90 |
+
|
| 91 |
+
Delegates to lead_analyzer module.
|
| 92 |
+
"""
|
| 93 |
+
from .lead_analyzer import evaluate_reactivation_impl
|
| 94 |
+
return await evaluate_reactivation_impl(self, session, lead, conversation_history)
|
| 95 |
+
|
| 96 |
+
# =========================================================================
|
| 97 |
+
# Context Management (from context_manager.py)
|
| 98 |
+
# =========================================================================
|
| 99 |
+
|
| 100 |
+
async def _get_booking_context(
|
| 101 |
+
self,
|
| 102 |
+
session: AsyncSession,
|
| 103 |
+
tenant_id: UUID,
|
| 104 |
+
lead: Lead,
|
| 105 |
+
user_message: str,
|
| 106 |
+
stage: Optional[SalesStage] = None
|
| 107 |
+
) -> str:
|
| 108 |
+
"""Get booking/appointment context."""
|
| 109 |
+
from .context_manager import get_booking_context
|
| 110 |
+
return await get_booking_context(session, tenant_id, lead, user_message, stage)
|
| 111 |
+
|
| 112 |
+
async def _get_order_context(
|
| 113 |
+
self,
|
| 114 |
+
session: AsyncSession,
|
| 115 |
+
tenant_id: UUID
|
| 116 |
+
) -> str:
|
| 117 |
+
"""Get order context for commerce agent."""
|
| 118 |
+
from .context_manager import get_order_context
|
| 119 |
+
return await get_order_context(session, tenant_id)
|
| 120 |
+
|
| 121 |
+
async def _get_relevant_context(
|
| 122 |
+
self,
|
| 123 |
+
session: AsyncSession,
|
| 124 |
+
tenant_id: UUID,
|
| 125 |
+
user_message: str,
|
| 126 |
+
top_k: int = 3
|
| 127 |
+
) -> str:
|
| 128 |
+
"""Get relevant context from knowledge base via vector search."""
|
| 129 |
+
from .context_manager import get_relevant_context
|
| 130 |
+
return await get_relevant_context(
|
| 131 |
+
self.vector_store, session, tenant_id, user_message, top_k
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
async def _get_training_examples(
|
| 135 |
+
self,
|
| 136 |
+
session: AsyncSession,
|
| 137 |
+
tenant_id: UUID,
|
| 138 |
+
limit: int = 5
|
| 139 |
+
) -> List[AITrainingExample]:
|
| 140 |
+
"""Load training examples for few-shot learning."""
|
| 141 |
+
from .context_manager import get_training_examples
|
| 142 |
+
return await get_training_examples(session, tenant_id, limit)
|
| 143 |
+
|
| 144 |
+
async def _get_learning_rules(
|
| 145 |
+
self,
|
| 146 |
+
session: AsyncSession,
|
| 147 |
+
tenant_id: UUID,
|
| 148 |
+
user_message: str
|
| 149 |
+
) -> List[AILearningRule]:
|
| 150 |
+
"""Load learning rules filtered by trigger keywords."""
|
| 151 |
+
from .context_manager import get_learning_rules
|
| 152 |
+
return await get_learning_rules(session, tenant_id, user_message)
|
| 153 |
+
|
| 154 |
+
async def _get_relevant_scripts(
|
| 155 |
+
self,
|
| 156 |
+
session: AsyncSession,
|
| 157 |
+
tenant_id: UUID,
|
| 158 |
+
user_message: str,
|
| 159 |
+
psychotype: Psychotype
|
| 160 |
+
) -> List[str]:
|
| 161 |
+
"""Get relevant sales scripts based on user message."""
|
| 162 |
+
from .context_manager import get_relevant_scripts
|
| 163 |
+
return await get_relevant_scripts(
|
| 164 |
+
self.vector_store, session, tenant_id, user_message, psychotype
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
# =========================================================================
|
| 168 |
+
# Prompt Building (from prompt_builder.py)
|
| 169 |
+
# =========================================================================
|
| 170 |
+
|
| 171 |
+
def _build_system_prompt(
|
| 172 |
+
self,
|
| 173 |
+
tenant: Tenant,
|
| 174 |
+
lead: Lead,
|
| 175 |
+
context_facts: str,
|
| 176 |
+
product_context: str,
|
| 177 |
+
scripts_context: Optional[List[str]],
|
| 178 |
+
training_examples: Optional[List[AITrainingExample]] = None,
|
| 179 |
+
learning_rules: Optional[List[AILearningRule]] = None,
|
| 180 |
+
stage: Optional[SalesStage] = None,
|
| 181 |
+
booking_context: str = "",
|
| 182 |
+
order_context: str = ""
|
| 183 |
+
) -> str:
|
| 184 |
+
"""Build the system prompt for AI generation."""
|
| 185 |
+
from .prompt_builder import build_system_prompt
|
| 186 |
+
return build_system_prompt(
|
| 187 |
+
tenant, lead, context_facts, product_context, scripts_context,
|
| 188 |
+
training_examples, learning_rules, stage, booking_context, order_context
|
| 189 |
+
)
|
| 190 |
+
|
| 191 |
+
def _get_dynamic_sales_mission(self, methodology: str, tone: str) -> str:
|
| 192 |
+
"""Generate dynamic sales mission based on configuration."""
|
| 193 |
+
from .prompt_builder import get_dynamic_sales_mission
|
| 194 |
+
return get_dynamic_sales_mission(methodology, tone)
|
| 195 |
+
|
| 196 |
+
def _format_chat_history(self, messages: List[Message]) -> List[Dict[str, str]]:
|
| 197 |
+
"""Format messages for Gemini chat history."""
|
| 198 |
+
from .response_generator import format_chat_history
|
| 199 |
+
return format_chat_history(messages)
|
| 200 |
+
|
| 201 |
+
# =========================================================================
|
| 202 |
+
# Internal Helpers (from lead_analyzer.py)
|
| 203 |
+
# =========================================================================
|
| 204 |
+
|
| 205 |
+
def _merge_summaries(self, old: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]:
|
| 206 |
+
"""Smart merging logic for anti-amnesia."""
|
| 207 |
+
from .lead_analyzer import merge_summaries
|
| 208 |
+
return merge_summaries(old, new)
|
| 209 |
+
|
| 210 |
+
async def _extract_and_update_bant(
|
| 211 |
+
self,
|
| 212 |
+
session: AsyncSession,
|
| 213 |
+
lead: Lead,
|
| 214 |
+
user_message: str
|
| 215 |
+
) -> None:
|
| 216 |
+
"""Extract BANT information from user message and update lead."""
|
| 217 |
+
from .lead_analyzer import extract_and_update_bant
|
| 218 |
+
await extract_and_update_bant(self.llm, session, lead, user_message)
|
| 219 |
+
|
| 220 |
+
async def _trigger_crm_auto_sync(
|
| 221 |
+
self,
|
| 222 |
+
session: AsyncSession,
|
| 223 |
+
lead: Lead
|
| 224 |
+
) -> None:
|
| 225 |
+
"""Trigger automatic CRM synchronization if enabled."""
|
| 226 |
+
from .lead_analyzer import trigger_crm_auto_sync
|
| 227 |
+
await trigger_crm_auto_sync(session, lead)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# Singleton instance
|
| 231 |
+
_ai_core_instance: Optional[AICore] = None
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def get_ai_core() -> AICore:
|
| 235 |
+
"""Get AI Core service instance."""
|
| 236 |
+
global _ai_core_instance
|
| 237 |
+
if _ai_core_instance is None:
|
| 238 |
+
_ai_core_instance = AICore()
|
| 239 |
+
return _ai_core_instance
|
backend/app/services/ai_core/context_manager.py
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Context Manager
|
| 3 |
+
|
| 4 |
+
Handles retrieval of context for AI responses:
|
| 5 |
+
- Booking availability
|
| 6 |
+
- Order context (commerce agent)
|
| 7 |
+
- Knowledge Base (RAG)
|
| 8 |
+
- Training examples
|
| 9 |
+
- Learning rules
|
| 10 |
+
- Sales scripts
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from typing import List, Dict, Any, Optional
|
| 14 |
+
from uuid import UUID
|
| 15 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 16 |
+
from sqlmodel import select
|
| 17 |
+
|
| 18 |
+
from app.models.lead import Lead, Psychotype
|
| 19 |
+
from app.models.sales_stage import SalesStage
|
| 20 |
+
from app.models.booking import Service
|
| 21 |
+
from app.models.ai_training import AITrainingExample, AILearningRule
|
| 22 |
+
from app.models.knowledge import SalesScript
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ============================================================================
|
| 26 |
+
# Booking Context
|
| 27 |
+
# ============================================================================
|
| 28 |
+
|
| 29 |
+
async def get_booking_context(
|
| 30 |
+
session: AsyncSession,
|
| 31 |
+
tenant_id: UUID,
|
| 32 |
+
lead: Lead,
|
| 33 |
+
user_message: str,
|
| 34 |
+
stage: Optional[SalesStage] = None
|
| 35 |
+
) -> str:
|
| 36 |
+
"""
|
| 37 |
+
Get booking/appointment context.
|
| 38 |
+
|
| 39 |
+
NOTE: This now ALWAYS returns context when services/slots exist.
|
| 40 |
+
AI will decide whether to use it based on conditional prompt instructions.
|
| 41 |
+
"""
|
| 42 |
+
# Get active services for tenant
|
| 43 |
+
stmt = select(Service).where(
|
| 44 |
+
Service.tenant_id == tenant_id,
|
| 45 |
+
Service.is_active == True
|
| 46 |
+
)
|
| 47 |
+
result = await session.execute(stmt)
|
| 48 |
+
services = result.scalars().all()
|
| 49 |
+
|
| 50 |
+
if not services:
|
| 51 |
+
return ""
|
| 52 |
+
|
| 53 |
+
# Format context
|
| 54 |
+
context = "AVAILABLE BOOKING SERVICES:\n"
|
| 55 |
+
for service in services:
|
| 56 |
+
context += f"- {service.name} ({service.duration_minutes} min): {service.description or 'No description'}\n"
|
| 57 |
+
|
| 58 |
+
context += "\n(To book, ask the user for their preferred date/time)"
|
| 59 |
+
|
| 60 |
+
return context
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# ============================================================================
|
| 64 |
+
# Order Context (Commerce Agent)
|
| 65 |
+
# ============================================================================
|
| 66 |
+
|
| 67 |
+
async def get_order_context(
|
| 68 |
+
session: AsyncSession,
|
| 69 |
+
tenant_id: UUID
|
| 70 |
+
) -> str:
|
| 71 |
+
"""
|
| 72 |
+
Get instructions for the "Order Agent" capability.
|
| 73 |
+
The AI uses this to know HOW to create an order tag.
|
| 74 |
+
"""
|
| 75 |
+
return """
|
| 76 |
+
⚠️ ORDER CREATION PROTOCOL (Use when client wants to buy):
|
| 77 |
+
1. IF the user confirms they want to place an order.
|
| 78 |
+
2. YOU MUST COLLECT:
|
| 79 |
+
- Items (What products?)
|
| 80 |
+
- Customer Name (If unknown)
|
| 81 |
+
- Delivery Address (If delivery needed)
|
| 82 |
+
- Phone Number
|
| 83 |
+
|
| 84 |
+
3. ONCE COLLECTED, output the hidden tag to trigger the Order Agent:
|
| 85 |
+
[CREATE_ORDER: {
|
| 86 |
+
"items": [{"product_name": "...", "quantity": 1}],
|
| 87 |
+
"customer": {"name": "...", "phone": "...", "address": "..."},
|
| 88 |
+
"notes": "..."
|
| 89 |
+
}]
|
| 90 |
+
|
| 91 |
+
4. DO NOT make up an Order ID. Just output the tag. The system will reply with the confirmation.
|
| 92 |
+
"""
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
# ============================================================================
|
| 96 |
+
# Knowledge Base Context (RAG)
|
| 97 |
+
# ============================================================================
|
| 98 |
+
|
| 99 |
+
async def get_relevant_context(
|
| 100 |
+
vector_store, # VectorStore instance
|
| 101 |
+
session: AsyncSession,
|
| 102 |
+
tenant_id: UUID,
|
| 103 |
+
user_message: str,
|
| 104 |
+
top_k: int = 3
|
| 105 |
+
) -> str:
|
| 106 |
+
"""
|
| 107 |
+
Get relevant FACTS from Knowledge Base using vector search.
|
| 108 |
+
|
| 109 |
+
TASK 1: Vector Search Retrieval
|
| 110 |
+
- Embed the user's message
|
| 111 |
+
- Query knowledge_base table using pgvector (cosine distance)
|
| 112 |
+
- Return top K most relevant chunks for the tenant
|
| 113 |
+
"""
|
| 114 |
+
try:
|
| 115 |
+
# Use vector store for semantic search
|
| 116 |
+
results = await vector_store.semantic_search(
|
| 117 |
+
session=session,
|
| 118 |
+
tenant_id=tenant_id,
|
| 119 |
+
query=user_message,
|
| 120 |
+
top_k=top_k,
|
| 121 |
+
min_similarity=0.6 # Only return relevant results
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
if not results:
|
| 125 |
+
return "No relevant facts found in knowledge base."
|
| 126 |
+
|
| 127 |
+
# Format results as structured context
|
| 128 |
+
context_parts = []
|
| 129 |
+
for i, result in enumerate(results, 1):
|
| 130 |
+
similarity_score = result['similarity']
|
| 131 |
+
content = result['content']
|
| 132 |
+
category = result.get('category', 'General')
|
| 133 |
+
|
| 134 |
+
# Add metadata for transparency
|
| 135 |
+
context_parts.append(
|
| 136 |
+
f"[Fact {i}] (Relevance: {similarity_score:.0%}) - Category: {category}\n{content}"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
return "\n\n".join(context_parts)
|
| 140 |
+
|
| 141 |
+
except Exception as e:
|
| 142 |
+
print(f"❌ Error retrieving context from Knowledge Base: {e}")
|
| 143 |
+
import traceback
|
| 144 |
+
traceback.print_exc()
|
| 145 |
+
return "No relevant facts found in knowledge base."
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
# ============================================================================
|
| 149 |
+
# Training Examples
|
| 150 |
+
# ============================================================================
|
| 151 |
+
|
| 152 |
+
async def get_training_examples(
|
| 153 |
+
session: AsyncSession,
|
| 154 |
+
tenant_id: UUID,
|
| 155 |
+
limit: int = 5
|
| 156 |
+
) -> List[AITrainingExample]:
|
| 157 |
+
"""
|
| 158 |
+
Load training examples for few-shot learning.
|
| 159 |
+
Returns most important examples (sorted by weight).
|
| 160 |
+
"""
|
| 161 |
+
try:
|
| 162 |
+
stmt = select(AITrainingExample).where(
|
| 163 |
+
AITrainingExample.tenant_id == tenant_id,
|
| 164 |
+
AITrainingExample.is_active == True
|
| 165 |
+
).order_by(AITrainingExample.weight.desc()).limit(limit)
|
| 166 |
+
|
| 167 |
+
result = await session.execute(stmt)
|
| 168 |
+
examples = result.scalars().all()
|
| 169 |
+
return list(examples)
|
| 170 |
+
|
| 171 |
+
except Exception as e:
|
| 172 |
+
print(f"⚠️ Error loading training examples: {e}")
|
| 173 |
+
return []
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# ============================================================================
|
| 177 |
+
# Learning Rules
|
| 178 |
+
# ============================================================================
|
| 179 |
+
|
| 180 |
+
async def get_learning_rules(
|
| 181 |
+
session: AsyncSession,
|
| 182 |
+
tenant_id: UUID,
|
| 183 |
+
user_message: str
|
| 184 |
+
) -> List[AILearningRule]:
|
| 185 |
+
"""
|
| 186 |
+
Load learning rules, optionally filtered by trigger keywords.
|
| 187 |
+
Returns rules sorted by priority.
|
| 188 |
+
"""
|
| 189 |
+
try:
|
| 190 |
+
stmt = select(AILearningRule).where(
|
| 191 |
+
AILearningRule.tenant_id == tenant_id,
|
| 192 |
+
AILearningRule.is_active == True
|
| 193 |
+
).order_by(AILearningRule.priority.desc())
|
| 194 |
+
|
| 195 |
+
result = await session.execute(stmt)
|
| 196 |
+
all_rules = result.scalars().all()
|
| 197 |
+
|
| 198 |
+
# Filter by triggers if present
|
| 199 |
+
filtered_rules = []
|
| 200 |
+
user_lower = user_message.lower()
|
| 201 |
+
|
| 202 |
+
for rule in all_rules:
|
| 203 |
+
# If rule has triggers, check if any match
|
| 204 |
+
if rule.triggers:
|
| 205 |
+
if any(trigger.lower() in user_lower for trigger in rule.triggers):
|
| 206 |
+
filtered_rules.append(rule)
|
| 207 |
+
else:
|
| 208 |
+
# No triggers = always applies
|
| 209 |
+
filtered_rules.append(rule)
|
| 210 |
+
|
| 211 |
+
return filtered_rules
|
| 212 |
+
|
| 213 |
+
except Exception as e:
|
| 214 |
+
print(f"⚠️ Error loading learning rules: {e}")
|
| 215 |
+
return []
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ============================================================================
|
| 219 |
+
# Sales Scripts
|
| 220 |
+
# ============================================================================
|
| 221 |
+
|
| 222 |
+
async def get_relevant_scripts(
|
| 223 |
+
vector_store, # VectorStore instance
|
| 224 |
+
session: AsyncSession,
|
| 225 |
+
tenant_id: UUID,
|
| 226 |
+
user_message: str,
|
| 227 |
+
psychotype: Psychotype
|
| 228 |
+
) -> List[str]:
|
| 229 |
+
"""
|
| 230 |
+
Get relevant sales scripts based on user message.
|
| 231 |
+
"""
|
| 232 |
+
try:
|
| 233 |
+
# Query sales scripts (could be enhanced with vector search)
|
| 234 |
+
stmt = select(SalesScript).where(
|
| 235 |
+
SalesScript.tenant_id == tenant_id,
|
| 236 |
+
SalesScript.is_active == True
|
| 237 |
+
)
|
| 238 |
+
|
| 239 |
+
result = await session.execute(stmt)
|
| 240 |
+
scripts = result.scalars().all()
|
| 241 |
+
|
| 242 |
+
# Filter by psychotype if matching
|
| 243 |
+
matching_scripts = []
|
| 244 |
+
for script in scripts:
|
| 245 |
+
# Check if script targets this psychotype
|
| 246 |
+
if script.target_psychotype:
|
| 247 |
+
if script.target_psychotype == psychotype.value:
|
| 248 |
+
matching_scripts.append(script.content)
|
| 249 |
+
else:
|
| 250 |
+
# Generic script
|
| 251 |
+
matching_scripts.append(script.content)
|
| 252 |
+
|
| 253 |
+
return matching_scripts[:3] # Limit to 3 scripts
|
| 254 |
+
|
| 255 |
+
except Exception as e:
|
| 256 |
+
print(f"⚠️ Error loading sales scripts: {e}")
|
| 257 |
+
return []
|
backend/app/services/ai_core/lead_analyzer.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Lead Analyzer
|
| 3 |
+
|
| 4 |
+
Handles lead analysis:
|
| 5 |
+
- Psychotype detection
|
| 6 |
+
- Heat score calculation
|
| 7 |
+
- 11-point summary generation
|
| 8 |
+
- Summary merging (anti-amnesia)
|
| 9 |
+
- BANT extraction
|
| 10 |
+
- CRM synchronization
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from typing import List, Dict, Any, TYPE_CHECKING
|
| 14 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 15 |
+
|
| 16 |
+
from app.models.lead import Lead, Message, Psychotype, LeadHeat
|
| 17 |
+
from app.models.crm_integration import CRMIntegration, SyncStatus
|
| 18 |
+
|
| 19 |
+
if TYPE_CHECKING:
|
| 20 |
+
from .base import AICore
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
# ============================================================================
|
| 24 |
+
# Helper Functions
|
| 25 |
+
# ============================================================================
|
| 26 |
+
|
| 27 |
+
def is_empty_value(val: Any) -> bool:
|
| 28 |
+
"""Check if value is 'empty' (unknown, not detected, etc.)"""
|
| 29 |
+
if not val:
|
| 30 |
+
return True
|
| 31 |
+
if isinstance(val, str):
|
| 32 |
+
empty_patterns = [
|
| 33 |
+
'не выявлен', 'не указан', 'неизвестно',
|
| 34 |
+
'не определен', 'не раскрыт', 'не обнаружено',
|
| 35 |
+
'потребуется выявить', 'анализ ожидается',
|
| 36 |
+
'требуется выявить', 'будет уточнено',
|
| 37 |
+
'unknown', 'not specified', 'not disclosed'
|
| 38 |
+
]
|
| 39 |
+
return any(pattern in val.lower() for pattern in empty_patterns)
|
| 40 |
+
return False
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def merge_summaries(old: Dict[str, Any], new: Dict[str, Any]) -> Dict[str, Any]:
|
| 44 |
+
"""
|
| 45 |
+
TASK 2: Smart Merging Logic (Anti-Amnesia)
|
| 46 |
+
|
| 47 |
+
Strategy:
|
| 48 |
+
- intent: Always use NEW (intent changes)
|
| 49 |
+
- budget/authority/timeline: Keep OLD if NEW is empty/unknown
|
| 50 |
+
- pain_points: APPEND unique new points (max 5)
|
| 51 |
+
- objections: APPEND unique new points (max 5)
|
| 52 |
+
- psychotype: Always use NEW (gets better with more data)
|
| 53 |
+
- heat_score: Always use NEW (real-time metric)
|
| 54 |
+
"""
|
| 55 |
+
# Start with new summary as base
|
| 56 |
+
merged = new.copy()
|
| 57 |
+
|
| 58 |
+
# BUDGET: Keep old if new is empty
|
| 59 |
+
if is_empty_value(new.get('budget')) and not is_empty_value(old.get('budget')):
|
| 60 |
+
merged['budget'] = old['budget']
|
| 61 |
+
print(f"💰 Kept old budget: {old['budget']}")
|
| 62 |
+
|
| 63 |
+
# AUTHORITY: Keep old if new is empty
|
| 64 |
+
if is_empty_value(new.get('authority')) and not is_empty_value(old.get('authority')):
|
| 65 |
+
merged['authority'] = old['authority']
|
| 66 |
+
print(f"👤 Kept old authority: {old['authority']}")
|
| 67 |
+
|
| 68 |
+
# TIMELINE: Keep old if new is empty
|
| 69 |
+
if is_empty_value(new.get('timeline')) and not is_empty_value(old.get('timeline')):
|
| 70 |
+
merged['timeline'] = old['timeline']
|
| 71 |
+
print(f"⏰ Kept old timeline: {old['timeline']}")
|
| 72 |
+
|
| 73 |
+
# PAIN POINTS: Append unique new points (max 5)
|
| 74 |
+
old_pains = old.get('pain_points', []) if isinstance(old.get('pain_points'), list) else []
|
| 75 |
+
new_pains = new.get('pain_points', []) if isinstance(new.get('pain_points'), list) else []
|
| 76 |
+
|
| 77 |
+
merged_pains = old_pains.copy()
|
| 78 |
+
for pain in new_pains:
|
| 79 |
+
if pain and not is_empty_value(pain):
|
| 80 |
+
is_duplicate = False
|
| 81 |
+
pain_lower = pain.lower()
|
| 82 |
+
for existing in merged_pains:
|
| 83 |
+
if pain_lower in existing.lower() or existing.lower() in pain_lower:
|
| 84 |
+
is_duplicate = True
|
| 85 |
+
break
|
| 86 |
+
if not is_duplicate:
|
| 87 |
+
merged_pains.append(pain)
|
| 88 |
+
|
| 89 |
+
merged['pain_points'] = merged_pains[-5:]
|
| 90 |
+
|
| 91 |
+
# OBJECTIONS: Append unique new points (max 5)
|
| 92 |
+
old_objections = old.get('objections', []) if isinstance(old.get('objections'), list) else []
|
| 93 |
+
new_objections = new.get('objections', []) if isinstance(new.get('objections'), list) else []
|
| 94 |
+
|
| 95 |
+
merged_objections = old_objections.copy()
|
| 96 |
+
for objection in new_objections:
|
| 97 |
+
if objection and not is_empty_value(objection):
|
| 98 |
+
is_duplicate = False
|
| 99 |
+
objection_lower = objection.lower()
|
| 100 |
+
for existing in merged_objections:
|
| 101 |
+
if objection_lower in existing.lower() or existing.lower() in objection_lower:
|
| 102 |
+
is_duplicate = True
|
| 103 |
+
break
|
| 104 |
+
if not is_duplicate:
|
| 105 |
+
merged_objections.append(objection)
|
| 106 |
+
|
| 107 |
+
merged['objections'] = merged_objections[-5:]
|
| 108 |
+
|
| 109 |
+
return merged
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ============================================================================
|
| 113 |
+
# BANT Extraction
|
| 114 |
+
# ============================================================================
|
| 115 |
+
|
| 116 |
+
async def extract_and_update_bant(
|
| 117 |
+
llm, # LLM client
|
| 118 |
+
session: AsyncSession,
|
| 119 |
+
lead: Lead,
|
| 120 |
+
user_message: str
|
| 121 |
+
) -> None:
|
| 122 |
+
"""Extract BANT information from user message and update lead."""
|
| 123 |
+
try:
|
| 124 |
+
# Simple keyword-based BANT extraction (LLM would be overkill for this)
|
| 125 |
+
message_lower = user_message.lower()
|
| 126 |
+
|
| 127 |
+
# Budget signals
|
| 128 |
+
budget_keywords = ['бюджет', 'budget', 'цена', 'price', 'стоимость', 'дорого', 'дешево']
|
| 129 |
+
if any(kw in message_lower for kw in budget_keywords):
|
| 130 |
+
# Could extract actual value with regex or LLM
|
| 131 |
+
pass
|
| 132 |
+
|
| 133 |
+
# Timeline signals
|
| 134 |
+
timeline_keywords = ['когда', 'срок', 'deadline', 'быстро', 'срочно', 'asap']
|
| 135 |
+
if any(kw in message_lower for kw in timeline_keywords):
|
| 136 |
+
pass
|
| 137 |
+
|
| 138 |
+
except Exception as e:
|
| 139 |
+
print(f"⚠️ BANT extraction error (non-critical): {e}")
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
# ============================================================================
|
| 143 |
+
# CRM Sync
|
| 144 |
+
# ============================================================================
|
| 145 |
+
|
| 146 |
+
async def trigger_crm_auto_sync(
|
| 147 |
+
session: AsyncSession,
|
| 148 |
+
lead: Lead
|
| 149 |
+
) -> None:
|
| 150 |
+
"""Trigger automatic CRM synchronization if enabled."""
|
| 151 |
+
try:
|
| 152 |
+
if lead.heat_level != LeadHeat.HOT:
|
| 153 |
+
return # Only sync hot leads
|
| 154 |
+
|
| 155 |
+
from sqlmodel import select
|
| 156 |
+
|
| 157 |
+
# Check if CRM integration is enabled
|
| 158 |
+
stmt = select(CRMIntegration).where(
|
| 159 |
+
CRMIntegration.tenant_id == lead.tenant_id,
|
| 160 |
+
CRMIntegration.is_active == True,
|
| 161 |
+
CRMIntegration.auto_sync == True
|
| 162 |
+
)
|
| 163 |
+
result = await session.execute(stmt)
|
| 164 |
+
integration = result.scalar_one_or_none()
|
| 165 |
+
|
| 166 |
+
if not integration:
|
| 167 |
+
return
|
| 168 |
+
|
| 169 |
+
# Trigger async sync (don't wait)
|
| 170 |
+
from app.services.crm_service import get_crm_service
|
| 171 |
+
crm_service = get_crm_service()
|
| 172 |
+
await crm_service.sync_lead(session, lead, integration)
|
| 173 |
+
|
| 174 |
+
print(f"🔄 CRM auto-sync triggered for lead {lead.id}")
|
| 175 |
+
|
| 176 |
+
except Exception as e:
|
| 177 |
+
print(f"⚠️ CRM auto-sync failed (non-critical): {e}")
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
# ============================================================================
|
| 181 |
+
# Main Analysis Function
|
| 182 |
+
# ============================================================================
|
| 183 |
+
|
| 184 |
+
async def analyze_lead_impl(
|
| 185 |
+
ai_core: "AICore",
|
| 186 |
+
session: AsyncSession,
|
| 187 |
+
lead: Lead,
|
| 188 |
+
conversation_history: List[Message]
|
| 189 |
+
) -> Dict[str, Any]:
|
| 190 |
+
"""
|
| 191 |
+
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
| 192 |
+
|
| 193 |
+
UPDATED LOGIC:
|
| 194 |
+
- NO message thresholds (analyze immediately)
|
| 195 |
+
- Smart merging (anti-amnesia)
|
| 196 |
+
- Inference mode (avoid "Unknown")
|
| 197 |
+
"""
|
| 198 |
+
# Extract user messages for psychotype analysis
|
| 199 |
+
user_messages = [
|
| 200 |
+
msg.content for msg in conversation_history
|
| 201 |
+
if msg.sender_type == "user"
|
| 202 |
+
]
|
| 203 |
+
|
| 204 |
+
# Get full conversation text
|
| 205 |
+
conversation_text = "\n".join([
|
| 206 |
+
f"{msg.sender_type.upper()}: {msg.content}"
|
| 207 |
+
for msg in conversation_history
|
| 208 |
+
])
|
| 209 |
+
|
| 210 |
+
# DEBUG
|
| 211 |
+
print(f"\n{'='*80}")
|
| 212 |
+
print(f"DEBUG CONTEXT FOR LEAD {lead.id} ({len(conversation_history)} messages):")
|
| 213 |
+
print(f"{'='*80}")
|
| 214 |
+
print(conversation_text[:500])
|
| 215 |
+
print(f"{'='*80}\n")
|
| 216 |
+
|
| 217 |
+
# 1. Detect psychotype
|
| 218 |
+
if len(user_messages) > 0:
|
| 219 |
+
psychotype_str = await ai_core.llm.analyze_psychotype(user_messages)
|
| 220 |
+
psychotype_str = psychotype_str.replace("*", "").strip().lower()
|
| 221 |
+
lead.psychotype = Psychotype(psychotype_str)
|
| 222 |
+
|
| 223 |
+
# 2. Calculate heat score
|
| 224 |
+
bant_data = {
|
| 225 |
+
"budget": lead.budget,
|
| 226 |
+
"authority": lead.authority,
|
| 227 |
+
"need": lead.need,
|
| 228 |
+
"timeline": lead.timeline
|
| 229 |
+
}
|
| 230 |
+
|
| 231 |
+
heat_score = await ai_core.llm.calculate_heat_score(
|
| 232 |
+
conversation_text=conversation_text,
|
| 233 |
+
bant_data=bant_data
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
lead.heat_score = heat_score
|
| 237 |
+
previous_heat_level = lead.heat_level
|
| 238 |
+
|
| 239 |
+
# Update heat level
|
| 240 |
+
if heat_score >= 70:
|
| 241 |
+
lead.heat_level = LeadHeat.HOT
|
| 242 |
+
elif heat_score >= 50:
|
| 243 |
+
lead.heat_level = LeadHeat.WARM
|
| 244 |
+
elif heat_score >= 30:
|
| 245 |
+
lead.heat_level = LeadHeat.COLD
|
| 246 |
+
else:
|
| 247 |
+
lead.heat_level = LeadHeat.JUNK
|
| 248 |
+
|
| 249 |
+
# 🔥 HOT LEAD NOTIFICATION
|
| 250 |
+
if previous_heat_level != LeadHeat.HOT and lead.heat_level == LeadHeat.HOT:
|
| 251 |
+
print(f"🔥 Lead {lead.id} became HOT! Sending notification...")
|
| 252 |
+
try:
|
| 253 |
+
from app.services.notification_service import get_notification_service
|
| 254 |
+
notification_service = get_notification_service()
|
| 255 |
+
await notification_service.notify_hot_lead(
|
| 256 |
+
session=session,
|
| 257 |
+
lead=lead,
|
| 258 |
+
tenant=lead.tenant
|
| 259 |
+
)
|
| 260 |
+
print(f"✅ HOT lead notification sent successfully")
|
| 261 |
+
except Exception as e:
|
| 262 |
+
print(f"⚠️ Failed to send HOT lead notification: {e}")
|
| 263 |
+
|
| 264 |
+
# 3. Generate and merge summary
|
| 265 |
+
try:
|
| 266 |
+
ai_settings = getattr(lead.tenant, 'ai_settings', None) if hasattr(lead, 'tenant') else None
|
| 267 |
+
business_desc = (ai_settings or {}).get('business_description', 'General business')
|
| 268 |
+
|
| 269 |
+
old_summary = lead.ai_summary_json or {}
|
| 270 |
+
|
| 271 |
+
new_summary = await ai_core.llm.generate_11_point_summary(
|
| 272 |
+
conversation_text=conversation_text,
|
| 273 |
+
lead_name=lead.name or "Customer",
|
| 274 |
+
psychotype=lead.psychotype.value,
|
| 275 |
+
heat_score=heat_score,
|
| 276 |
+
business_description=business_desc,
|
| 277 |
+
tenant_settings=ai_settings
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
print(f"✅ New summary generated: {len(new_summary)} fields")
|
| 281 |
+
|
| 282 |
+
merged_summary = merge_summaries(old_summary, new_summary)
|
| 283 |
+
lead.ai_summary_json = merged_summary
|
| 284 |
+
|
| 285 |
+
print(f"🔀 Merged summary applied")
|
| 286 |
+
|
| 287 |
+
except Exception as e:
|
| 288 |
+
print(f"❌ CRITICAL: 11-point summary generation failed: {e}")
|
| 289 |
+
import traceback
|
| 290 |
+
traceback.print_exc()
|
| 291 |
+
|
| 292 |
+
if not lead.ai_summary_json:
|
| 293 |
+
lead.ai_summary_json = {
|
| 294 |
+
"intent": "Анализ в процессе",
|
| 295 |
+
"psychotype": lead.psychotype.value,
|
| 296 |
+
"heat_score": heat_score,
|
| 297 |
+
"_error": str(e)
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
merged_summary = lead.ai_summary_json
|
| 301 |
+
|
| 302 |
+
# Save changes
|
| 303 |
+
session.add(lead)
|
| 304 |
+
await session.commit()
|
| 305 |
+
|
| 306 |
+
# Trigger CRM auto-sync
|
| 307 |
+
await trigger_crm_auto_sync(session, lead)
|
| 308 |
+
|
| 309 |
+
# PLAYBOOK: Evaluate Stage Transition
|
| 310 |
+
from app.services.playbook_service import get_playbook_service
|
| 311 |
+
stage_moved = await get_playbook_service().evaluate_transition(session, lead, merged_summary)
|
| 312 |
+
|
| 313 |
+
return {
|
| 314 |
+
"psychotype": lead.psychotype.value,
|
| 315 |
+
"heat_score": heat_score,
|
| 316 |
+
"heat_level": lead.heat_level.value,
|
| 317 |
+
"summary_generated": bool(lead.ai_summary_json),
|
| 318 |
+
"stage_moved": stage_moved
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# ============================================================================
|
| 323 |
+
# Reactivation
|
| 324 |
+
# ============================================================================
|
| 325 |
+
|
| 326 |
+
async def evaluate_reactivation_impl(
|
| 327 |
+
ai_core: "AICore",
|
| 328 |
+
session: AsyncSession,
|
| 329 |
+
lead: Lead,
|
| 330 |
+
conversation_history: List[Message]
|
| 331 |
+
) -> Dict[str, Any]:
|
| 332 |
+
"""
|
| 333 |
+
Evaluate if a stale lead should be reactivated and generate a message.
|
| 334 |
+
"""
|
| 335 |
+
# Get conversation text
|
| 336 |
+
conversation_text = "\n".join([
|
| 337 |
+
f"{msg.sender_type.upper()}: {msg.content}"
|
| 338 |
+
for msg in conversation_history[-10:] # Last 10 messages
|
| 339 |
+
])
|
| 340 |
+
|
| 341 |
+
# Use LLM to generate reactivation message
|
| 342 |
+
try:
|
| 343 |
+
reactivation_prompt = f"""
|
| 344 |
+
Based on the following conversation, generate a friendly reactivation message
|
| 345 |
+
to re-engage the lead. The message should:
|
| 346 |
+
1. Reference something specific from the conversation
|
| 347 |
+
2. Add value (new info, offer, etc.)
|
| 348 |
+
3. Have a clear call to action
|
| 349 |
+
|
| 350 |
+
Conversation:
|
| 351 |
+
{conversation_text}
|
| 352 |
+
|
| 353 |
+
Generate ONLY the reactivation message, nothing else.
|
| 354 |
+
"""
|
| 355 |
+
|
| 356 |
+
response = await ai_core.llm.generate_response(
|
| 357 |
+
prompt=reactivation_prompt,
|
| 358 |
+
system_instruction="You are a sales assistant. Be friendly and non-pushy."
|
| 359 |
+
)
|
| 360 |
+
|
| 361 |
+
return {
|
| 362 |
+
"should_reactivate": True,
|
| 363 |
+
"message": response["text"],
|
| 364 |
+
"reason": "Stale lead reactivation"
|
| 365 |
+
}
|
| 366 |
+
|
| 367 |
+
except Exception as e:
|
| 368 |
+
print(f"⚠️ Reactivation evaluation failed: {e}")
|
| 369 |
+
return {
|
| 370 |
+
"should_reactivate": False,
|
| 371 |
+
"message": None,
|
| 372 |
+
"reason": str(e)
|
| 373 |
+
}
|
backend/app/services/ai_core/prompt_builder.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Prompt Builder
|
| 3 |
+
|
| 4 |
+
Handles construction of system prompts for AI:
|
| 5 |
+
- Dynamic sales mission based on methodology
|
| 6 |
+
- Psychotype-specific instructions
|
| 7 |
+
- Playbook stage context
|
| 8 |
+
- Booking and order system instructions
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from typing import List, Optional
|
| 12 |
+
from app.models.lead import Lead
|
| 13 |
+
from app.models.tenant import Tenant
|
| 14 |
+
from app.models.sales_stage import SalesStage
|
| 15 |
+
from app.models.ai_training import AITrainingExample, AILearningRule
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# ============================================================================
|
| 19 |
+
# Dynamic Sales Mission
|
| 20 |
+
# ============================================================================
|
| 21 |
+
|
| 22 |
+
def get_dynamic_sales_mission(methodology: str, tone: str) -> str:
|
| 23 |
+
"""
|
| 24 |
+
Dynamically generate the Sales Mission based on user configuration.
|
| 25 |
+
This ensures the bot's "soul" matches the user's settings.
|
| 26 |
+
"""
|
| 27 |
+
# Default / Balanced Mission
|
| 28 |
+
mission_title = "🎯 DYNAMIC SALES MISSION"
|
| 29 |
+
mission_body = """
|
| 30 |
+
⚠️ ТВОЯ ЗАДАЧА: Найти баланс между помощью клиенту и продажей.
|
| 31 |
+
🔥 ТВОЯ ЦЕЛЬ: Помочь клиенту принять решение.
|
| 32 |
+
✅ СТИЛЬ: Адаптируйся под клиента.
|
| 33 |
+
"""
|
| 34 |
+
|
| 35 |
+
# 1. AGGRESSIVE / HARD SELLING
|
| 36 |
+
if any(x in methodology for x in ["Challenger", "Direct", "Transactional"]) or \
|
| 37 |
+
any(x in tone for x in ["Confident", "Aggressive", "Bold"]):
|
| 38 |
+
mission_title = "🚀 ACTIVE SALES MISSION"
|
| 39 |
+
mission_body = """
|
| 40 |
+
⚠️ ТВОЯ ЗАДАЧА: Вести клиента к сделке уверенно и прямо.
|
| 41 |
+
🔥 ТВОЯ ЦЕЛЬ: Продажа или четкий отказ (квалификация).
|
| 42 |
+
❌ НЕ БУДЬ ПАССИВНЫМ: Не жди вопросов, веди диалог сам.
|
| 43 |
+
✅ БУДЬ УВЕРЕННЫМ: Предлагай решения смело. Чёткие CTA.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
# 2. EMPATHETIC / SOFT SELLING
|
| 47 |
+
elif any(x in methodology for x in ["Consultative", "Relationship", "Soft"]) or \
|
| 48 |
+
any(x in tone for x in ["Empathetic", "Friendly", "Warm", "Polite"]):
|
| 49 |
+
mission_title = "❤️ TRUST-BASED SALES MISSION"
|
| 50 |
+
mission_body = """
|
| 51 |
+
⚠️ ТВОЯ ЗАДАЧА: Продавать через ДОВЕРИЕ и ЗАБОТУ.
|
| 52 |
+
🔥 ТВОЯ ЦЕЛЬ: Стать надежным советником для клиента.
|
| 53 |
+
❌ НЕ ДАВИ: Продажа - это следствие хороших отношений.
|
| 54 |
+
✅ БУДЬ ЭМПАТИЧНЫМ: Слушай, поддерживай, улыбайся.
|
| 55 |
+
"""
|
| 56 |
+
|
| 57 |
+
# 3. SANDLER
|
| 58 |
+
if "Sandler" in methodology:
|
| 59 |
+
mission_title = "🧠 SANDLER SALES EXPERT"
|
| 60 |
+
mission_body = """
|
| 61 |
+
⚠️ ТВОЯ ЗАДАЧА: Вести продажу через методологию Sandler.
|
| 62 |
+
🔥 ТВОЯ ЦЕЛЬ: Квалификация через БОЛЬ и ДОГОВОРЕННОСТИ.
|
| 63 |
+
✅ Upfront Contracts: Договаривайся о правилах беседы.
|
| 64 |
+
✅ Pain Funnel: Не продавай, пока не найдешь БОЛЬ.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
return f"""
|
| 68 |
+
═══════════════════════════════════════════════════════════════
|
| 69 |
+
[{mission_title}] - YOUR CONFIGURED MODE
|
| 70 |
+
═══════════════════════════════════════════════════════════════
|
| 71 |
+
{mission_body.strip()}
|
| 72 |
+
"""
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
# ============================================================================
|
| 76 |
+
# Psychotype Instructions
|
| 77 |
+
# ============================================================================
|
| 78 |
+
|
| 79 |
+
def get_psychotype_instructions(psychotype: str) -> str:
|
| 80 |
+
"""Get instructions for adapting to lead's psychotype."""
|
| 81 |
+
|
| 82 |
+
instructions = {
|
| 83 |
+
"dominant": """
|
| 84 |
+
🧠 ПСИХОТИП: ДОМИНАНТНЫЙ (D-тип)
|
| 85 |
+
- Будь ПРЯМЫМ и КРАТКИМ - никакой воды.
|
| 86 |
+
- Фокус на РЕЗУЛЬТАТАХ и ROI.
|
| 87 |
+
- Используй списки, не абзацы.
|
| 88 |
+
- Покажи, как это РЕШИТ проблему БЫСТРО.
|
| 89 |
+
""",
|
| 90 |
+
"influential": """
|
| 91 |
+
🧠 ПСИХОТИП: ВЛИЯТЕЛЬНЫЙ (I-тип)
|
| 92 |
+
- Будь ЭНТУЗИАСТОМ и ТЕПЛЫМ.
|
| 93 |
+
- Используй эмоциональный язык и истории.
|
| 94 |
+
- Подчеркивай, как они БУДУТ ЧУВСТВОВАТЬ после покупки.
|
| 95 |
+
- Социальное доказательство: "Многим нравится..."
|
| 96 |
+
""",
|
| 97 |
+
"steady": """
|
| 98 |
+
🧠 ПСИХОТИП: СТАБИЛЬНЫЙ (S-тип)
|
| 99 |
+
- Будь ТЕРПЕЛИВЫМ и ПОДДЕРЖИВАЮЩИМ.
|
| 100 |
+
- Никакого давления, пусть решают в своем темпе.
|
| 101 |
+
- Подчеркивай СТАБИЛЬНОСТЬ и НАДЕЖНОСТЬ.
|
| 102 |
+
- Давай полную информацию.
|
| 103 |
+
""",
|
| 104 |
+
"conscientious": """
|
| 105 |
+
🧠 ПСИХОТИ��: АНАЛИТИЧЕСКИЙ (C-тип)
|
| 106 |
+
- Будь ТОЧНЫМ и ДЕТАЛЬНЫМ.
|
| 107 |
+
- Предоставляй ФАКТЫ и ДАННЫЕ.
|
| 108 |
+
- Избегай эмоциональных аргументов.
|
| 109 |
+
- Дай время на анализ.
|
| 110 |
+
"""
|
| 111 |
+
}
|
| 112 |
+
|
| 113 |
+
return instructions.get(psychotype.lower(), "")
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
# ============================================================================
|
| 117 |
+
# Main Prompt Builder
|
| 118 |
+
# ============================================================================
|
| 119 |
+
|
| 120 |
+
def build_system_prompt(
|
| 121 |
+
tenant: Tenant,
|
| 122 |
+
lead: Lead,
|
| 123 |
+
context_facts: str,
|
| 124 |
+
product_context: str,
|
| 125 |
+
scripts_context: Optional[List[str]],
|
| 126 |
+
training_examples: Optional[List[AITrainingExample]] = None,
|
| 127 |
+
learning_rules: Optional[List[AILearningRule]] = None,
|
| 128 |
+
stage: Optional[SalesStage] = None,
|
| 129 |
+
booking_context: str = "",
|
| 130 |
+
order_context: str = ""
|
| 131 |
+
) -> str:
|
| 132 |
+
"""
|
| 133 |
+
Build HYBRID System Prompt for AI.
|
| 134 |
+
|
| 135 |
+
Combines:
|
| 136 |
+
- Tenant persona and settings
|
| 137 |
+
- Lead psychotype adaptation
|
| 138 |
+
- Playbook stage context
|
| 139 |
+
- Knowledge base facts
|
| 140 |
+
- Booking/order systems
|
| 141 |
+
"""
|
| 142 |
+
|
| 143 |
+
# Extract bot identity
|
| 144 |
+
ai_identity = tenant.ai_identity or {}
|
| 145 |
+
bot_name = ai_identity.get("bot_name", "")
|
| 146 |
+
bot_role = ai_identity.get("bot_role", "")
|
| 147 |
+
company_name = tenant.business_name or tenant.name or ""
|
| 148 |
+
|
| 149 |
+
# Extract AI settings
|
| 150 |
+
ai_settings = tenant.ai_settings or {}
|
| 151 |
+
business_description = ai_settings.get("business_description", "")
|
| 152 |
+
tone_instruction = tenant.tone_of_voice or ""
|
| 153 |
+
sales_methodology = tenant.sales_methodology or ""
|
| 154 |
+
custom_instructions = tenant.custom_instructions or ""
|
| 155 |
+
banned_words = tenant.banned_words or []
|
| 156 |
+
|
| 157 |
+
# Format banned words
|
| 158 |
+
banned_words_text = ""
|
| 159 |
+
if banned_words:
|
| 160 |
+
banned_words_text = f"\n⚠️ ЗАПРЕЩЕННЫЕ СЛОВА: {', '.join(banned_words)}"
|
| 161 |
+
|
| 162 |
+
# Get dynamic mission
|
| 163 |
+
sales_mission = get_dynamic_sales_mission(sales_methodology, tone_instruction)
|
| 164 |
+
|
| 165 |
+
# Get psychotype instructions
|
| 166 |
+
psychotype_text = get_psychotype_instructions(lead.psychotype.value if lead.psychotype else "")
|
| 167 |
+
|
| 168 |
+
# Build playbook section
|
| 169 |
+
playbook_text = ""
|
| 170 |
+
if stage:
|
| 171 |
+
playbook_text = f"""
|
| 172 |
+
═══════════════════════════════════════════════════════════════
|
| 173 |
+
[PLAYBOOK STAGE: {stage.name.upper()}]
|
| 174 |
+
═══════════════════════════════════════════════════════════════
|
| 175 |
+
📌 ЭТАП: {stage.name}
|
| 176 |
+
({stage.description})
|
| 177 |
+
|
| 178 |
+
🎯 ЦЕЛЬ: {stage.ai_goal}
|
| 179 |
+
|
| 180 |
+
🚧 КРИТЕРИИ ПЕРЕХОДА:
|
| 181 |
+
{', '.join(stage.exit_criteria) if stage.exit_criteria else 'N/A'}
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
# Build booking section
|
| 185 |
+
booking_section = ""
|
| 186 |
+
if booking_context:
|
| 187 |
+
booking_section = f"""
|
| 188 |
+
═══════════════════════════════════════════════════════════════
|
| 189 |
+
[BOOKING SYSTEM]
|
| 190 |
+
═══════════════════════════════════════════════════════════════
|
| 191 |
+
{booking_context}
|
| 192 |
+
|
| 193 |
+
📝 Для записи используй: [BOOK_SLOT: YYYY-MM-DD HH:MM]
|
| 194 |
+
"""
|
| 195 |
+
|
| 196 |
+
# Build order section
|
| 197 |
+
order_section = ""
|
| 198 |
+
if order_context:
|
| 199 |
+
order_section = f"""
|
| 200 |
+
═══════════════════════════════════════════════════════════════
|
| 201 |
+
[ORDER SYSTEM]
|
| 202 |
+
═══════════════════════════════════════════════════════════════
|
| 203 |
+
{order_context}
|
| 204 |
+
"""
|
| 205 |
+
|
| 206 |
+
# Combine all sections
|
| 207 |
+
prompt = f"""
|
| 208 |
+
═══════════════════════════════════════════════════════════════
|
| 209 |
+
[BOT IDENTITY]
|
| 210 |
+
═══════════════════════════════════════════════════════════════
|
| 211 |
+
{f"Имя: {bot_name}" if bot_name else ""}
|
| 212 |
+
{f"Роль: {bot_role}" if bot_role else ""}
|
| 213 |
+
{f"Компания: {company_name}" if company_name else ""}
|
| 214 |
+
{f"Описание: {business_description}" if business_description else ""}
|
| 215 |
+
{banned_words_text}
|
| 216 |
+
|
| 217 |
+
{sales_mission}
|
| 218 |
+
|
| 219 |
+
{psychotype_text}
|
| 220 |
+
|
| 221 |
+
{playbook_text}
|
| 222 |
+
|
| 223 |
+
═══════════════════════════════════════════════════════════════
|
| 224 |
+
[KNOWLEDGE BASE]
|
| 225 |
+
═════════════════════════��═════════════════════════════════════
|
| 226 |
+
{context_facts}
|
| 227 |
+
|
| 228 |
+
{booking_section}
|
| 229 |
+
|
| 230 |
+
{order_section}
|
| 231 |
+
|
| 232 |
+
{f"ДОПОЛНИТЕЛЬНЫЕ ИНСТРУКЦИИ: {custom_instructions}" if custom_instructions else ""}
|
| 233 |
+
"""
|
| 234 |
+
|
| 235 |
+
return prompt.strip()
|
backend/app/services/ai_core/response_generator.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Response Generator
|
| 3 |
+
|
| 4 |
+
Handles generation of AI sales responses:
|
| 5 |
+
- Response generation with memory cache
|
| 6 |
+
- Chat history formatting
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from typing import List, Dict, Any, TYPE_CHECKING
|
| 10 |
+
from datetime import datetime
|
| 11 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 12 |
+
|
| 13 |
+
from app.models.lead import Lead, Message
|
| 14 |
+
from app.models.tenant import Tenant
|
| 15 |
+
|
| 16 |
+
if TYPE_CHECKING:
|
| 17 |
+
from .base import AICore
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
# ============================================================================
|
| 21 |
+
# Response Generation
|
| 22 |
+
# ============================================================================
|
| 23 |
+
|
| 24 |
+
async def generate_sales_response_impl(
|
| 25 |
+
ai_core: "AICore",
|
| 26 |
+
session: AsyncSession,
|
| 27 |
+
tenant: Tenant,
|
| 28 |
+
lead: Lead,
|
| 29 |
+
user_message: str,
|
| 30 |
+
conversation_history: List[Message]
|
| 31 |
+
) -> Dict[str, Any]:
|
| 32 |
+
"""
|
| 33 |
+
Generate AI sales response with PERSISTENT MEMORY (Gemini Cache).
|
| 34 |
+
|
| 35 |
+
New Flow:
|
| 36 |
+
1. Smart Context: Get Playbook Stage & Booking Slots (Dynamic)
|
| 37 |
+
2. Persistent Memory: Get cached Tenant Context (Static: KB, Products, Persona)
|
| 38 |
+
3. Interference: Inject dynamic context into prompt.
|
| 39 |
+
4. Generation: Gemini 1.5 Flash uses Cache + Dynamic Context.
|
| 40 |
+
"""
|
| 41 |
+
# Import here to avoid circular imports
|
| 42 |
+
from .lead_analyzer import extract_and_update_bant
|
| 43 |
+
from app.services.playbook_service import get_playbook_service
|
| 44 |
+
from app.services.ai_memory_manager import get_memory_manager
|
| 45 |
+
|
| 46 |
+
# Extract BANT information from user message and update lead
|
| 47 |
+
await extract_and_update_bant(ai_core.llm, session, lead, user_message)
|
| 48 |
+
|
| 49 |
+
# PLAYBOOK INTEGRATION (Deep Funnel)
|
| 50 |
+
playbook_service = get_playbook_service()
|
| 51 |
+
|
| 52 |
+
# 0. Ensure Playbook Exists for Tenant (Lazy Init)
|
| 53 |
+
await playbook_service.initialize_default_stages(session, tenant.id)
|
| 54 |
+
|
| 55 |
+
# 1. Get Current Stage
|
| 56 |
+
current_stage = await playbook_service.get_current_stage(session, lead)
|
| 57 |
+
|
| 58 |
+
# 2. BOOKING SYSTEM: Get available slots (if intent/stage matches)
|
| 59 |
+
booking_context = await ai_core._get_booking_context(
|
| 60 |
+
session=session,
|
| 61 |
+
tenant_id=tenant.id,
|
| 62 |
+
lead=lead,
|
| 63 |
+
user_message=user_message,
|
| 64 |
+
stage=current_stage
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
# 3. MEMORY RETRIEVAL (The "Big Brain")
|
| 68 |
+
memory_manager = get_memory_manager()
|
| 69 |
+
cache_name = await memory_manager.get_valid_memory(session, tenant)
|
| 70 |
+
|
| 71 |
+
# 4. DYNAMIC CONTEXT (Things that change per request)
|
| 72 |
+
dynamic_context = f"""
|
| 73 |
+
[CURRENT CONTEXT - {datetime.now().strftime("%Y-%m-%d %H:%M")}]
|
| 74 |
+
User Name: {lead.name or 'Unknown'}
|
| 75 |
+
Psychotype: {lead.psychotype} (Adapt tone accordingly)
|
| 76 |
+
Funnel Stage: {current_stage.name if current_stage else 'General'}
|
| 77 |
+
Goal: {current_stage.ai_goal if current_stage else 'Assist user'}
|
| 78 |
+
|
| 79 |
+
[BOOKING AVAILABILITY]
|
| 80 |
+
{booking_context if booking_context else "No specific slots needed yet."}
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
# 5. Format conversation history
|
| 84 |
+
chat_history = format_chat_history(conversation_history)
|
| 85 |
+
|
| 86 |
+
# 6. Generate response utilizing CACHE or FALLBACK
|
| 87 |
+
final_system_instruction = dynamic_context
|
| 88 |
+
|
| 89 |
+
if not cache_name:
|
| 90 |
+
# FALLBACK: Memory Creation Failed (Quota/Auth) -> Inject Manually
|
| 91 |
+
print("⚠️ Memory Cache missing/failed. Injecting full context manually (Standard RAG).")
|
| 92 |
+
full_static_context = await memory_manager.build_tenant_context(session, tenant)
|
| 93 |
+
final_system_instruction = full_static_context + "\n\n" + dynamic_context
|
| 94 |
+
|
| 95 |
+
response = await ai_core.llm.generate_response(
|
| 96 |
+
prompt=user_message,
|
| 97 |
+
system_instruction=final_system_instruction,
|
| 98 |
+
context=cache_name, # THE CACHE KEY (or None)
|
| 99 |
+
chat_history=chat_history
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
"text": response["text"],
|
| 104 |
+
"prompt_tokens": response["prompt_tokens"],
|
| 105 |
+
"completion_tokens": response["completion_tokens"],
|
| 106 |
+
"total_tokens": response["total_tokens"],
|
| 107 |
+
"rag_context_used": False, # Deprecated with Caching
|
| 108 |
+
"products_found": True, # Assumed in Cache
|
| 109 |
+
"scripts_used": 0 # Hidden in Cache
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ============================================================================
|
| 114 |
+
# Chat History Formatting
|
| 115 |
+
# ============================================================================
|
| 116 |
+
|
| 117 |
+
def format_chat_history(messages: List[Message]) -> List[Dict[str, Any]]:
|
| 118 |
+
"""
|
| 119 |
+
Format messages for Gemini chat history.
|
| 120 |
+
|
| 121 |
+
CRITICAL FIX: Include ALL message types (user, ai, human).
|
| 122 |
+
- user -> role="user"
|
| 123 |
+
- ai/human -> role="model" (both are bot responses from user's perspective)
|
| 124 |
+
"""
|
| 125 |
+
history = []
|
| 126 |
+
|
| 127 |
+
# DEBUG: Print message types being formatted
|
| 128 |
+
msg_types = [msg.sender_type for msg in messages]
|
| 129 |
+
print(f"🔍 Formatting {len(messages)} messages: {msg_types}")
|
| 130 |
+
|
| 131 |
+
for msg in messages[:-1]: # Exclude last message (it's the current prompt)
|
| 132 |
+
# Map sender_type to Gemini role
|
| 133 |
+
if msg.sender_type == "user":
|
| 134 |
+
role = "user"
|
| 135 |
+
else: # ai or human (both are bot from user's perspective)
|
| 136 |
+
role = "model"
|
| 137 |
+
|
| 138 |
+
history.append({
|
| 139 |
+
"role": role,
|
| 140 |
+
"content": msg.content
|
| 141 |
+
})
|
| 142 |
+
|
| 143 |
+
print(f"✅ Chat history formatted: {len(history)} messages for Gemini")
|
| 144 |
+
return history
|
backend/app/services/ai_core/types.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AI Core Types and Common Imports
|
| 3 |
+
|
| 4 |
+
Shared types and imports for the AI Core module.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import List, Dict, Any, Optional, TYPE_CHECKING
|
| 8 |
+
from uuid import UUID
|
| 9 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 10 |
+
|
| 11 |
+
# Re-export common types for convenience
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from app.models.lead import Lead, Message, Psychotype, LeadHeat
|
| 14 |
+
from app.models.tenant import Tenant
|
| 15 |
+
from app.models.sales_stage import SalesStage
|
| 16 |
+
from app.models.ai_training import AITrainingExample, AILearningRule
|
| 17 |
+
from app.models.booking import Service
|
| 18 |
+
|
| 19 |
+
# Type aliases for cleaner signatures
|
| 20 |
+
ConversationHistory = List["Message"]
|
| 21 |
+
SummaryDict = Dict[str, Any]
|
backend/app/services/{ai_core.py → ai_core_legacy.py}
RENAMED
|
File without changes
|
backend/app/services/whatsapp_qr.py
DELETED
|
@@ -1,4 +0,0 @@
|
|
| 1 |
-
"""
|
| 2 |
-
DEPRECATED: WhatsApp QR (Evolution API) service has been removed.
|
| 3 |
-
Please use app.services.meta_whatsapp.WhatsAppCloudService instead.
|
| 4 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
backend/tests/test_evolution_webhook.py
DELETED
|
@@ -1,122 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
import pytest
|
| 3 |
-
from fastapi.testclient import TestClient
|
| 4 |
-
from unittest.mock import patch, MagicMock
|
| 5 |
-
from app.main import app
|
| 6 |
-
|
| 7 |
-
client = TestClient(app)
|
| 8 |
-
|
| 9 |
-
# Mock data
|
| 10 |
-
MOCK_TEXT_MESSAGE = {
|
| 11 |
-
"event": "messages.upsert",
|
| 12 |
-
"instance": "instance_name",
|
| 13 |
-
"data": {
|
| 14 |
-
"key": {
|
| 15 |
-
"remoteJid": "1234567890@s.whatsapp.net",
|
| 16 |
-
"fromMe": False,
|
| 17 |
-
"id": "MESSAGE_ID"
|
| 18 |
-
},
|
| 19 |
-
"pushName": "Test User",
|
| 20 |
-
"message": {
|
| 21 |
-
"conversation": "Hello world"
|
| 22 |
-
},
|
| 23 |
-
"messageType": "conversation"
|
| 24 |
-
},
|
| 25 |
-
"sender": "1234567890@s.whatsapp.net"
|
| 26 |
-
}
|
| 27 |
-
|
| 28 |
-
MOCK_EXTENDED_MESSAGE = {
|
| 29 |
-
"event": "messages.upsert",
|
| 30 |
-
"instance": "instance_name",
|
| 31 |
-
"data": {
|
| 32 |
-
"key": {
|
| 33 |
-
"remoteJid": "1234567890@s.whatsapp.net",
|
| 34 |
-
"fromMe": False,
|
| 35 |
-
"id": "MESSAGE_ID"
|
| 36 |
-
},
|
| 37 |
-
"pushName": "Test User",
|
| 38 |
-
"message": {
|
| 39 |
-
"extendedTextMessage": {
|
| 40 |
-
"text": "Hello extended"
|
| 41 |
-
}
|
| 42 |
-
},
|
| 43 |
-
"messageType": "extendedTextMessage"
|
| 44 |
-
},
|
| 45 |
-
"sender": "1234567890@s.whatsapp.net"
|
| 46 |
-
}
|
| 47 |
-
|
| 48 |
-
@pytest.fixture
|
| 49 |
-
def mock_process_message():
|
| 50 |
-
with patch("app.api.evolution_webhook.process_meta_message") as mock:
|
| 51 |
-
yield mock
|
| 52 |
-
|
| 53 |
-
def test_evolution_webhook_text_message(mock_process_message):
|
| 54 |
-
"""Test processing of a simple text message."""
|
| 55 |
-
# Mock the Tenant query to return a tenant with matching instance/config if needed
|
| 56 |
-
# For now, assuming the webhook handler extracts tenant_id from URL or similar
|
| 57 |
-
# In the implementation, the webhook URL is /api/v1/webhook/evolution/{tenant_id}
|
| 58 |
-
|
| 59 |
-
tenant_id = "test-tenant-id"
|
| 60 |
-
|
| 61 |
-
response = client.post(
|
| 62 |
-
f"/api/v1/webhook/evolution/{tenant_id}",
|
| 63 |
-
json=MOCK_TEXT_MESSAGE,
|
| 64 |
-
headers={"apikey": "test-api-key"} # Assuming some auth or just open for now based on implementation
|
| 65 |
-
)
|
| 66 |
-
|
| 67 |
-
assert response.status_code == 200
|
| 68 |
-
assert response.json() == {"status": "ok"}
|
| 69 |
-
|
| 70 |
-
# Verify process_meta_message was called with correct arguments
|
| 71 |
-
mock_process_message.assert_called_once()
|
| 72 |
-
call_args = mock_process_message.call_args
|
| 73 |
-
assert call_args[0][0] == tenant_id
|
| 74 |
-
assert call_args[0][1] == "1234567890" # Phone number extracted
|
| 75 |
-
assert call_args[0][2] == "Hello world" # Text extracted
|
| 76 |
-
assert call_args[0][3] == "Test User" # Name extracted
|
| 77 |
-
assert call_args[0][4] == "whatsapp" # Channel
|
| 78 |
-
|
| 79 |
-
def test_evolution_webhook_extended_message(mock_process_message):
|
| 80 |
-
"""Test processing of an extended text message."""
|
| 81 |
-
tenant_id = "test-tenant-id"
|
| 82 |
-
|
| 83 |
-
response = client.post(
|
| 84 |
-
f"/api/v1/webhook/evolution/{tenant_id}",
|
| 85 |
-
json=MOCK_EXTENDED_MESSAGE
|
| 86 |
-
)
|
| 87 |
-
|
| 88 |
-
assert response.status_code == 200
|
| 89 |
-
|
| 90 |
-
mock_process_message.assert_called_once()
|
| 91 |
-
call_args = mock_process_message.call_args
|
| 92 |
-
assert call_args[0][2] == "Hello extended"
|
| 93 |
-
|
| 94 |
-
def test_evolution_webhook_from_me(mock_process_message):
|
| 95 |
-
"""Test that messages from me are ignored."""
|
| 96 |
-
tenant_id = "test-tenant-id"
|
| 97 |
-
|
| 98 |
-
payload = MOCK_TEXT_MESSAGE.copy()
|
| 99 |
-
payload["data"]["key"]["fromMe"] = True
|
| 100 |
-
|
| 101 |
-
response = client.post(
|
| 102 |
-
f"/api/v1/webhook/evolution/{tenant_id}",
|
| 103 |
-
json=payload
|
| 104 |
-
)
|
| 105 |
-
|
| 106 |
-
assert response.status_code == 200
|
| 107 |
-
mock_process_message.assert_not_called()
|
| 108 |
-
|
| 109 |
-
def test_evolution_webhook_invalid_event(mock_process_message):
|
| 110 |
-
"""Test that non-message events are ignored."""
|
| 111 |
-
tenant_id = "test-tenant-id"
|
| 112 |
-
|
| 113 |
-
payload = MOCK_TEXT_MESSAGE.copy()
|
| 114 |
-
payload["event"] = "presence.update"
|
| 115 |
-
|
| 116 |
-
response = client.post(
|
| 117 |
-
f"/api/v1/webhook/evolution/{tenant_id}",
|
| 118 |
-
json=payload
|
| 119 |
-
)
|
| 120 |
-
|
| 121 |
-
assert response.status_code == 200
|
| 122 |
-
mock_process_message.assert_not_called()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
frontend/components/ChatWindow.tsx
CHANGED
|
@@ -1,15 +1,24 @@
|
|
| 1 |
'use client'
|
| 2 |
|
| 3 |
import { useState, useRef, useEffect } from 'react'
|
| 4 |
-
import { Message, Lead, leadsApi
|
| 5 |
-
import {
|
| 6 |
-
import {
|
| 7 |
|
| 8 |
import { ClientCard } from './ClientCard'
|
| 9 |
import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'
|
| 10 |
-
import { motion, AnimatePresence } from 'framer-motion'
|
| 11 |
import { BookingModal } from '@/components/bookings/BookingModal'
|
| 12 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
interface ChatWindowProps {
|
| 14 |
messages: Message[]
|
| 15 |
leadId?: string
|
|
@@ -26,19 +35,68 @@ interface ChatWindowProps {
|
|
| 26 |
isLeadsListOpen?: boolean
|
| 27 |
}
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
const [inputMessage, setInputMessage] = useState('')
|
| 31 |
-
const messagesEndRef = useRef<HTMLDivElement>(null)
|
| 32 |
const [isSending, setIsSending] = useState(false)
|
| 33 |
const [optimisticMessages, setOptimisticMessages] = useState<Message[]>([])
|
| 34 |
-
|
| 35 |
-
// Stages logic removed
|
| 36 |
const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false)
|
| 37 |
-
|
| 38 |
const [isTogglingAI, setIsTogglingAI] = useState(false)
|
| 39 |
-
const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])
|
| 40 |
const [isBookingModalOpen, setIsBookingModalOpen] = useState(false)
|
| 41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
const scrollToBottom = () => {
|
| 43 |
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
| 44 |
}
|
|
@@ -47,11 +105,21 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 47 |
scrollToBottom()
|
| 48 |
}, [messages, optimisticMessages, realtimeMessages, isAnalyzing])
|
| 49 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
-
|
| 52 |
-
/
|
| 53 |
-
|
| 54 |
-
/* Stage click handler removed */
|
| 55 |
|
| 56 |
const handleToggleAI = async () => {
|
| 57 |
if (!leadId || isTogglingAI) return
|
|
@@ -83,18 +151,6 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 83 |
}
|
| 84 |
}
|
| 85 |
|
| 86 |
-
useEffect(() => {
|
| 87 |
-
if (!leadId || !tenantId || !isRealtimeEnabled()) return
|
| 88 |
-
setRealtimeMessages([])
|
| 89 |
-
const unsubscribe = subscribeToMessages(conversationId || '', (newMessage) => {
|
| 90 |
-
setRealtimeMessages(prev => {
|
| 91 |
-
if (prev.some(m => m.id === newMessage.id)) return prev
|
| 92 |
-
return [...prev, newMessage]
|
| 93 |
-
})
|
| 94 |
-
})
|
| 95 |
-
return () => { unsubscribe() }
|
| 96 |
-
}, [leadId, tenantId])
|
| 97 |
-
|
| 98 |
const handleSendMessage = async (e: React.FormEvent) => {
|
| 99 |
e.preventDefault()
|
| 100 |
if (!inputMessage.trim() || !leadId || !conversationId) return
|
|
@@ -113,7 +169,6 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 113 |
setIsSending(true)
|
| 114 |
|
| 115 |
try {
|
| 116 |
-
// @ts-ignore
|
| 117 |
await leadsApi.sendMessage(leadId, conversationId, inputMessage)
|
| 118 |
setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))
|
| 119 |
} catch (error) {
|
|
@@ -125,115 +180,25 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 125 |
}
|
| 126 |
}
|
| 127 |
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
)
|
| 132 |
-
.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())
|
| 133 |
-
|
| 134 |
-
const isAIActive = !conversation?.human_takeover
|
| 135 |
-
|
| 136 |
-
// Helper to check if we should show date separator
|
| 137 |
-
const shouldShowDateSeparator = (currentMsg: Message, prevMsg: Message | null) => {
|
| 138 |
-
if (!prevMsg) return true
|
| 139 |
-
const currentDate = new Date(currentMsg.created_at).toDateString()
|
| 140 |
-
const prevDate = new Date(prevMsg.created_at).toDateString()
|
| 141 |
-
return currentDate !== prevDate
|
| 142 |
-
}
|
| 143 |
-
|
| 144 |
-
// Helper to format date separator
|
| 145 |
-
const getDateLabel = (dateString: string) => {
|
| 146 |
-
const date = new Date(dateString)
|
| 147 |
-
const today = new Date()
|
| 148 |
-
const yesterday = new Date(today)
|
| 149 |
-
yesterday.setDate(yesterday.getDate() - 1)
|
| 150 |
-
|
| 151 |
-
if (date.toDateString() === today.toDateString()) return 'Сегодня'
|
| 152 |
-
if (date.toDateString() === yesterday.toDateString()) return 'Вчера'
|
| 153 |
-
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })
|
| 154 |
-
}
|
| 155 |
|
| 156 |
return (
|
| 157 |
<div className="flex flex-col h-full bg-[#0D0E18] font-['Inter'] relative">
|
| 158 |
{/* Header */}
|
| 159 |
-
<
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
<ArrowLeft className="w-5 h-5" />
|
| 172 |
-
</button>
|
| 173 |
-
|
| 174 |
-
<div className="flex items-center gap-3">
|
| 175 |
-
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-600/30 to-purple-600/30 flex items-center justify-center text-indigo-400 font-bold text-sm border border-indigo-500/30 relative shadow-sm">
|
| 176 |
-
{lead?.name?.charAt(0) || 'L'}
|
| 177 |
-
<div className={cn(
|
| 178 |
-
"absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-white",
|
| 179 |
-
lead?.heat_level === 'HOT' ? "bg-red-500" :
|
| 180 |
-
lead?.heat_level === 'WARM' ? "bg-amber-500" :
|
| 181 |
-
"bg-blue-500"
|
| 182 |
-
)} />
|
| 183 |
-
</div>
|
| 184 |
-
<div>
|
| 185 |
-
<h2 className="font-bold text-white text-sm">{lead?.name || 'Лид'}</h2>
|
| 186 |
-
<div className="flex items-center gap-2">
|
| 187 |
-
<span className="text-xs text-slate-400 font-medium">{(lead as any)?.channel_source || 'Неизвестно'}</span>
|
| 188 |
-
{isAnalyzing && (
|
| 189 |
-
<span className="flex items-center gap-1 text-[10px] text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full animate-pulse border border-indigo-100 font-semibold">
|
| 190 |
-
<Sparkles className="w-3 h-3" />
|
| 191 |
-
AI думает...
|
| 192 |
-
</span>
|
| 193 |
-
)}
|
| 194 |
-
</div>
|
| 195 |
-
</div>
|
| 196 |
-
</div>
|
| 197 |
-
</div>
|
| 198 |
-
|
| 199 |
-
<div className="flex items-center gap-3">
|
| 200 |
-
<button
|
| 201 |
-
onClick={() => setIsBookingModalOpen(true)}
|
| 202 |
-
className="hidden md:flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold bg-white/5 text-slate-300 border border-white/10 hover:bg-white/10 transition-all"
|
| 203 |
-
title="Записать на встречу"
|
| 204 |
-
>
|
| 205 |
-
<Calendar className="w-3.5 h-3.5 text-slate-500" />
|
| 206 |
-
Записать
|
| 207 |
-
</button>
|
| 208 |
-
|
| 209 |
-
<button
|
| 210 |
-
onClick={handleToggleAI}
|
| 211 |
-
disabled={isTogglingAI}
|
| 212 |
-
className={cn(
|
| 213 |
-
"flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all duration-200 border shadow-sm",
|
| 214 |
-
isAIActive
|
| 215 |
-
? "bg-indigo-500/20 text-indigo-300 border-indigo-500/30 hover:bg-indigo-500/30"
|
| 216 |
-
: "bg-white/5 text-slate-400 border-white/10 hover:bg-white/10"
|
| 217 |
-
)}
|
| 218 |
-
>
|
| 219 |
-
{isTogglingAI ? (
|
| 220 |
-
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
| 221 |
-
) : (
|
| 222 |
-
<Bot className={cn("w-3.5 h-3.5", isAIActive ? "text-indigo-600" : "text-slate-400")} />
|
| 223 |
-
)}
|
| 224 |
-
{isAIActive ? 'AI Активен' : 'AI Отключен'}
|
| 225 |
-
</button>
|
| 226 |
-
|
| 227 |
-
<button
|
| 228 |
-
onClick={() => setIsMobileDrawerOpen(true)}
|
| 229 |
-
className="md:hidden p-2 text-slate-400 hover:text-slate-600"
|
| 230 |
-
>
|
| 231 |
-
<Info className="w-5 h-5" />
|
| 232 |
-
</button>
|
| 233 |
-
</div>
|
| 234 |
-
</div>
|
| 235 |
-
|
| 236 |
-
|
| 237 |
|
| 238 |
{/* Messages Area */}
|
| 239 |
<div className="flex-1 overflow-y-auto p-6 space-y-6 bg-[#0D0E18] scrollbar-thin scrollbar-thumb-white/10">
|
|
@@ -252,215 +217,71 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 252 |
) : (
|
| 253 |
<>
|
| 254 |
{allMessages.map((msg, index) => {
|
| 255 |
-
// Logic:
|
| 256 |
-
// 'human' -> Agent (Me) -> Right
|
| 257 |
-
// 'ai' -> Agent (Bot) -> Right
|
| 258 |
-
// 'lead' / 'user' (anything else) -> Lead -> Left
|
| 259 |
-
|
| 260 |
-
// NOTE: We need to be sure about 'sender_type'.
|
| 261 |
-
// Usually in this app: 'human' = Operator, 'ai' = Bot.
|
| 262 |
-
// The 'lead' messages usually have sender_type = 'lead' or 'user'.
|
| 263 |
-
// Let's assume anything NOT 'human' and NOT 'ai' is the Lead.
|
| 264 |
-
|
| 265 |
const isMe = msg.sender_type === 'human' || msg.sender_type === 'ai'
|
| 266 |
const isAI = msg.sender_type === 'ai'
|
| 267 |
-
|
| 268 |
const prevMsg = index > 0 ? allMessages[index - 1] : null
|
| 269 |
const showDate = shouldShowDateSeparator(msg, prevMsg)
|
| 270 |
|
| 271 |
-
// Group if same side and no date separator
|
| 272 |
const isSequence = prevMsg &&
|
| 273 |
((isMe && (prevMsg.sender_type === 'human' || prevMsg.sender_type === 'ai')) ||
|
| 274 |
(!isMe && (prevMsg.sender_type !== 'human' && prevMsg.sender_type !== 'ai'))) &&
|
| 275 |
!showDate
|
| 276 |
|
| 277 |
return (
|
| 278 |
-
<
|
| 279 |
-
{
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
)}
|
| 286 |
-
|
| 287 |
-
<motion.div
|
| 288 |
-
initial={{ opacity: 0, y: 10 }}
|
| 289 |
-
animate={{ opacity: 1, y: 0 }}
|
| 290 |
-
transition={{ duration: 0.3 }}
|
| 291 |
-
className={cn(
|
| 292 |
-
"flex w-full max-w-3xl mx-auto group",
|
| 293 |
-
isMe ? "justify-end" : "justify-start",
|
| 294 |
-
isSequence ? "mt-1" : "mt-4"
|
| 295 |
-
)}
|
| 296 |
-
>
|
| 297 |
-
<div className={cn(
|
| 298 |
-
"flex gap-3 max-w-[75%]",
|
| 299 |
-
isMe ? "flex-row-reverse" : "flex-row"
|
| 300 |
-
)}>
|
| 301 |
-
{/* Avatar */}
|
| 302 |
-
<div className={cn(
|
| 303 |
-
"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-auto mb-1 transition-opacity",
|
| 304 |
-
isMe ? "bg-indigo-600 text-white" : "bg-[#12131F] text-slate-400 border border-white/10",
|
| 305 |
-
isSequence ? "opacity-0 w-0 overflow-hidden ml-0 mr-0" : "opacity-100"
|
| 306 |
-
)}>
|
| 307 |
-
{isMe ? (isAI ? <Bot className="w-4 h-4" /> : <User className="w-4 h-4" />) : <User className="w-4 h-4" />}
|
| 308 |
-
</div>
|
| 309 |
-
|
| 310 |
-
{/* Message Bubble */}
|
| 311 |
-
<div className="flex flex-col gap-1 min-w-0">
|
| 312 |
-
{/* Optional Subject for Email (could be passed in content or metadata) */}
|
| 313 |
-
<div className={cn(
|
| 314 |
-
"px-4 py-2.5 text-sm leading-relaxed shadow-sm relative break-words",
|
| 315 |
-
isMe
|
| 316 |
-
? "bg-gradient-to-r from-indigo-600 to-violet-600 text-white rounded-2xl rounded-br-none shadow-[0_4px_15px_-3px_rgba(99,102,241,0.3)]"
|
| 317 |
-
: "bg-[#1E2030] text-slate-200 border border-white/5 rounded-2xl rounded-bl-none",
|
| 318 |
-
isSequence && isMe && "rounded-tr-md rounded-br-md",
|
| 319 |
-
isSequence && !isMe && "rounded-tl-md rounded-bl-md"
|
| 320 |
-
)}>
|
| 321 |
-
{msg.content}
|
| 322 |
-
|
| 323 |
-
{/* Channel Micro-Indicator for Merged View (if needed) */}
|
| 324 |
-
{/*
|
| 325 |
-
{!isMe && (
|
| 326 |
-
<div className="absolute -top-2 -left-2 bg-white rounded-full p-0.5 shadow-sm border border-slate-100">
|
| 327 |
-
<Mail className="w-2 h-2 text-blue-500" />
|
| 328 |
-
</div>
|
| 329 |
-
)}
|
| 330 |
-
*/}
|
| 331 |
-
</div>
|
| 332 |
-
{!isSequence && (
|
| 333 |
-
<span className={cn(
|
| 334 |
-
"text-[10px] text-slate-400 px-1 flex items-center gap-1",
|
| 335 |
-
isMe ? "justify-end text-right" : "justify-start text-left"
|
| 336 |
-
)}>
|
| 337 |
-
{formatDate(msg.created_at)}
|
| 338 |
-
{/* Read Receipt or Channel Icon could go here */}
|
| 339 |
-
</span>
|
| 340 |
-
)}
|
| 341 |
-
</div>
|
| 342 |
-
</div>
|
| 343 |
-
</motion.div>
|
| 344 |
-
</div>
|
| 345 |
)
|
| 346 |
})}
|
| 347 |
|
| 348 |
-
{
|
| 349 |
-
<AnimatePresence>
|
| 350 |
-
{isAnalyzing && (
|
| 351 |
-
<motion.div
|
| 352 |
-
initial={{ opacity: 0, y: 10 }}
|
| 353 |
-
animate={{ opacity: 1, y: 0 }}
|
| 354 |
-
exit={{ opacity: 0, scale: 0.9 }}
|
| 355 |
-
className="flex w-full max-w-3xl mx-auto justify-end mt-4"
|
| 356 |
-
>
|
| 357 |
-
<div className="flex gap-3 flex-row-reverse">
|
| 358 |
-
<div className="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center flex-shrink-0 shadow-sm mt-auto mb-1">
|
| 359 |
-
<Bot className="w-4 h-4" />
|
| 360 |
-
</div>
|
| 361 |
-
<div className="bg-indigo-600 text-white px-4 py-3 rounded-2xl rounded-br-none shadow-sm flex items-center gap-1">
|
| 362 |
-
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce [animation-delay:-0.3s]"></span>
|
| 363 |
-
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce [animation-delay:-0.15s]"></span>
|
| 364 |
-
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce"></span>
|
| 365 |
-
</div>
|
| 366 |
-
</div>
|
| 367 |
-
</motion.div>
|
| 368 |
-
)}
|
| 369 |
-
</AnimatePresence>
|
| 370 |
</>
|
| 371 |
)}
|
| 372 |
<div ref={messagesEndRef} />
|
| 373 |
</div>
|
| 374 |
|
| 375 |
-
{/* Input Area
|
| 376 |
-
<
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
| 403 |
-
|
| 404 |
-
<button
|
| 405 |
-
type="button"
|
| 406 |
-
className="p-2.5 text-slate-500 hover:text-indigo-400 hover:bg-white/5 rounded-xl transition-colors"
|
| 407 |
-
>
|
| 408 |
-
<Smile className="w-5 h-5" />
|
| 409 |
-
</button>
|
| 410 |
-
|
| 411 |
-
<button
|
| 412 |
-
type="submit"
|
| 413 |
-
disabled={!inputMessage.trim() || isSending}
|
| 414 |
-
className={cn(
|
| 415 |
-
"p-2.5 rounded-xl transition-all duration-200 shadow-sm",
|
| 416 |
-
(inputMessage.trim() && !isSending)
|
| 417 |
-
? "bg-indigo-600 text-white hover:bg-indigo-500 hover:scale-105 active:scale-95"
|
| 418 |
-
: "bg-white/5 text-slate-500 cursor-not-allowed"
|
| 419 |
-
)}
|
| 420 |
-
>
|
| 421 |
-
{isSending ? (
|
| 422 |
-
<Loader2 className="w-5 h-5 animate-spin" />
|
| 423 |
-
) : (
|
| 424 |
-
<Send className="w-5 h-5" />
|
| 425 |
)}
|
| 426 |
-
</button>
|
| 427 |
-
</form>
|
| 428 |
-
<div className="text-center mt-2">
|
| 429 |
-
<p className="text-[10px] text-slate-400 font-medium">
|
| 430 |
-
Enter для отправки • Shift + Enter для переноса
|
| 431 |
-
</p>
|
| 432 |
-
</div>
|
| 433 |
-
</div>
|
| 434 |
-
</div>
|
| 435 |
-
|
| 436 |
-
{
|
| 437 |
-
isMobileDrawerOpen && (
|
| 438 |
-
<div className="fixed inset-0 z-50 md:hidden">
|
| 439 |
-
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setIsMobileDrawerOpen(false)} />
|
| 440 |
-
<div className="absolute right-0 top-0 bottom-0 w-[85%] bg-[#12131F] shadow-2xl animate-in slide-in-from-right duration-300">
|
| 441 |
-
<div className="p-4 border-b border-white/10 flex items-center justify-between">
|
| 442 |
-
<h3 className="font-bold text-white">Инфо о лиде</h3>
|
| 443 |
-
<button onClick={() => setIsMobileDrawerOpen(false)} className="p-2 hover:bg-white/10 rounded-full">
|
| 444 |
-
<X className="w-5 h-5 text-slate-400" />
|
| 445 |
-
</button>
|
| 446 |
-
</div>
|
| 447 |
-
<div className="h-full overflow-y-auto pb-20">
|
| 448 |
-
{lead && (
|
| 449 |
-
<ClientCard
|
| 450 |
-
lead={lead}
|
| 451 |
-
onTakeover={onTakeover || (() => { })}
|
| 452 |
-
isAnalyzing={isAnalyzing}
|
| 453 |
-
onRefresh={onRefresh || (() => { })}
|
| 454 |
-
conversationId={conversationId}
|
| 455 |
-
tenantId={tenantId}
|
| 456 |
-
/>
|
| 457 |
-
)}
|
| 458 |
-
</div>
|
| 459 |
</div>
|
| 460 |
</div>
|
| 461 |
-
|
| 462 |
-
}
|
| 463 |
|
|
|
|
| 464 |
<AnimatePresence>
|
| 465 |
{isBookingModalOpen && leadId && (
|
| 466 |
<BookingModal
|
|
@@ -471,6 +292,6 @@ export function ChatWindow({ messages, leadId, tenantId, conversationId, lead, c
|
|
| 471 |
/>
|
| 472 |
)}
|
| 473 |
</AnimatePresence>
|
| 474 |
-
</div
|
| 475 |
)
|
| 476 |
}
|
|
|
|
| 1 |
'use client'
|
| 2 |
|
| 3 |
import { useState, useRef, useEffect } from 'react'
|
| 4 |
+
import { Message, Lead, leadsApi } from '@/lib/api'
|
| 5 |
+
import { Bot, Loader2, X } from 'lucide-react'
|
| 6 |
+
import { AnimatePresence } from 'framer-motion'
|
| 7 |
|
| 8 |
import { ClientCard } from './ClientCard'
|
| 9 |
import { subscribeToMessages, isRealtimeEnabled } from '@/lib/supabaseClient'
|
|
|
|
| 10 |
import { BookingModal } from '@/components/bookings/BookingModal'
|
| 11 |
|
| 12 |
+
// Import refactored sub-components
|
| 13 |
+
import { ChatHeader } from './ChatWindow/ChatHeader'
|
| 14 |
+
import { MessageBubble } from './ChatWindow/MessageBubble'
|
| 15 |
+
import { MessageInput } from './ChatWindow/MessageInput'
|
| 16 |
+
import { TypingIndicator } from './ChatWindow/TypingIndicator'
|
| 17 |
+
|
| 18 |
+
// ============================================================================
|
| 19 |
+
// Types
|
| 20 |
+
// ============================================================================
|
| 21 |
+
|
| 22 |
interface ChatWindowProps {
|
| 23 |
messages: Message[]
|
| 24 |
leadId?: string
|
|
|
|
| 35 |
isLeadsListOpen?: boolean
|
| 36 |
}
|
| 37 |
|
| 38 |
+
// ============================================================================
|
| 39 |
+
// Helper Functions
|
| 40 |
+
// ============================================================================
|
| 41 |
+
|
| 42 |
+
function shouldShowDateSeparator(currentMsg: Message, prevMsg: Message | null): boolean {
|
| 43 |
+
if (!prevMsg) return true
|
| 44 |
+
const currentDate = new Date(currentMsg.created_at).toDateString()
|
| 45 |
+
const prevDate = new Date(prevMsg.created_at).toDateString()
|
| 46 |
+
return currentDate !== prevDate
|
| 47 |
+
}
|
| 48 |
+
|
| 49 |
+
function getDateLabel(dateString: string): string {
|
| 50 |
+
const date = new Date(dateString)
|
| 51 |
+
const today = new Date()
|
| 52 |
+
const yesterday = new Date(today)
|
| 53 |
+
yesterday.setDate(yesterday.getDate() - 1)
|
| 54 |
+
|
| 55 |
+
if (date.toDateString() === today.toDateString()) return 'Сегодня'
|
| 56 |
+
if (date.toDateString() === yesterday.toDateString()) return 'Вчера'
|
| 57 |
+
return date.toLocaleDateString('ru-RU', { day: 'numeric', month: 'long' })
|
| 58 |
+
}
|
| 59 |
+
|
| 60 |
+
// ============================================================================
|
| 61 |
+
// Main Component
|
| 62 |
+
// ============================================================================
|
| 63 |
+
|
| 64 |
+
export function ChatWindow({
|
| 65 |
+
messages,
|
| 66 |
+
leadId,
|
| 67 |
+
tenantId,
|
| 68 |
+
conversationId,
|
| 69 |
+
lead,
|
| 70 |
+
conversation,
|
| 71 |
+
isLoading,
|
| 72 |
+
isAnalyzing,
|
| 73 |
+
onRefresh,
|
| 74 |
+
onTakeover,
|
| 75 |
+
onBack,
|
| 76 |
+
onToggleLeadsList,
|
| 77 |
+
isLeadsListOpen,
|
| 78 |
+
}: ChatWindowProps) {
|
| 79 |
+
// State
|
| 80 |
const [inputMessage, setInputMessage] = useState('')
|
|
|
|
| 81 |
const [isSending, setIsSending] = useState(false)
|
| 82 |
const [optimisticMessages, setOptimisticMessages] = useState<Message[]>([])
|
| 83 |
+
const [realtimeMessages, setRealtimeMessages] = useState<Message[]>([])
|
|
|
|
| 84 |
const [isMobileDrawerOpen, setIsMobileDrawerOpen] = useState(false)
|
|
|
|
| 85 |
const [isTogglingAI, setIsTogglingAI] = useState(false)
|
|
|
|
| 86 |
const [isBookingModalOpen, setIsBookingModalOpen] = useState(false)
|
| 87 |
|
| 88 |
+
const messagesEndRef = useRef<HTMLDivElement>(null)
|
| 89 |
+
|
| 90 |
+
// Computed values
|
| 91 |
+
const isAIActive = !conversation?.human_takeover
|
| 92 |
+
const allMessages = [...messages, ...optimisticMessages, ...realtimeMessages]
|
| 93 |
+
.filter((msg, index, self) => index === self.findIndex((t) => t.id === msg.id))
|
| 94 |
+
.sort((a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime())
|
| 95 |
+
|
| 96 |
+
// ============================================================================
|
| 97 |
+
// Effects
|
| 98 |
+
// ============================================================================
|
| 99 |
+
|
| 100 |
const scrollToBottom = () => {
|
| 101 |
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })
|
| 102 |
}
|
|
|
|
| 105 |
scrollToBottom()
|
| 106 |
}, [messages, optimisticMessages, realtimeMessages, isAnalyzing])
|
| 107 |
|
| 108 |
+
useEffect(() => {
|
| 109 |
+
if (!leadId || !tenantId || !isRealtimeEnabled()) return
|
| 110 |
+
setRealtimeMessages([])
|
| 111 |
+
const unsubscribe = subscribeToMessages(conversationId || '', (newMessage) => {
|
| 112 |
+
setRealtimeMessages(prev => {
|
| 113 |
+
if (prev.some(m => m.id === newMessage.id)) return prev
|
| 114 |
+
return [...prev, newMessage]
|
| 115 |
+
})
|
| 116 |
+
})
|
| 117 |
+
return () => { unsubscribe() }
|
| 118 |
+
}, [leadId, tenantId, conversationId])
|
| 119 |
|
| 120 |
+
// ============================================================================
|
| 121 |
+
// Handlers
|
| 122 |
+
// ============================================================================
|
|
|
|
| 123 |
|
| 124 |
const handleToggleAI = async () => {
|
| 125 |
if (!leadId || isTogglingAI) return
|
|
|
|
| 151 |
}
|
| 152 |
}
|
| 153 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 154 |
const handleSendMessage = async (e: React.FormEvent) => {
|
| 155 |
e.preventDefault()
|
| 156 |
if (!inputMessage.trim() || !leadId || !conversationId) return
|
|
|
|
| 169 |
setIsSending(true)
|
| 170 |
|
| 171 |
try {
|
|
|
|
| 172 |
await leadsApi.sendMessage(leadId, conversationId, inputMessage)
|
| 173 |
setOptimisticMessages(prev => prev.filter(m => m.id !== tempId))
|
| 174 |
} catch (error) {
|
|
|
|
| 180 |
}
|
| 181 |
}
|
| 182 |
|
| 183 |
+
// ============================================================================
|
| 184 |
+
// Render
|
| 185 |
+
// ============================================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
|
| 187 |
return (
|
| 188 |
<div className="flex flex-col h-full bg-[#0D0E18] font-['Inter'] relative">
|
| 189 |
{/* Header */}
|
| 190 |
+
<ChatHeader
|
| 191 |
+
lead={lead}
|
| 192 |
+
isAnalyzing={isAnalyzing}
|
| 193 |
+
isAIActive={isAIActive}
|
| 194 |
+
isTogglingAI={isTogglingAI}
|
| 195 |
+
isLeadsListOpen={isLeadsListOpen}
|
| 196 |
+
onToggleLeadsList={onToggleLeadsList}
|
| 197 |
+
onBack={onBack}
|
| 198 |
+
onToggleAI={handleToggleAI}
|
| 199 |
+
onOpenMobileDrawer={() => setIsMobileDrawerOpen(true)}
|
| 200 |
+
onOpenBookingModal={() => setIsBookingModalOpen(true)}
|
| 201 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
{/* Messages Area */}
|
| 204 |
<div className="flex-1 overflow-y-auto p-6 space-y-6 bg-[#0D0E18] scrollbar-thin scrollbar-thumb-white/10">
|
|
|
|
| 217 |
) : (
|
| 218 |
<>
|
| 219 |
{allMessages.map((msg, index) => {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
const isMe = msg.sender_type === 'human' || msg.sender_type === 'ai'
|
| 221 |
const isAI = msg.sender_type === 'ai'
|
|
|
|
| 222 |
const prevMsg = index > 0 ? allMessages[index - 1] : null
|
| 223 |
const showDate = shouldShowDateSeparator(msg, prevMsg)
|
| 224 |
|
|
|
|
| 225 |
const isSequence = prevMsg &&
|
| 226 |
((isMe && (prevMsg.sender_type === 'human' || prevMsg.sender_type === 'ai')) ||
|
| 227 |
(!isMe && (prevMsg.sender_type !== 'human' && prevMsg.sender_type !== 'ai'))) &&
|
| 228 |
!showDate
|
| 229 |
|
| 230 |
return (
|
| 231 |
+
<MessageBubble
|
| 232 |
+
key={msg.id}
|
| 233 |
+
message={msg}
|
| 234 |
+
isMe={isMe}
|
| 235 |
+
isAI={isAI}
|
| 236 |
+
isSequence={!!isSequence}
|
| 237 |
+
showDate={showDate}
|
| 238 |
+
dateLabel={getDateLabel(msg.created_at)}
|
| 239 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 240 |
)
|
| 241 |
})}
|
| 242 |
|
| 243 |
+
<TypingIndicator isVisible={!!isAnalyzing} />
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 244 |
</>
|
| 245 |
)}
|
| 246 |
<div ref={messagesEndRef} />
|
| 247 |
</div>
|
| 248 |
|
| 249 |
+
{/* Input Area */}
|
| 250 |
+
<MessageInput
|
| 251 |
+
value={inputMessage}
|
| 252 |
+
onChange={setInputMessage}
|
| 253 |
+
onSubmit={handleSendMessage}
|
| 254 |
+
isSending={isSending}
|
| 255 |
+
/>
|
| 256 |
+
|
| 257 |
+
{/* Mobile Drawer */}
|
| 258 |
+
{isMobileDrawerOpen && (
|
| 259 |
+
<div className="fixed inset-0 z-50 md:hidden">
|
| 260 |
+
<div className="absolute inset-0 bg-black/60 backdrop-blur-sm" onClick={() => setIsMobileDrawerOpen(false)} />
|
| 261 |
+
<div className="absolute right-0 top-0 bottom-0 w-[85%] bg-[#12131F] shadow-2xl animate-in slide-in-from-right duration-300">
|
| 262 |
+
<div className="p-4 border-b border-white/10 flex items-center justify-between">
|
| 263 |
+
<h3 className="font-bold text-white">Инфо о лиде</h3>
|
| 264 |
+
<button onClick={() => setIsMobileDrawerOpen(false)} className="p-2 hover:bg-white/10 rounded-full">
|
| 265 |
+
<X className="w-5 h-5 text-slate-400" />
|
| 266 |
+
</button>
|
| 267 |
+
</div>
|
| 268 |
+
<div className="h-full overflow-y-auto pb-20">
|
| 269 |
+
{lead && (
|
| 270 |
+
<ClientCard
|
| 271 |
+
lead={lead}
|
| 272 |
+
onTakeover={onTakeover || (() => { })}
|
| 273 |
+
isAnalyzing={isAnalyzing}
|
| 274 |
+
onRefresh={onRefresh || (() => { })}
|
| 275 |
+
conversationId={conversationId}
|
| 276 |
+
tenantId={tenantId}
|
| 277 |
+
/>
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
)}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
</div>
|
| 280 |
</div>
|
| 281 |
+
</div>
|
| 282 |
+
)}
|
| 283 |
|
| 284 |
+
{/* Booking Modal */}
|
| 285 |
<AnimatePresence>
|
| 286 |
{isBookingModalOpen && leadId && (
|
| 287 |
<BookingModal
|
|
|
|
| 292 |
/>
|
| 293 |
)}
|
| 294 |
</AnimatePresence>
|
| 295 |
+
</div>
|
| 296 |
)
|
| 297 |
}
|
frontend/components/ChatWindow/ChatHeader.tsx
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client'
|
| 2 |
+
|
| 3 |
+
import { cn } from '@/lib/utils'
|
| 4 |
+
import { ArrowLeft, Bot, Calendar, Info, Loader2, MoreVertical, Sparkles } from 'lucide-react'
|
| 5 |
+
import type { Lead } from '@/types'
|
| 6 |
+
|
| 7 |
+
interface ChatHeaderProps {
|
| 8 |
+
lead?: Lead
|
| 9 |
+
isAnalyzing?: boolean
|
| 10 |
+
isAIActive: boolean
|
| 11 |
+
isTogglingAI: boolean
|
| 12 |
+
isLeadsListOpen?: boolean
|
| 13 |
+
onToggleLeadsList?: () => void
|
| 14 |
+
onBack?: () => void
|
| 15 |
+
onToggleAI: () => void
|
| 16 |
+
onOpenMobileDrawer: () => void
|
| 17 |
+
onOpenBookingModal: () => void
|
| 18 |
+
}
|
| 19 |
+
|
| 20 |
+
export function ChatHeader({
|
| 21 |
+
lead,
|
| 22 |
+
isAnalyzing,
|
| 23 |
+
isAIActive,
|
| 24 |
+
isTogglingAI,
|
| 25 |
+
isLeadsListOpen,
|
| 26 |
+
onToggleLeadsList,
|
| 27 |
+
onBack,
|
| 28 |
+
onToggleAI,
|
| 29 |
+
onOpenMobileDrawer,
|
| 30 |
+
onOpenBookingModal,
|
| 31 |
+
}: ChatHeaderProps) {
|
| 32 |
+
return (
|
| 33 |
+
<div className="bg-[#12131F] border-b border-white/10 px-6 py-3 flex items-center justify-between z-10 flex-shrink-0">
|
| 34 |
+
<div className="flex items-center gap-4">
|
| 35 |
+
{/* Desktop Toggle */}
|
| 36 |
+
<button
|
| 37 |
+
onClick={onToggleLeadsList}
|
| 38 |
+
className="hidden md:flex p-2 -ml-2 text-slate-400 hover:text-indigo-400 hover:bg-white/5 rounded-lg transition-all"
|
| 39 |
+
title={isLeadsListOpen ? "Скрыть список" : "Показать список"}
|
| 40 |
+
>
|
| 41 |
+
{isLeadsListOpen ? <ArrowLeft className="w-5 h-5" /> : <MoreVertical className="w-5 h-5 rotate-90" />}
|
| 42 |
+
</button>
|
| 43 |
+
|
| 44 |
+
<button onClick={onBack} className="md:hidden p-2 -ml-2 text-slate-400 hover:text-white">
|
| 45 |
+
<ArrowLeft className="w-5 h-5" />
|
| 46 |
+
</button>
|
| 47 |
+
|
| 48 |
+
<div className="flex items-center gap-3">
|
| 49 |
+
<div className="w-10 h-10 rounded-full bg-gradient-to-br from-indigo-600/30 to-purple-600/30 flex items-center justify-center text-indigo-400 font-bold text-sm border border-indigo-500/30 relative shadow-sm">
|
| 50 |
+
{lead?.name?.charAt(0) || 'L'}
|
| 51 |
+
<div className={cn(
|
| 52 |
+
"absolute bottom-0 right-0 w-3 h-3 rounded-full border-2 border-white",
|
| 53 |
+
lead?.heat_level === 'HOT' ? "bg-red-500" :
|
| 54 |
+
lead?.heat_level === 'WARM' ? "bg-amber-500" :
|
| 55 |
+
"bg-blue-500"
|
| 56 |
+
)} />
|
| 57 |
+
</div>
|
| 58 |
+
<div>
|
| 59 |
+
<h2 className="font-bold text-white text-sm">{lead?.name || 'Лид'}</h2>
|
| 60 |
+
<div className="flex items-center gap-2">
|
| 61 |
+
<span className="text-xs text-slate-400 font-medium">{(lead as any)?.channel_source || 'Неизвестно'}</span>
|
| 62 |
+
{isAnalyzing && (
|
| 63 |
+
<span className="flex items-center gap-1 text-[10px] text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full animate-pulse border border-indigo-100 font-semibold">
|
| 64 |
+
<Sparkles className="w-3 h-3" />
|
| 65 |
+
AI думает...
|
| 66 |
+
</span>
|
| 67 |
+
)}
|
| 68 |
+
</div>
|
| 69 |
+
</div>
|
| 70 |
+
</div>
|
| 71 |
+
</div>
|
| 72 |
+
|
| 73 |
+
<div className="flex items-center gap-3">
|
| 74 |
+
<button
|
| 75 |
+
onClick={onOpenBookingModal}
|
| 76 |
+
className="hidden md:flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold bg-white/5 text-slate-300 border border-white/10 hover:bg-white/10 transition-all"
|
| 77 |
+
title="Записать на встречу"
|
| 78 |
+
>
|
| 79 |
+
<Calendar className="w-3.5 h-3.5 text-slate-500" />
|
| 80 |
+
Записать
|
| 81 |
+
</button>
|
| 82 |
+
|
| 83 |
+
<button
|
| 84 |
+
onClick={onToggleAI}
|
| 85 |
+
disabled={isTogglingAI}
|
| 86 |
+
className={cn(
|
| 87 |
+
"flex items-center gap-2 px-3 py-1.5 rounded-lg text-xs font-semibold transition-all duration-200 border shadow-sm",
|
| 88 |
+
isAIActive
|
| 89 |
+
? "bg-indigo-500/20 text-indigo-300 border-indigo-500/30 hover:bg-indigo-500/30"
|
| 90 |
+
: "bg-white/5 text-slate-400 border-white/10 hover:bg-white/10"
|
| 91 |
+
)}
|
| 92 |
+
>
|
| 93 |
+
{isTogglingAI ? (
|
| 94 |
+
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
| 95 |
+
) : (
|
| 96 |
+
<Bot className={cn("w-3.5 h-3.5", isAIActive ? "text-indigo-600" : "text-slate-400")} />
|
| 97 |
+
)}
|
| 98 |
+
{isAIActive ? 'AI Активен' : 'AI Отключен'}
|
| 99 |
+
</button>
|
| 100 |
+
|
| 101 |
+
<button
|
| 102 |
+
onClick={onOpenMobileDrawer}
|
| 103 |
+
className="md:hidden p-2 text-slate-400 hover:text-slate-600"
|
| 104 |
+
>
|
| 105 |
+
<Info className="w-5 h-5" />
|
| 106 |
+
</button>
|
| 107 |
+
</div>
|
| 108 |
+
</div>
|
| 109 |
+
)
|
| 110 |
+
}
|
frontend/components/ChatWindow/MessageBubble.tsx
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client'
|
| 2 |
+
|
| 3 |
+
import { cn, formatDate } from '@/lib/utils'
|
| 4 |
+
import { Bot, User } from 'lucide-react'
|
| 5 |
+
import { motion } from 'framer-motion'
|
| 6 |
+
import type { Message } from '@/types'
|
| 7 |
+
|
| 8 |
+
interface MessageBubbleProps {
|
| 9 |
+
message: Message
|
| 10 |
+
isMe: boolean
|
| 11 |
+
isAI: boolean
|
| 12 |
+
isSequence: boolean
|
| 13 |
+
showDate: boolean
|
| 14 |
+
dateLabel: string
|
| 15 |
+
}
|
| 16 |
+
|
| 17 |
+
export function MessageBubble({
|
| 18 |
+
message,
|
| 19 |
+
isMe,
|
| 20 |
+
isAI,
|
| 21 |
+
isSequence,
|
| 22 |
+
showDate,
|
| 23 |
+
dateLabel,
|
| 24 |
+
}: MessageBubbleProps) {
|
| 25 |
+
return (
|
| 26 |
+
<div>
|
| 27 |
+
{showDate && (
|
| 28 |
+
<div className="flex items-center justify-center my-6">
|
| 29 |
+
<span className="text-[10px] font-bold text-slate-400 bg-white/10 px-3 py-1 rounded-full uppercase tracking-wide">
|
| 30 |
+
{dateLabel}
|
| 31 |
+
</span>
|
| 32 |
+
</div>
|
| 33 |
+
)}
|
| 34 |
+
|
| 35 |
+
<motion.div
|
| 36 |
+
initial={{ opacity: 0, y: 10 }}
|
| 37 |
+
animate={{ opacity: 1, y: 0 }}
|
| 38 |
+
transition={{ duration: 0.3 }}
|
| 39 |
+
className={cn(
|
| 40 |
+
"flex w-full max-w-3xl mx-auto group",
|
| 41 |
+
isMe ? "justify-end" : "justify-start",
|
| 42 |
+
isSequence ? "mt-1" : "mt-4"
|
| 43 |
+
)}
|
| 44 |
+
>
|
| 45 |
+
<div className={cn(
|
| 46 |
+
"flex gap-3 max-w-[75%]",
|
| 47 |
+
isMe ? "flex-row-reverse" : "flex-row"
|
| 48 |
+
)}>
|
| 49 |
+
{/* Avatar */}
|
| 50 |
+
<div className={cn(
|
| 51 |
+
"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-auto mb-1 transition-opacity",
|
| 52 |
+
isMe ? "bg-indigo-600 text-white" : "bg-[#12131F] text-slate-400 border border-white/10",
|
| 53 |
+
isSequence ? "opacity-0 w-0 overflow-hidden ml-0 mr-0" : "opacity-100"
|
| 54 |
+
)}>
|
| 55 |
+
{isMe ? (isAI ? <Bot className="w-4 h-4" /> : <User className="w-4 h-4" />) : <User className="w-4 h-4" />}
|
| 56 |
+
</div>
|
| 57 |
+
|
| 58 |
+
{/* Message Bubble */}
|
| 59 |
+
<div className="flex flex-col gap-1 min-w-0">
|
| 60 |
+
<div className={cn(
|
| 61 |
+
"px-4 py-2.5 text-sm leading-relaxed shadow-sm relative break-words",
|
| 62 |
+
isMe
|
| 63 |
+
? "bg-gradient-to-r from-indigo-600 to-violet-600 text-white rounded-2xl rounded-br-none shadow-[0_4px_15px_-3px_rgba(99,102,241,0.3)]"
|
| 64 |
+
: "bg-[#1E2030] text-slate-200 border border-white/5 rounded-2xl rounded-bl-none",
|
| 65 |
+
isSequence && isMe && "rounded-tr-md rounded-br-md",
|
| 66 |
+
isSequence && !isMe && "rounded-tl-md rounded-bl-md"
|
| 67 |
+
)}>
|
| 68 |
+
{message.content}
|
| 69 |
+
</div>
|
| 70 |
+
{!isSequence && (
|
| 71 |
+
<span className={cn(
|
| 72 |
+
"text-[10px] text-slate-400 px-1 flex items-center gap-1",
|
| 73 |
+
isMe ? "justify-end text-right" : "justify-start text-left"
|
| 74 |
+
)}>
|
| 75 |
+
{formatDate(message.created_at)}
|
| 76 |
+
</span>
|
| 77 |
+
)}
|
| 78 |
+
</div>
|
| 79 |
+
</div>
|
| 80 |
+
</motion.div>
|
| 81 |
+
</div>
|
| 82 |
+
)
|
| 83 |
+
}
|
frontend/components/ChatWindow/MessageInput.tsx
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client'
|
| 2 |
+
|
| 3 |
+
import { cn } from '@/lib/utils'
|
| 4 |
+
import { Loader2, Paperclip, Send, Smile } from 'lucide-react'
|
| 5 |
+
|
| 6 |
+
interface MessageInputProps {
|
| 7 |
+
value: string
|
| 8 |
+
onChange: (value: string) => void
|
| 9 |
+
onSubmit: (e: React.FormEvent) => void
|
| 10 |
+
isSending: boolean
|
| 11 |
+
disabled?: boolean
|
| 12 |
+
}
|
| 13 |
+
|
| 14 |
+
export function MessageInput({
|
| 15 |
+
value,
|
| 16 |
+
onChange,
|
| 17 |
+
onSubmit,
|
| 18 |
+
isSending,
|
| 19 |
+
disabled,
|
| 20 |
+
}: MessageInputProps) {
|
| 21 |
+
const handleKeyDown = (e: React.KeyboardEvent) => {
|
| 22 |
+
if (e.key === 'Enter' && !e.shiftKey) {
|
| 23 |
+
e.preventDefault()
|
| 24 |
+
onSubmit(e as unknown as React.FormEvent)
|
| 25 |
+
}
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
return (
|
| 29 |
+
<div className="p-6 bg-[#0D0E18] flex-shrink-0">
|
| 30 |
+
<div className="max-w-4xl mx-auto relative">
|
| 31 |
+
<form
|
| 32 |
+
onSubmit={onSubmit}
|
| 33 |
+
className="flex items-end gap-2 bg-[#12131F] p-2 rounded-2xl border border-white/10 focus-within:ring-2 focus-within:ring-indigo-500/30 transition-all"
|
| 34 |
+
>
|
| 35 |
+
<button
|
| 36 |
+
type="button"
|
| 37 |
+
className="p-2.5 text-slate-500 hover:text-indigo-400 hover:bg-white/5 rounded-xl transition-colors"
|
| 38 |
+
>
|
| 39 |
+
<Paperclip className="w-5 h-5" />
|
| 40 |
+
</button>
|
| 41 |
+
|
| 42 |
+
<textarea
|
| 43 |
+
value={value}
|
| 44 |
+
onChange={(e) => onChange(e.target.value)}
|
| 45 |
+
onKeyDown={handleKeyDown}
|
| 46 |
+
placeholder="Напишите сообщение..."
|
| 47 |
+
className="flex-1 bg-transparent border-none focus:ring-0 resize-none max-h-32 py-2.5 px-4 text-sm text-white placeholder:text-slate-500"
|
| 48 |
+
rows={1}
|
| 49 |
+
style={{ minHeight: '44px' }}
|
| 50 |
+
disabled={disabled}
|
| 51 |
+
/>
|
| 52 |
+
|
| 53 |
+
<button
|
| 54 |
+
type="button"
|
| 55 |
+
className="p-2.5 text-slate-500 hover:text-indigo-400 hover:bg-white/5 rounded-xl transition-colors"
|
| 56 |
+
>
|
| 57 |
+
<Smile className="w-5 h-5" />
|
| 58 |
+
</button>
|
| 59 |
+
|
| 60 |
+
<button
|
| 61 |
+
type="submit"
|
| 62 |
+
disabled={!value.trim() || isSending || disabled}
|
| 63 |
+
className={cn(
|
| 64 |
+
"p-2.5 rounded-xl transition-all duration-200 shadow-sm",
|
| 65 |
+
(value.trim() && !isSending && !disabled)
|
| 66 |
+
? "bg-indigo-600 text-white hover:bg-indigo-500 hover:scale-105 active:scale-95"
|
| 67 |
+
: "bg-white/5 text-slate-500 cursor-not-allowed"
|
| 68 |
+
)}
|
| 69 |
+
>
|
| 70 |
+
{isSending ? (
|
| 71 |
+
<Loader2 className="w-5 h-5 animate-spin" />
|
| 72 |
+
) : (
|
| 73 |
+
<Send className="w-5 h-5" />
|
| 74 |
+
)}
|
| 75 |
+
</button>
|
| 76 |
+
</form>
|
| 77 |
+
<div className="text-center mt-2">
|
| 78 |
+
<p className="text-[10px] text-slate-400 font-medium">
|
| 79 |
+
Enter для отправки • Shift + Enter для переноса
|
| 80 |
+
</p>
|
| 81 |
+
</div>
|
| 82 |
+
</div>
|
| 83 |
+
</div>
|
| 84 |
+
)
|
| 85 |
+
}
|
frontend/components/ChatWindow/TypingIndicator.tsx
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client'
|
| 2 |
+
|
| 3 |
+
import { Bot } from 'lucide-react'
|
| 4 |
+
import { motion, AnimatePresence } from 'framer-motion'
|
| 5 |
+
|
| 6 |
+
interface TypingIndicatorProps {
|
| 7 |
+
isVisible: boolean
|
| 8 |
+
}
|
| 9 |
+
|
| 10 |
+
export function TypingIndicator({ isVisible }: TypingIndicatorProps) {
|
| 11 |
+
return (
|
| 12 |
+
<AnimatePresence>
|
| 13 |
+
{isVisible && (
|
| 14 |
+
<motion.div
|
| 15 |
+
initial={{ opacity: 0, y: 10 }}
|
| 16 |
+
animate={{ opacity: 1, y: 0 }}
|
| 17 |
+
exit={{ opacity: 0, scale: 0.9 }}
|
| 18 |
+
className="flex w-full max-w-3xl mx-auto justify-end mt-4"
|
| 19 |
+
>
|
| 20 |
+
<div className="flex gap-3 flex-row-reverse">
|
| 21 |
+
<div className="w-8 h-8 rounded-full bg-indigo-600 text-white flex items-center justify-center flex-shrink-0 shadow-sm mt-auto mb-1">
|
| 22 |
+
<Bot className="w-4 h-4" />
|
| 23 |
+
</div>
|
| 24 |
+
<div className="bg-indigo-600 text-white px-4 py-3 rounded-2xl rounded-br-none shadow-sm flex items-center gap-1">
|
| 25 |
+
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce [animation-delay:-0.3s]"></span>
|
| 26 |
+
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce [animation-delay:-0.15s]"></span>
|
| 27 |
+
<span className="w-1.5 h-1.5 bg-white/70 rounded-full animate-bounce"></span>
|
| 28 |
+
</div>
|
| 29 |
+
</div>
|
| 30 |
+
</motion.div>
|
| 31 |
+
)}
|
| 32 |
+
</AnimatePresence>
|
| 33 |
+
)
|
| 34 |
+
}
|
frontend/components/ChatWindow/index.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* ChatWindow Component Module
|
| 3 |
+
*
|
| 4 |
+
* Модульная структура компонента чата.
|
| 5 |
+
* Основной компонент остаётся в components/ChatWindow.tsx для обратной совместимости.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
export { ChatHeader } from './ChatHeader'
|
| 9 |
+
export { MessageBubble } from './MessageBubble'
|
| 10 |
+
export { MessageInput } from './MessageInput'
|
| 11 |
+
export { TypingIndicator } from './TypingIndicator'
|
frontend/components/Sidebar.tsx
CHANGED
|
@@ -2,73 +2,100 @@
|
|
| 2 |
|
| 3 |
import Link from 'next/link'
|
| 4 |
import { usePathname } from 'next/navigation'
|
| 5 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
import { useAuth } from '@/contexts/AuthContext'
|
| 7 |
-
import { motion
|
| 8 |
-
import {
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
|
|
|
|
|
|
|
|
|
| 10 |
|
| 11 |
export function Sidebar() {
|
| 12 |
const pathname = usePathname()
|
| 13 |
-
const { user,
|
| 14 |
|
| 15 |
// Don't show sidebar on auth pages
|
| 16 |
if (pathname === '/login' || pathname === '/register' || pathname === '/') {
|
| 17 |
return null
|
| 18 |
}
|
| 19 |
|
| 20 |
-
//
|
| 21 |
if (!isLoading && !user) {
|
| 22 |
-
// This should be handled by AuthContext/Middleware, but as a fallback:
|
| 23 |
return null
|
| 24 |
}
|
| 25 |
|
| 26 |
-
// Helper to check if route is active
|
| 27 |
const isActive = (path: string) => pathname === path || pathname.startsWith(path + '/')
|
| 28 |
-
|
| 29 |
-
// Get user initials for avatar
|
| 30 |
-
const getInitials = (name?: string | null, email?: string) => {
|
| 31 |
-
if (name) {
|
| 32 |
-
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
|
| 33 |
-
}
|
| 34 |
-
if (email) {
|
| 35 |
-
return email.slice(0, 2).toUpperCase()
|
| 36 |
-
}
|
| 37 |
-
return 'U'
|
| 38 |
-
}
|
| 39 |
-
|
| 40 |
-
// Generate random avatar color based on user email
|
| 41 |
-
const getAvatarColor = (email?: string) => {
|
| 42 |
-
if (!email) return 'bg-indigo-600'
|
| 43 |
-
const colors = [
|
| 44 |
-
'bg-indigo-600',
|
| 45 |
-
'bg-purple-600',
|
| 46 |
-
'bg-pink-600',
|
| 47 |
-
'bg-blue-600',
|
| 48 |
-
'bg-cyan-600',
|
| 49 |
-
'bg-teal-600',
|
| 50 |
-
'bg-emerald-600',
|
| 51 |
-
]
|
| 52 |
-
const index = email.charCodeAt(0) % colors.length
|
| 53 |
-
return colors[index]
|
| 54 |
-
}
|
| 55 |
-
|
| 56 |
-
const sidebarVariants = {
|
| 57 |
-
hidden: { x: -20, opacity: 0 },
|
| 58 |
-
visible: {
|
| 59 |
-
x: 0,
|
| 60 |
-
opacity: 1,
|
| 61 |
-
transition: {
|
| 62 |
-
duration: 0.4,
|
| 63 |
-
staggerChildren: 0.05
|
| 64 |
-
}
|
| 65 |
-
}
|
| 66 |
-
}
|
| 67 |
-
|
| 68 |
-
const itemVariants = {
|
| 69 |
-
hidden: { x: -10, opacity: 0 },
|
| 70 |
-
visible: { x: 0, opacity: 1 }
|
| 71 |
-
}
|
| 72 |
|
| 73 |
return (
|
| 74 |
<motion.aside
|
|
@@ -77,8 +104,6 @@ export function Sidebar() {
|
|
| 77 |
variants={sidebarVariants}
|
| 78 |
className="w-72 bg-[#020005] border-r border-white/10 flex flex-col font-['Inter'] relative shrink-0 h-screen sticky top-0"
|
| 79 |
>
|
| 80 |
-
{/* Background Glow Effect - Removed for better visibility */}
|
| 81 |
-
|
| 82 |
{/* Logo Section */}
|
| 83 |
<div className="p-6 border-b border-white/10 relative z-50">
|
| 84 |
<Link href="/dashboard" className="flex items-center gap-3 group">
|
|
@@ -91,7 +116,7 @@ export function Sidebar() {
|
|
| 91 |
</Link>
|
| 92 |
</div>
|
| 93 |
|
| 94 |
-
{/* Loading State
|
| 95 |
{isLoading ? (
|
| 96 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
|
| 97 |
{[1, 2, 3].map((i) => (
|
|
@@ -109,178 +134,72 @@ export function Sidebar() {
|
|
| 109 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent">
|
| 110 |
|
| 111 |
{/* Main Navigation */}
|
| 112 |
-
<motion.div
|
| 113 |
-
initial="hidden"
|
| 114 |
-
animate="visible"
|
| 115 |
-
variants={itemVariants}
|
| 116 |
-
>
|
| 117 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 118 |
/ ГЛАВНАЯ
|
| 119 |
</p>
|
| 120 |
<div className="space-y-1">
|
| 121 |
-
{/* Admin Link
|
| 122 |
-
{
|
| 123 |
-
<
|
| 124 |
-
"
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
<span className="font-mono">АДМИН</span>
|
| 131 |
-
{isActive('/admin') && <div className="ml-auto w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />}
|
| 132 |
-
</Link>
|
| 133 |
)}
|
| 134 |
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
</Link>
|
| 145 |
-
|
| 146 |
-
<Link href="/chats" className={cn(
|
| 147 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 148 |
-
isActive('/chats')
|
| 149 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 150 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 151 |
-
)}>
|
| 152 |
-
<MessageSquare className={cn("w-4 h-4 transition-colors", isActive('/chats') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 153 |
-
<span>Чаты</span>
|
| 154 |
-
{/* Badge for unread messages could go here */}
|
| 155 |
-
</Link>
|
| 156 |
-
|
| 157 |
-
<Link href="/appointments" className={cn(
|
| 158 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 159 |
-
isActive('/appointments')
|
| 160 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 161 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 162 |
-
)}>
|
| 163 |
-
<Calendar className={cn("w-4 h-4 transition-colors", isActive('/appointments') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 164 |
-
<span>Записи</span>
|
| 165 |
-
</Link>
|
| 166 |
-
|
| 167 |
-
|
| 168 |
</div>
|
| 169 |
</motion.div>
|
| 170 |
|
| 171 |
-
{/*
|
| 172 |
-
<motion.div
|
| 173 |
-
initial="hidden"
|
| 174 |
-
animate="visible"
|
| 175 |
-
variants={itemVariants}
|
| 176 |
-
>
|
| 177 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 178 |
/ ИНТЕГРАЦИИ
|
| 179 |
</p>
|
| 180 |
<div className="space-y-1">
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
<span>Подключения</span>
|
| 191 |
-
</Link>
|
| 192 |
</div>
|
| 193 |
</motion.div>
|
| 194 |
|
| 195 |
-
{/* Settings
|
| 196 |
-
<motion.div
|
| 197 |
-
initial="hidden"
|
| 198 |
-
animate="visible"
|
| 199 |
-
variants={itemVariants}
|
| 200 |
-
>
|
| 201 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 202 |
/ НАСТРОЙКИ
|
| 203 |
</p>
|
| 204 |
<div className="space-y-1">
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
<Link href="/settings/crm" className={cn(
|
| 216 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 217 |
-
isActive('/settings/crm')
|
| 218 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 219 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 220 |
-
)}>
|
| 221 |
-
<Database className={cn("w-4 h-4 transition-colors", isActive('/settings/crm') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 222 |
-
<span>CRM</span>
|
| 223 |
-
</Link>
|
| 224 |
-
|
| 225 |
-
<Link href="/settings/playbook" className={cn(
|
| 226 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 227 |
-
isActive('/settings/playbook')
|
| 228 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 229 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 230 |
-
)}>
|
| 231 |
-
<FileText className={cn("w-4 h-4 transition-colors", isActive('/settings/playbook') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 232 |
-
<span>Воронка</span>
|
| 233 |
-
</Link>
|
| 234 |
-
|
| 235 |
-
<Link href="/settings/team" className={cn(
|
| 236 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 237 |
-
isActive('/settings/team')
|
| 238 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 239 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 240 |
-
)}>
|
| 241 |
-
<Users className={cn("w-4 h-4 transition-colors", isActive('/settings/team') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 242 |
-
<span>Команда</span>
|
| 243 |
-
</Link>
|
| 244 |
-
|
| 245 |
-
<Link href="/settings/notifications" className={cn(
|
| 246 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 247 |
-
isActive('/settings/notifications')
|
| 248 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 249 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 250 |
-
)}>
|
| 251 |
-
<Bell className={cn("w-4 h-4 transition-colors", isActive('/settings/notifications') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 252 |
-
<span>Уведомления</span>
|
| 253 |
-
</Link>
|
| 254 |
-
|
| 255 |
-
<Link href="/settings/billing" className={cn(
|
| 256 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 257 |
-
isActive('/settings/billing')
|
| 258 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 259 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 260 |
-
)}>
|
| 261 |
-
<CreditCard className={cn("w-4 h-4 transition-colors", isActive('/settings/billing') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 262 |
-
<span>Тарифы</span>
|
| 263 |
-
</Link>
|
| 264 |
-
|
| 265 |
-
{/* Partner Program Link - Moved to nav with others per request/flow or keep at bottom? User said rename "Affilate program" to "Партнерская программа".
|
| 266 |
-
I will add it here as a regular menu item for consistency or keep it special?
|
| 267 |
-
The previous design had it at bottom. I'll move it here to be cleaner if the bottom profile is gone.
|
| 268 |
-
Actually, let's keep it as a nav item.
|
| 269 |
-
*/}
|
| 270 |
-
<Link href="/partners" className={cn(
|
| 271 |
-
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 272 |
-
isActive('/partners')
|
| 273 |
-
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 274 |
-
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 275 |
-
)}>
|
| 276 |
-
<Zap className={cn("w-4 h-4 transition-colors", isActive('/partners') ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400")} />
|
| 277 |
-
<span>Партнерская программа</span>
|
| 278 |
-
</Link>
|
| 279 |
</div>
|
| 280 |
</motion.div>
|
|
|
|
| 281 |
</nav>
|
| 282 |
)}
|
| 283 |
</motion.aside>
|
| 284 |
)
|
| 285 |
}
|
| 286 |
-
|
|
|
|
| 2 |
|
| 3 |
import Link from 'next/link'
|
| 4 |
import { usePathname } from 'next/navigation'
|
| 5 |
+
import {
|
| 6 |
+
LayoutDashboard,
|
| 7 |
+
MessageSquare,
|
| 8 |
+
Database,
|
| 9 |
+
CreditCard,
|
| 10 |
+
Brain,
|
| 11 |
+
FileText,
|
| 12 |
+
Plug,
|
| 13 |
+
Zap,
|
| 14 |
+
Users,
|
| 15 |
+
Bell,
|
| 16 |
+
Calendar,
|
| 17 |
+
Shield
|
| 18 |
+
} from 'lucide-react'
|
| 19 |
import { useAuth } from '@/contexts/AuthContext'
|
| 20 |
+
import { motion } from 'framer-motion'
|
| 21 |
+
import { NavItem } from './Sidebar/NavItem'
|
| 22 |
+
|
| 23 |
+
// ============================================================================
|
| 24 |
+
// Animation Variants
|
| 25 |
+
// ============================================================================
|
| 26 |
+
|
| 27 |
+
const sidebarVariants = {
|
| 28 |
+
hidden: { x: -20, opacity: 0 },
|
| 29 |
+
visible: {
|
| 30 |
+
x: 0,
|
| 31 |
+
opacity: 1,
|
| 32 |
+
transition: { duration: 0.4, staggerChildren: 0.05 }
|
| 33 |
+
}
|
| 34 |
+
}
|
| 35 |
+
|
| 36 |
+
const itemVariants = {
|
| 37 |
+
hidden: { x: -10, opacity: 0 },
|
| 38 |
+
visible: { x: 0, opacity: 1 }
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
// ============================================================================
|
| 42 |
+
// Navigation Configuration
|
| 43 |
+
// ============================================================================
|
| 44 |
+
|
| 45 |
+
const mainNavItems = [
|
| 46 |
+
{ href: '/dashboard', icon: LayoutDashboard, label: 'Аналитика' },
|
| 47 |
+
{ href: '/chats', icon: MessageSquare, label: 'Чаты' },
|
| 48 |
+
{ href: '/appointments', icon: Calendar, label: 'Записи' },
|
| 49 |
+
]
|
| 50 |
+
|
| 51 |
+
const integrationItems = [
|
| 52 |
+
{ href: '/channels', icon: Plug, label: 'Подключения' },
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
const settingsItems = [
|
| 56 |
+
{ href: '/settings/brain', icon: Brain, label: 'ИИ Мозг' },
|
| 57 |
+
{ href: '/settings/crm', icon: Database, label: 'CRM' },
|
| 58 |
+
{ href: '/settings/playbook', icon: FileText, label: 'Воронка' },
|
| 59 |
+
{ href: '/settings/team', icon: Users, label: 'Команда' },
|
| 60 |
+
{ href: '/settings/notifications', icon: Bell, label: 'Уведомления' },
|
| 61 |
+
{ href: '/settings/billing', icon: CreditCard, label: 'Тарифы' },
|
| 62 |
+
{ href: '/partners', icon: Zap, label: 'Партнерская программа' },
|
| 63 |
+
]
|
| 64 |
+
|
| 65 |
+
// ============================================================================
|
| 66 |
+
// Helper Functions
|
| 67 |
+
// ============================================================================
|
| 68 |
+
|
| 69 |
+
function getInitials(name?: string | null, email?: string): string {
|
| 70 |
+
if (name) {
|
| 71 |
+
return name.split(' ').map(n => n[0]).join('').toUpperCase().slice(0, 2)
|
| 72 |
+
}
|
| 73 |
+
if (email) {
|
| 74 |
+
return email.slice(0, 2).toUpperCase()
|
| 75 |
+
}
|
| 76 |
+
return 'U'
|
| 77 |
+
}
|
| 78 |
|
| 79 |
+
// ============================================================================
|
| 80 |
+
// Main Component
|
| 81 |
+
// ============================================================================
|
| 82 |
|
| 83 |
export function Sidebar() {
|
| 84 |
const pathname = usePathname()
|
| 85 |
+
const { user, isLoading } = useAuth()
|
| 86 |
|
| 87 |
// Don't show sidebar on auth pages
|
| 88 |
if (pathname === '/login' || pathname === '/register' || pathname === '/') {
|
| 89 |
return null
|
| 90 |
}
|
| 91 |
|
| 92 |
+
// Hide if not authenticated
|
| 93 |
if (!isLoading && !user) {
|
|
|
|
| 94 |
return null
|
| 95 |
}
|
| 96 |
|
|
|
|
| 97 |
const isActive = (path: string) => pathname === path || pathname.startsWith(path + '/')
|
| 98 |
+
const isAdmin = user?.is_superuser || user?.role === 'admin'
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
return (
|
| 101 |
<motion.aside
|
|
|
|
| 104 |
variants={sidebarVariants}
|
| 105 |
className="w-72 bg-[#020005] border-r border-white/10 flex flex-col font-['Inter'] relative shrink-0 h-screen sticky top-0"
|
| 106 |
>
|
|
|
|
|
|
|
| 107 |
{/* Logo Section */}
|
| 108 |
<div className="p-6 border-b border-white/10 relative z-50">
|
| 109 |
<Link href="/dashboard" className="flex items-center gap-3 group">
|
|
|
|
| 116 |
</Link>
|
| 117 |
</div>
|
| 118 |
|
| 119 |
+
{/* Loading State */}
|
| 120 |
{isLoading ? (
|
| 121 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10">
|
| 122 |
{[1, 2, 3].map((i) => (
|
|
|
|
| 134 |
<nav className="flex-1 overflow-y-auto p-4 space-y-6 relative z-10 scrollbar-thin scrollbar-thumb-white/10 scrollbar-track-transparent">
|
| 135 |
|
| 136 |
{/* Main Navigation */}
|
| 137 |
+
<motion.div initial="hidden" animate="visible" variants={itemVariants}>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 139 |
/ ГЛАВНАЯ
|
| 140 |
</p>
|
| 141 |
<div className="space-y-1">
|
| 142 |
+
{/* Admin Link */}
|
| 143 |
+
{isAdmin && (
|
| 144 |
+
<NavItem
|
| 145 |
+
href="/admin"
|
| 146 |
+
icon={Shield}
|
| 147 |
+
label="АДМИН"
|
| 148 |
+
isActive={isActive('/admin')}
|
| 149 |
+
variant="admin"
|
| 150 |
+
/>
|
|
|
|
|
|
|
|
|
|
| 151 |
)}
|
| 152 |
|
| 153 |
+
{mainNavItems.map((item) => (
|
| 154 |
+
<NavItem
|
| 155 |
+
key={item.href}
|
| 156 |
+
href={item.href}
|
| 157 |
+
icon={item.icon}
|
| 158 |
+
label={item.label}
|
| 159 |
+
isActive={isActive(item.href)}
|
| 160 |
+
/>
|
| 161 |
+
))}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 162 |
</div>
|
| 163 |
</motion.div>
|
| 164 |
|
| 165 |
+
{/* Integrations */}
|
| 166 |
+
<motion.div initial="hidden" animate="visible" variants={itemVariants}>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 167 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 168 |
/ ИНТЕГРАЦИИ
|
| 169 |
</p>
|
| 170 |
<div className="space-y-1">
|
| 171 |
+
{integrationItems.map((item) => (
|
| 172 |
+
<NavItem
|
| 173 |
+
key={item.href}
|
| 174 |
+
href={item.href}
|
| 175 |
+
icon={item.icon}
|
| 176 |
+
label={item.label}
|
| 177 |
+
isActive={isActive(item.href)}
|
| 178 |
+
/>
|
| 179 |
+
))}
|
|
|
|
|
|
|
| 180 |
</div>
|
| 181 |
</motion.div>
|
| 182 |
|
| 183 |
+
{/* Settings */}
|
| 184 |
+
<motion.div initial="hidden" animate="visible" variants={itemVariants}>
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
<p className="px-4 text-[10px] font-bold text-slate-500 uppercase tracking-widest mb-2 font-mono">
|
| 186 |
/ НАСТРОЙКИ
|
| 187 |
</p>
|
| 188 |
<div className="space-y-1">
|
| 189 |
+
{settingsItems.map((item) => (
|
| 190 |
+
<NavItem
|
| 191 |
+
key={item.href}
|
| 192 |
+
href={item.href}
|
| 193 |
+
icon={item.icon}
|
| 194 |
+
label={item.label}
|
| 195 |
+
isActive={isActive(item.href)}
|
| 196 |
+
/>
|
| 197 |
+
))}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
</div>
|
| 199 |
</motion.div>
|
| 200 |
+
|
| 201 |
</nav>
|
| 202 |
)}
|
| 203 |
</motion.aside>
|
| 204 |
)
|
| 205 |
}
|
|
|
frontend/components/Sidebar/NavItem.tsx
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
'use client'
|
| 2 |
+
|
| 3 |
+
import Link from 'next/link'
|
| 4 |
+
import { cn } from '@/lib/utils'
|
| 5 |
+
import type { LucideIcon } from 'lucide-react'
|
| 6 |
+
|
| 7 |
+
interface NavItemProps {
|
| 8 |
+
href: string
|
| 9 |
+
icon: LucideIcon
|
| 10 |
+
label: string
|
| 11 |
+
isActive: boolean
|
| 12 |
+
variant?: 'default' | 'admin'
|
| 13 |
+
}
|
| 14 |
+
|
| 15 |
+
export function NavItem({ href, icon: Icon, label, isActive, variant = 'default' }: NavItemProps) {
|
| 16 |
+
const isAdmin = variant === 'admin'
|
| 17 |
+
|
| 18 |
+
return (
|
| 19 |
+
<Link
|
| 20 |
+
href={href}
|
| 21 |
+
className={cn(
|
| 22 |
+
"flex items-center gap-3 px-4 py-2.5 rounded-lg text-sm font-medium transition-all duration-200 group relative border",
|
| 23 |
+
isAdmin ? (
|
| 24 |
+
isActive
|
| 25 |
+
? "text-white bg-red-500/10 border-red-500/50 shadow-[0_0_15px_-3px_rgba(220,38,38,0.3)]"
|
| 26 |
+
: "text-red-400 border-transparent hover:bg-red-500/5 hover:border-red-500/20"
|
| 27 |
+
) : (
|
| 28 |
+
isActive
|
| 29 |
+
? "text-white bg-indigo-500/10 border-indigo-500/50 shadow-[0_0_15px_-3px_rgba(99,102,241,0.3)]"
|
| 30 |
+
: "text-slate-400 border-transparent hover:text-white hover:bg-white/5 hover:border-white/10"
|
| 31 |
+
)
|
| 32 |
+
)}
|
| 33 |
+
>
|
| 34 |
+
<Icon
|
| 35 |
+
className={cn(
|
| 36 |
+
"w-4 h-4 transition-colors",
|
| 37 |
+
isAdmin ? (
|
| 38 |
+
isActive ? "text-red-500" : "text-red-400"
|
| 39 |
+
) : (
|
| 40 |
+
isActive ? "text-indigo-400" : "text-slate-500 group-hover:text-indigo-400"
|
| 41 |
+
)
|
| 42 |
+
)}
|
| 43 |
+
/>
|
| 44 |
+
<span className={isAdmin ? "font-mono font-bold" : ""}>{label}</span>
|
| 45 |
+
{isActive && (
|
| 46 |
+
<div className={cn(
|
| 47 |
+
"ml-auto w-1.5 h-1.5 rounded-full animate-pulse",
|
| 48 |
+
isAdmin ? "bg-red-500" : "bg-indigo-500"
|
| 49 |
+
)} />
|
| 50 |
+
)}
|
| 51 |
+
</Link>
|
| 52 |
+
)
|
| 53 |
+
}
|
frontend/components/Sidebar/index.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* Sidebar Component Module
|
| 3 |
+
*/
|
| 4 |
+
|
| 5 |
+
export { NavItem } from './NavItem'
|
frontend/lib/api.ts
CHANGED
|
@@ -1,5 +1,22 @@
|
|
| 1 |
import axios from 'axios'
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
|
| 4 |
console.log('🔗 API URL:', API_BASE_URL)
|
| 5 |
|
|
@@ -40,98 +57,6 @@ api.interceptors.response.use(
|
|
| 40 |
}
|
| 41 |
)
|
| 42 |
|
| 43 |
-
// Types
|
| 44 |
-
export interface Lead {
|
| 45 |
-
id: string
|
| 46 |
-
tenant_id: string
|
| 47 |
-
name: string | null
|
| 48 |
-
telegram_id: string | null
|
| 49 |
-
whatsapp_id: string | null
|
| 50 |
-
email: string | null
|
| 51 |
-
linkedin_profile: string | null
|
| 52 |
-
linkedin_urn: string | null
|
| 53 |
-
status: string
|
| 54 |
-
heat_score: number
|
| 55 |
-
heat_level: string
|
| 56 |
-
psychotype: string
|
| 57 |
-
processing_status: 'idle' | 'analyzing' | 'generating' | 'error'
|
| 58 |
-
budget: string | null
|
| 59 |
-
authority: string | null
|
| 60 |
-
need: string | null
|
| 61 |
-
timeline: string | null
|
| 62 |
-
ai_summary_json: {
|
| 63 |
-
// Hard Data
|
| 64 |
-
intent?: string
|
| 65 |
-
budget?: string
|
| 66 |
-
timeline?: string
|
| 67 |
-
authority?: string
|
| 68 |
-
location?: string
|
| 69 |
-
industry?: string
|
| 70 |
-
// Soft Data
|
| 71 |
-
pain_points?: string[]
|
| 72 |
-
psychotype?: string
|
| 73 |
-
heat_score?: number
|
| 74 |
-
// Strategy
|
| 75 |
-
objections?: string[]
|
| 76 |
-
hidden_signals?: string
|
| 77 |
-
recommendation?: string
|
| 78 |
-
draft_reply?: string
|
| 79 |
-
}
|
| 80 |
-
first_message_at: string
|
| 81 |
-
last_message_at: string
|
| 82 |
-
created_at: string
|
| 83 |
-
current_stage_id?: string | null
|
| 84 |
-
}
|
| 85 |
-
|
| 86 |
-
export interface Message {
|
| 87 |
-
id: string
|
| 88 |
-
conversation_id?: string
|
| 89 |
-
tenant_id?: string
|
| 90 |
-
sender_type: 'user' | 'ai' | 'human_manager' | 'human' // Added 'human' for manual replies
|
| 91 |
-
content: string
|
| 92 |
-
created_at: string
|
| 93 |
-
prompt_tokens?: number | null
|
| 94 |
-
completion_tokens?: number | null
|
| 95 |
-
model_used?: string | null
|
| 96 |
-
tokens?: {
|
| 97 |
-
prompt: number
|
| 98 |
-
completion: number
|
| 99 |
-
}
|
| 100 |
-
}
|
| 101 |
-
|
| 102 |
-
export interface Conversation {
|
| 103 |
-
id: string
|
| 104 |
-
channel: string
|
| 105 |
-
is_active: boolean
|
| 106 |
-
human_takeover: boolean
|
| 107 |
-
started_at: string
|
| 108 |
-
messages: Message[]
|
| 109 |
-
}
|
| 110 |
-
|
| 111 |
-
export interface LeadStats {
|
| 112 |
-
total_leads: number
|
| 113 |
-
hot_leads: number
|
| 114 |
-
warm_leads: number
|
| 115 |
-
qualified_leads: number
|
| 116 |
-
conversion_rate: number
|
| 117 |
-
}
|
| 118 |
-
|
| 119 |
-
export interface Tenant {
|
| 120 |
-
id: string
|
| 121 |
-
name: string
|
| 122 |
-
business_name?: string
|
| 123 |
-
business_type: 'product' | 'service' | 'hybrid'
|
| 124 |
-
ai_settings?: any
|
| 125 |
-
tone_of_voice?: string
|
| 126 |
-
sales_methodology?: string
|
| 127 |
-
custom_instructions?: string
|
| 128 |
-
banned_words?: string[]
|
| 129 |
-
booking_settings?: any
|
| 130 |
-
tokens_balance: number
|
| 131 |
-
is_active: boolean
|
| 132 |
-
manager_monthly_salary?: number
|
| 133 |
-
}
|
| 134 |
-
|
| 135 |
export const tenantsApi = {
|
| 136 |
getMe: async () => {
|
| 137 |
const response = await api.get<Tenant>('/api/v1/tenants/me')
|
|
|
|
| 1 |
import axios from 'axios'
|
| 2 |
|
| 3 |
+
// Import types from centralized types module
|
| 4 |
+
import type {
|
| 5 |
+
Lead,
|
| 6 |
+
Message,
|
| 7 |
+
Conversation,
|
| 8 |
+
Tenant,
|
| 9 |
+
LeadStats,
|
| 10 |
+
ProcessingStatus,
|
| 11 |
+
SenderType,
|
| 12 |
+
BusinessType,
|
| 13 |
+
AISummaryJson,
|
| 14 |
+
} from '@/types'
|
| 15 |
+
|
| 16 |
+
// Re-export types for backward compatibility
|
| 17 |
+
export type { Lead, Message, Conversation, Tenant, LeadStats }
|
| 18 |
+
export type { ProcessingStatus, SenderType, BusinessType, AISummaryJson }
|
| 19 |
+
|
| 20 |
const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000'
|
| 21 |
console.log('🔗 API URL:', API_BASE_URL)
|
| 22 |
|
|
|
|
| 57 |
}
|
| 58 |
)
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
export const tenantsApi = {
|
| 61 |
getMe: async () => {
|
| 62 |
const response = await api.get<Tenant>('/api/v1/tenants/me')
|
frontend/types/index.ts
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/**
|
| 2 |
+
* MicroFunnel Studio - Shared Types
|
| 3 |
+
*
|
| 4 |
+
* Центральное хранилище типов для всего frontend приложения.
|
| 5 |
+
* Все типы синхронизированы с backend моделями.
|
| 6 |
+
*/
|
| 7 |
+
|
| 8 |
+
// ============================================================================
|
| 9 |
+
// Enums & Constants
|
| 10 |
+
// ============================================================================
|
| 11 |
+
|
| 12 |
+
export type ProcessingStatus = 'idle' | 'analyzing' | 'generating' | 'error'
|
| 13 |
+
|
| 14 |
+
export type SenderType = 'user' | 'ai' | 'human_manager' | 'human'
|
| 15 |
+
|
| 16 |
+
export type BusinessType = 'product' | 'service' | 'hybrid'
|
| 17 |
+
|
| 18 |
+
export type HeatLevel = 'hot' | 'warm' | 'cold' | 'junk'
|
| 19 |
+
|
| 20 |
+
export type LeadStatus = 'new' | 'qualified' | 'in_progress' | 'closed_won' | 'closed_lost' | 'junk'
|
| 21 |
+
|
| 22 |
+
export type Psychotype = 'dominant' | 'influential' | 'steady' | 'conscientious' | 'unknown'
|
| 23 |
+
|
| 24 |
+
// ============================================================================
|
| 25 |
+
// AI Summary (11-point analysis)
|
| 26 |
+
// ============================================================================
|
| 27 |
+
|
| 28 |
+
export interface AISummaryJson {
|
| 29 |
+
// Hard Data
|
| 30 |
+
intent?: string
|
| 31 |
+
budget?: string
|
| 32 |
+
timeline?: string
|
| 33 |
+
authority?: string
|
| 34 |
+
location?: string
|
| 35 |
+
industry?: string
|
| 36 |
+
// Soft Data
|
| 37 |
+
pain_points?: string[]
|
| 38 |
+
psychotype?: string
|
| 39 |
+
heat_score?: number
|
| 40 |
+
// Strategy
|
| 41 |
+
objections?: string[]
|
| 42 |
+
hidden_signals?: string
|
| 43 |
+
recommendation?: string
|
| 44 |
+
draft_reply?: string
|
| 45 |
+
}
|
| 46 |
+
|
| 47 |
+
// ============================================================================
|
| 48 |
+
// Core Entities
|
| 49 |
+
// ============================================================================
|
| 50 |
+
|
| 51 |
+
export interface Lead {
|
| 52 |
+
id: string
|
| 53 |
+
tenant_id: string
|
| 54 |
+
name: string | null
|
| 55 |
+
telegram_id: string | null
|
| 56 |
+
whatsapp_id: string | null
|
| 57 |
+
email: string | null
|
| 58 |
+
linkedin_profile: string | null
|
| 59 |
+
linkedin_urn: string | null
|
| 60 |
+
status: string
|
| 61 |
+
heat_score: number
|
| 62 |
+
heat_level: string
|
| 63 |
+
psychotype: string
|
| 64 |
+
processing_status: ProcessingStatus
|
| 65 |
+
budget: string | null
|
| 66 |
+
authority: string | null
|
| 67 |
+
need: string | null
|
| 68 |
+
timeline: string | null
|
| 69 |
+
ai_summary_json: AISummaryJson
|
| 70 |
+
first_message_at: string
|
| 71 |
+
last_message_at: string
|
| 72 |
+
created_at: string
|
| 73 |
+
current_stage_id?: string | null
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
export interface Message {
|
| 77 |
+
id: string
|
| 78 |
+
conversation_id?: string
|
| 79 |
+
tenant_id?: string
|
| 80 |
+
sender_type: SenderType
|
| 81 |
+
content: string
|
| 82 |
+
created_at: string
|
| 83 |
+
prompt_tokens?: number | null
|
| 84 |
+
completion_tokens?: number | null
|
| 85 |
+
model_used?: string | null
|
| 86 |
+
tokens?: {
|
| 87 |
+
prompt: number
|
| 88 |
+
completion: number
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
export interface Conversation {
|
| 93 |
+
id: string
|
| 94 |
+
channel: string
|
| 95 |
+
is_active: boolean
|
| 96 |
+
human_takeover: boolean
|
| 97 |
+
started_at: string
|
| 98 |
+
messages: Message[]
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
export interface Tenant {
|
| 102 |
+
id: string
|
| 103 |
+
name: string
|
| 104 |
+
business_name?: string
|
| 105 |
+
business_type: BusinessType
|
| 106 |
+
ai_settings?: Record<string, unknown>
|
| 107 |
+
tone_of_voice?: string
|
| 108 |
+
sales_methodology?: string
|
| 109 |
+
custom_instructions?: string
|
| 110 |
+
banned_words?: string[]
|
| 111 |
+
booking_settings?: Record<string, unknown>
|
| 112 |
+
tokens_balance: number
|
| 113 |
+
is_active: boolean
|
| 114 |
+
manager_monthly_salary?: number
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
// ============================================================================
|
| 118 |
+
// Statistics & Analytics
|
| 119 |
+
// ============================================================================
|
| 120 |
+
|
| 121 |
+
export interface LeadStats {
|
| 122 |
+
total_leads: number
|
| 123 |
+
hot_leads: number
|
| 124 |
+
warm_leads: number
|
| 125 |
+
qualified_leads: number
|
| 126 |
+
conversion_rate: number
|
| 127 |
+
}
|
| 128 |
+
|
| 129 |
+
// ============================================================================
|
| 130 |
+
// User & Auth
|
| 131 |
+
// ============================================================================
|
| 132 |
+
|
| 133 |
+
export interface User {
|
| 134 |
+
id: string
|
| 135 |
+
email: string
|
| 136 |
+
full_name?: string
|
| 137 |
+
tenant_id: string
|
| 138 |
+
tenant_name: string
|
| 139 |
+
is_active: boolean
|
| 140 |
+
is_superuser: boolean
|
| 141 |
+
role: string
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
export interface AuthResponse {
|
| 145 |
+
access_token: string
|
| 146 |
+
token_type: string
|
| 147 |
+
user: User
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
// ============================================================================
|
| 151 |
+
// Products (Visual Commerce)
|
| 152 |
+
// ============================================================================
|
| 153 |
+
|
| 154 |
+
export interface Product {
|
| 155 |
+
id: string
|
| 156 |
+
tenant_id: string
|
| 157 |
+
name: string
|
| 158 |
+
description?: string
|
| 159 |
+
price: number
|
| 160 |
+
currency: string
|
| 161 |
+
image_url?: string
|
| 162 |
+
is_active: boolean
|
| 163 |
+
created_at: string
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
// ============================================================================
|
| 167 |
+
// Bookings
|
| 168 |
+
// ============================================================================
|
| 169 |
+
|
| 170 |
+
export interface Service {
|
| 171 |
+
id: string
|
| 172 |
+
tenant_id: string
|
| 173 |
+
name: string
|
| 174 |
+
duration_minutes: number
|
| 175 |
+
price?: number
|
| 176 |
+
description?: string
|
| 177 |
+
}
|
| 178 |
+
|
| 179 |
+
export interface Appointment {
|
| 180 |
+
id: string
|
| 181 |
+
service_id: string
|
| 182 |
+
lead_id: string
|
| 183 |
+
start_time: string
|
| 184 |
+
end_time: string
|
| 185 |
+
status: 'scheduled' | 'completed' | 'cancelled' | 'no_show'
|
| 186 |
+
notes?: string
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
// ============================================================================
|
| 190 |
+
// Sales Playbook
|
| 191 |
+
// ============================================================================
|
| 192 |
+
|
| 193 |
+
export interface SalesStage {
|
| 194 |
+
id: string
|
| 195 |
+
tenant_id: string
|
| 196 |
+
name: string
|
| 197 |
+
order: number
|
| 198 |
+
description?: string
|
| 199 |
+
goals?: string[]
|
| 200 |
+
questions?: string[]
|
| 201 |
+
objection_handlers?: string[]
|
| 202 |
+
}
|
| 203 |
+
|
| 204 |
+
// ============================================================================
|
| 205 |
+
// Notifications
|
| 206 |
+
// ============================================================================
|
| 207 |
+
|
| 208 |
+
export interface Notification {
|
| 209 |
+
id: string
|
| 210 |
+
tenant_id: string
|
| 211 |
+
type: string
|
| 212 |
+
title: string
|
| 213 |
+
message: string
|
| 214 |
+
is_read: boolean
|
| 215 |
+
created_at: string
|
| 216 |
+
data?: Record<string, unknown>
|
| 217 |
+
}
|