Spaces:
Running
Running
axeronis commited on
Commit ·
90be4ab
1
Parent(s): 526e04d
refactor: Webhook handlers + Pydantic schemas
Browse files- backend/app/api/meta_webhooks.py +85 -201
- backend/app/api/telegram_webhook.py +79 -143
- backend/app/schemas/__init__.py +67 -0
- backend/app/schemas/auth.py +81 -0
- backend/app/schemas/channels.py +86 -0
- backend/app/schemas/common.py +52 -0
- backend/app/services/message_processor.py +339 -0
backend/app/api/meta_webhooks.py
CHANGED
|
@@ -1,32 +1,30 @@
|
|
| 1 |
"""
|
| 2 |
Meta Official Webhook Handler (WhatsApp & Instagram).
|
|
|
|
|
|
|
| 3 |
Handles verification (GET) and event notifications (POST).
|
| 4 |
"""
|
| 5 |
|
| 6 |
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends, Query
|
| 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 |
import logging
|
| 13 |
|
| 14 |
from app.core.database import get_async_session, async_session_maker
|
| 15 |
from app.models.tenant import Tenant
|
| 16 |
-
from app.
|
| 17 |
-
from app.services.ai_core import get_ai_core
|
| 18 |
-
from app.core.config import settings
|
| 19 |
-
|
| 20 |
-
# Services
|
| 21 |
from app.services.meta_whatsapp import get_whatsapp_cloud_service
|
| 22 |
-
from app.services.
|
|
|
|
| 23 |
|
| 24 |
logger = logging.getLogger(__name__)
|
| 25 |
router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"])
|
| 26 |
|
| 27 |
-
|
|
|
|
| 28 |
# VERIFICATION (GET)
|
| 29 |
-
#
|
|
|
|
| 30 |
@router.get("/{tenant_id}")
|
| 31 |
async def verify_webhook(
|
| 32 |
tenant_id: UUID,
|
|
@@ -35,19 +33,12 @@ async def verify_webhook(
|
|
| 35 |
challenge: str = Query(alias="hub.challenge"),
|
| 36 |
session: AsyncSession = Depends(get_async_session)
|
| 37 |
):
|
| 38 |
-
"""
|
| 39 |
-
Handle Meta Webhook Verification Challenge.
|
| 40 |
-
Meta sends this to verify we own the endpoint.
|
| 41 |
-
"""
|
| 42 |
tenant = await session.get(Tenant, tenant_id)
|
| 43 |
if not tenant:
|
| 44 |
raise HTTPException(status_code=404, detail="Tenant not found")
|
| 45 |
-
|
| 46 |
-
# Check WhatsApp Config first, then Instagram
|
| 47 |
-
wa_verify = tenant.meta_wa_config.get("verify_token") if tenant.meta_wa_config else None
|
| 48 |
|
| 49 |
-
|
| 50 |
-
# Ideally we match against the configured token
|
| 51 |
|
| 52 |
if mode == "subscribe" and token == wa_verify:
|
| 53 |
logger.info(f"✅ Webhook Verified for Tenant {tenant_id}")
|
|
@@ -56,9 +47,10 @@ async def verify_webhook(
|
|
| 56 |
raise HTTPException(status_code=403, detail="Verification failed")
|
| 57 |
|
| 58 |
|
| 59 |
-
#
|
| 60 |
# EVENT NOTIFICATION (POST)
|
| 61 |
-
#
|
|
|
|
| 62 |
@router.post("/{tenant_id}")
|
| 63 |
async def handle_meta_webhook(
|
| 64 |
tenant_id: UUID,
|
|
@@ -66,243 +58,135 @@ async def handle_meta_webhook(
|
|
| 66 |
background_tasks: BackgroundTasks,
|
| 67 |
session: AsyncSession = Depends(get_async_session)
|
| 68 |
):
|
| 69 |
-
"""
|
| 70 |
-
Handle incoming events from Meta (WhatsApp & Instagram).
|
| 71 |
-
"""
|
| 72 |
try:
|
| 73 |
data = await request.json()
|
| 74 |
-
except Exception
|
| 75 |
raise HTTPException(status_code=400, detail="Invalid JSON")
|
| 76 |
-
|
| 77 |
-
# Log incoming (debug)
|
| 78 |
-
# logger.info(f"📩 Meta Webhook for {tenant_id}: {data}")
|
| 79 |
-
|
| 80 |
-
# Determine validation
|
| 81 |
tenant = await session.get(Tenant, tenant_id)
|
| 82 |
if not tenant:
|
| 83 |
return {"status": "ignored", "reason": "tenant_not_found"}
|
| 84 |
-
|
| 85 |
# Process in background
|
| 86 |
background_tasks.add_task(
|
| 87 |
process_meta_event,
|
| 88 |
tenant_id=tenant.id,
|
| 89 |
payload=data
|
| 90 |
)
|
| 91 |
-
|
| 92 |
return {"status": "ok"}
|
| 93 |
|
| 94 |
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
Identifies if it's WhatsApp or Instagram and routes accordingly.
|
| 99 |
-
"""
|
| 100 |
-
object_type = payload.get("object") # 'whatsapp_business' or 'instagram'
|
| 101 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
if object_type == "whatsapp_business":
|
| 103 |
await process_whatsapp_event(tenant_id, payload)
|
| 104 |
elif object_type == "instagram":
|
| 105 |
-
#
|
| 106 |
-
|
| 107 |
else:
|
| 108 |
logger.warning(f"Unknown Meta object type: {object_type}")
|
| 109 |
|
| 110 |
|
| 111 |
async def process_whatsapp_event(tenant_id: UUID, payload: dict):
|
| 112 |
-
"""
|
| 113 |
-
Process WhatsApp Business API specific structure.
|
| 114 |
-
"""
|
| 115 |
try:
|
| 116 |
entry = payload.get("entry", [])[0]
|
| 117 |
changes = entry.get("changes", [])[0]
|
| 118 |
value = changes.get("value", {})
|
| 119 |
|
| 120 |
-
# Check for messages
|
| 121 |
if "messages" not in value:
|
| 122 |
-
return
|
| 123 |
-
|
| 124 |
message = value["messages"][0]
|
| 125 |
contact = value.get("contacts", [])[0] if "contacts" in value else {}
|
| 126 |
|
| 127 |
-
sender_id = message.get("from")
|
| 128 |
sender_name = contact.get("profile", {}).get("name", f"User {sender_id}")
|
| 129 |
|
| 130 |
msg_type = message.get("type")
|
| 131 |
-
|
| 132 |
-
|
| 133 |
|
| 134 |
if msg_type == "text":
|
| 135 |
-
|
| 136 |
elif msg_type == "audio":
|
| 137 |
-
|
| 138 |
-
|
| 139 |
else:
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
#
|
| 143 |
-
await
|
| 144 |
tenant_id=tenant_id,
|
| 145 |
-
channel="whatsapp",
|
| 146 |
sender_id=sender_id,
|
| 147 |
sender_name=sender_name,
|
| 148 |
-
text=
|
| 149 |
-
|
| 150 |
-
is_voice=(msg_type == "audio")
|
| 151 |
)
|
| 152 |
-
|
| 153 |
except (IndexError, KeyError) as e:
|
| 154 |
logger.error(f"Error parsing WhatsApp payload: {e}")
|
| 155 |
|
| 156 |
|
| 157 |
-
async def
|
| 158 |
tenant_id: UUID,
|
| 159 |
-
channel: str,
|
| 160 |
sender_id: str,
|
| 161 |
sender_name: str,
|
| 162 |
text: str,
|
| 163 |
-
media_url: str = None,
|
| 164 |
is_voice: bool = False
|
| 165 |
):
|
| 166 |
-
"""
|
| 167 |
-
Generic logic to save message -> Generate AI Response -> Send back.
|
| 168 |
-
(Merged logic from old evolution_webhook)
|
| 169 |
-
"""
|
| 170 |
-
from app.services.llm_client import get_llm_client
|
| 171 |
-
|
| 172 |
-
logger.info(f"🔄 Processing {channel} message from {sender_id}: {text[:50]}...")
|
| 173 |
-
|
| 174 |
async with async_session_maker() as session:
|
| 175 |
-
tenant = await session.get(Tenant, tenant_id)
|
| 176 |
-
if not tenant:
|
| 177 |
-
return
|
| 178 |
-
|
| 179 |
-
# 1. FIND/CREATE LEAD
|
| 180 |
-
stmt = select(Lead).where(Lead.tenant_id == tenant.id, Lead.whatsapp_id == sender_id)
|
| 181 |
-
result = await session.execute(stmt)
|
| 182 |
-
lead = result.scalar_one_or_none()
|
| 183 |
-
|
| 184 |
-
if not lead:
|
| 185 |
-
lead = Lead(
|
| 186 |
-
tenant_id=tenant.id,
|
| 187 |
-
name=sender_name,
|
| 188 |
-
whatsapp_id=sender_id,
|
| 189 |
-
status="NEW",
|
| 190 |
-
processing_status="idle"
|
| 191 |
-
)
|
| 192 |
-
session.add(lead)
|
| 193 |
-
await session.flush()
|
| 194 |
-
|
| 195 |
-
lead.last_message_at = datetime.utcnow()
|
| 196 |
-
lead.processing_status = "analyzing"
|
| 197 |
-
session.add(lead)
|
| 198 |
-
|
| 199 |
-
# 2. FIND/CREATE CONVERSATION
|
| 200 |
-
stmt = select(Conversation).where(
|
| 201 |
-
Conversation.tenant_id == tenant.id,
|
| 202 |
-
Conversation.lead_id == lead.id
|
| 203 |
-
)
|
| 204 |
-
result = await session.execute(stmt)
|
| 205 |
-
conversation = result.scalar_one_or_none() # Assuming 1 active check logic simplified
|
| 206 |
-
|
| 207 |
-
if not conversation:
|
| 208 |
-
conversation = Conversation(
|
| 209 |
-
tenant_id=tenant.id,
|
| 210 |
-
lead_id=lead.id,
|
| 211 |
-
channel=channel,
|
| 212 |
-
is_active=True
|
| 213 |
-
)
|
| 214 |
-
session.add(conversation)
|
| 215 |
-
await session.flush()
|
| 216 |
-
|
| 217 |
-
# 3. SAVE USER MESSAGE
|
| 218 |
-
user_msg = Message(
|
| 219 |
-
tenant_id=tenant.id,
|
| 220 |
-
conversation_id=conversation.id,
|
| 221 |
-
sender_type="user",
|
| 222 |
-
content=text
|
| 223 |
-
)
|
| 224 |
-
session.add(user_msg)
|
| 225 |
-
await session.commit()
|
| 226 |
-
|
| 227 |
-
# 4. GENERATE AI RESPONSE
|
| 228 |
-
ai_core = get_ai_core()
|
| 229 |
-
|
| 230 |
-
# Fetch history
|
| 231 |
-
stmt = select(Message).where(Message.conversation_id == conversation.id).order_by(Message.created_at)
|
| 232 |
-
history = (await session.execute(stmt)).scalars().all()
|
| 233 |
-
|
| 234 |
-
response = await ai_core.generate_sales_response(
|
| 235 |
-
session=session,
|
| 236 |
-
tenant=tenant,
|
| 237 |
-
lead=lead,
|
| 238 |
-
user_message=text,
|
| 239 |
-
conversation_history=list(history)
|
| 240 |
-
)
|
| 241 |
-
|
| 242 |
-
response_text = response["text"]
|
| 243 |
-
|
| 244 |
-
# Parse Booking/Images (simplified for now)
|
| 245 |
-
# TODO: Add the Visual Commerce logic back
|
| 246 |
-
|
| 247 |
-
# 5. SAVE AI MESSAGE
|
| 248 |
-
ai_msg = Message(
|
| 249 |
-
tenant_id=tenant.id,
|
| 250 |
-
conversation_id=conversation.id,
|
| 251 |
-
sender_type="ai",
|
| 252 |
-
content=response_text,
|
| 253 |
-
status=MessageStatus.PENDING,
|
| 254 |
-
model_used=settings.GEMINI_MODEL
|
| 255 |
-
)
|
| 256 |
-
session.add(ai_msg)
|
| 257 |
-
await session.commit()
|
| 258 |
-
|
| 259 |
-
# 6. SEND RESPONSE VIA OFFICIAL API
|
| 260 |
-
success = False
|
| 261 |
try:
|
| 262 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 263 |
|
| 264 |
-
#
|
| 265 |
-
|
| 266 |
-
# For now: purely reactive. If input was voice -> output is voice.
|
| 267 |
-
should_send_voice = is_voice and settings.OPENAI_API_KEY
|
| 268 |
|
| 269 |
-
if
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
success = True
|
| 288 |
-
else:
|
| 289 |
-
await wa_service.send_text_message(
|
| 290 |
-
tenant=tenant,
|
| 291 |
-
to_phone=sender_id,
|
| 292 |
-
text=response_text
|
| 293 |
-
)
|
| 294 |
-
success = True
|
| 295 |
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
ai_msg.status = MessageStatus.SENT if success else MessageStatus.FAILED
|
| 299 |
-
lead.processing_status = "idle"
|
| 300 |
-
session.add(ai_msg)
|
| 301 |
-
session.add(lead)
|
| 302 |
-
await session.commit()
|
| 303 |
|
| 304 |
except Exception as e:
|
| 305 |
-
logger.error(f"
|
| 306 |
-
ai_msg.status = MessageStatus.FAILED
|
| 307 |
-
session.add(ai_msg)
|
| 308 |
-
await session.commit()
|
|
|
|
| 1 |
"""
|
| 2 |
Meta Official Webhook Handler (WhatsApp & Instagram).
|
| 3 |
+
|
| 4 |
+
Uses unified MessageProcessor for message handling.
|
| 5 |
Handles verification (GET) and event notifications (POST).
|
| 6 |
"""
|
| 7 |
|
| 8 |
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends, Query
|
| 9 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 10 |
from uuid import UUID
|
|
|
|
|
|
|
| 11 |
import logging
|
| 12 |
|
| 13 |
from app.core.database import get_async_session, async_session_maker
|
| 14 |
from app.models.tenant import Tenant
|
| 15 |
+
from app.services.message_processor import IncomingMessage, get_message_processor
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
from app.services.meta_whatsapp import get_whatsapp_cloud_service
|
| 17 |
+
from app.services.llm_client import get_llm_client
|
| 18 |
+
from app.core.config import settings
|
| 19 |
|
| 20 |
logger = logging.getLogger(__name__)
|
| 21 |
router = APIRouter(prefix="/webhook/meta", tags=["Meta Webhooks"])
|
| 22 |
|
| 23 |
+
|
| 24 |
+
# =========================================================================
|
| 25 |
# VERIFICATION (GET)
|
| 26 |
+
# =========================================================================
|
| 27 |
+
|
| 28 |
@router.get("/{tenant_id}")
|
| 29 |
async def verify_webhook(
|
| 30 |
tenant_id: UUID,
|
|
|
|
| 33 |
challenge: str = Query(alias="hub.challenge"),
|
| 34 |
session: AsyncSession = Depends(get_async_session)
|
| 35 |
):
|
| 36 |
+
"""Handle Meta Webhook Verification Challenge."""
|
|
|
|
|
|
|
|
|
|
| 37 |
tenant = await session.get(Tenant, tenant_id)
|
| 38 |
if not tenant:
|
| 39 |
raise HTTPException(status_code=404, detail="Tenant not found")
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
wa_verify = tenant.meta_wa_config.get("verify_token") if tenant.meta_wa_config else None
|
|
|
|
| 42 |
|
| 43 |
if mode == "subscribe" and token == wa_verify:
|
| 44 |
logger.info(f"✅ Webhook Verified for Tenant {tenant_id}")
|
|
|
|
| 47 |
raise HTTPException(status_code=403, detail="Verification failed")
|
| 48 |
|
| 49 |
|
| 50 |
+
# =========================================================================
|
| 51 |
# EVENT NOTIFICATION (POST)
|
| 52 |
+
# =========================================================================
|
| 53 |
+
|
| 54 |
@router.post("/{tenant_id}")
|
| 55 |
async def handle_meta_webhook(
|
| 56 |
tenant_id: UUID,
|
|
|
|
| 58 |
background_tasks: BackgroundTasks,
|
| 59 |
session: AsyncSession = Depends(get_async_session)
|
| 60 |
):
|
| 61 |
+
"""Handle incoming events from Meta (WhatsApp & Instagram)."""
|
|
|
|
|
|
|
| 62 |
try:
|
| 63 |
data = await request.json()
|
| 64 |
+
except Exception:
|
| 65 |
raise HTTPException(status_code=400, detail="Invalid JSON")
|
| 66 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
tenant = await session.get(Tenant, tenant_id)
|
| 68 |
if not tenant:
|
| 69 |
return {"status": "ignored", "reason": "tenant_not_found"}
|
| 70 |
+
|
| 71 |
# Process in background
|
| 72 |
background_tasks.add_task(
|
| 73 |
process_meta_event,
|
| 74 |
tenant_id=tenant.id,
|
| 75 |
payload=data
|
| 76 |
)
|
| 77 |
+
|
| 78 |
return {"status": "ok"}
|
| 79 |
|
| 80 |
|
| 81 |
+
# =========================================================================
|
| 82 |
+
# EVENT PROCESSING
|
| 83 |
+
# =========================================================================
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
+
async def process_meta_event(tenant_id: UUID, payload: dict):
|
| 86 |
+
"""Parse and route Meta event by platform."""
|
| 87 |
+
object_type = payload.get("object")
|
| 88 |
+
|
| 89 |
if object_type == "whatsapp_business":
|
| 90 |
await process_whatsapp_event(tenant_id, payload)
|
| 91 |
elif object_type == "instagram":
|
| 92 |
+
# TODO: Implement Instagram
|
| 93 |
+
logger.info("Instagram event received (not implemented)")
|
| 94 |
else:
|
| 95 |
logger.warning(f"Unknown Meta object type: {object_type}")
|
| 96 |
|
| 97 |
|
| 98 |
async def process_whatsapp_event(tenant_id: UUID, payload: dict):
|
| 99 |
+
"""Process WhatsApp Business API event."""
|
|
|
|
|
|
|
| 100 |
try:
|
| 101 |
entry = payload.get("entry", [])[0]
|
| 102 |
changes = entry.get("changes", [])[0]
|
| 103 |
value = changes.get("value", {})
|
| 104 |
|
|
|
|
| 105 |
if "messages" not in value:
|
| 106 |
+
return # Status update or other event
|
| 107 |
+
|
| 108 |
message = value["messages"][0]
|
| 109 |
contact = value.get("contacts", [])[0] if "contacts" in value else {}
|
| 110 |
|
| 111 |
+
sender_id = message.get("from")
|
| 112 |
sender_name = contact.get("profile", {}).get("name", f"User {sender_id}")
|
| 113 |
|
| 114 |
msg_type = message.get("type")
|
| 115 |
+
text = ""
|
| 116 |
+
is_voice = False
|
| 117 |
|
| 118 |
if msg_type == "text":
|
| 119 |
+
text = message["text"]["body"]
|
| 120 |
elif msg_type == "audio":
|
| 121 |
+
text = "[Voice Message]"
|
| 122 |
+
is_voice = True
|
| 123 |
else:
|
| 124 |
+
text = f"[{msg_type} message]"
|
| 125 |
+
|
| 126 |
+
# Use unified processor
|
| 127 |
+
await process_whatsapp_message(
|
| 128 |
tenant_id=tenant_id,
|
|
|
|
| 129 |
sender_id=sender_id,
|
| 130 |
sender_name=sender_name,
|
| 131 |
+
text=text,
|
| 132 |
+
is_voice=is_voice
|
|
|
|
| 133 |
)
|
| 134 |
+
|
| 135 |
except (IndexError, KeyError) as e:
|
| 136 |
logger.error(f"Error parsing WhatsApp payload: {e}")
|
| 137 |
|
| 138 |
|
| 139 |
+
async def process_whatsapp_message(
|
| 140 |
tenant_id: UUID,
|
|
|
|
| 141 |
sender_id: str,
|
| 142 |
sender_name: str,
|
| 143 |
text: str,
|
|
|
|
| 144 |
is_voice: bool = False
|
| 145 |
):
|
| 146 |
+
"""Process WhatsApp message using unified MessageProcessor."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
async with async_session_maker() as session:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
try:
|
| 149 |
+
tenant = await session.get(Tenant, tenant_id)
|
| 150 |
+
if not tenant:
|
| 151 |
+
logger.error(f"Tenant {tenant_id} not found")
|
| 152 |
+
return
|
| 153 |
+
|
| 154 |
+
# Build incoming message
|
| 155 |
+
incoming = IncomingMessage(
|
| 156 |
+
channel="whatsapp",
|
| 157 |
+
sender_id=sender_id,
|
| 158 |
+
sender_name=sender_name,
|
| 159 |
+
text=text,
|
| 160 |
+
is_voice=is_voice
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
# Process with unified MessageProcessor
|
| 164 |
+
processor = get_message_processor()
|
| 165 |
+
result = await processor.process(session, tenant, incoming)
|
| 166 |
|
| 167 |
+
# Send response via WhatsApp Cloud API
|
| 168 |
+
wa_service = get_whatsapp_cloud_service()
|
|
|
|
|
|
|
| 169 |
|
| 170 |
+
if result["is_voice_reply"] and settings.OPENAI_API_KEY:
|
| 171 |
+
# Send voice reply
|
| 172 |
+
try:
|
| 173 |
+
llm = get_llm_client()
|
| 174 |
+
audio_bytes = await llm.generate_speech(result["response_text"])
|
| 175 |
+
media_id = await wa_service.upload_media(tenant, audio_bytes)
|
| 176 |
+
await wa_service.send_audio_message(tenant, sender_id, media_id)
|
| 177 |
+
logger.info(f"🗣️ Voice reply sent to {sender_id}")
|
| 178 |
+
except Exception as e:
|
| 179 |
+
logger.error(f"Voice send failed, falling back to text: {e}")
|
| 180 |
+
await wa_service.send_text_message(tenant, sender_id, result["response_text"])
|
| 181 |
+
else:
|
| 182 |
+
# Send text reply
|
| 183 |
+
await wa_service.send_text_message(
|
| 184 |
+
tenant=tenant,
|
| 185 |
+
to_phone=sender_id,
|
| 186 |
+
text=result["response_text"]
|
| 187 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
+
logger.info(f"✅ WhatsApp reply sent to {sender_id}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
|
| 191 |
except Exception as e:
|
| 192 |
+
logger.error(f"Error processing WhatsApp message: {e}", exc_info=True)
|
|
|
|
|
|
|
|
|
backend/app/api/telegram_webhook.py
CHANGED
|
@@ -1,20 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
|
| 2 |
from sqlalchemy.ext.asyncio import AsyncSession
|
| 3 |
-
from sqlalchemy import select
|
| 4 |
from uuid import UUID
|
| 5 |
from datetime import datetime
|
| 6 |
import logging
|
|
|
|
| 7 |
|
| 8 |
-
from app.core.database import get_async_session
|
| 9 |
from app.models.tenant import Tenant
|
| 10 |
-
from app.
|
| 11 |
-
from app.services.ai_core import get_ai_core
|
| 12 |
from app.core.logging import get_logger
|
| 13 |
-
import
|
| 14 |
|
| 15 |
logger = get_logger(__name__)
|
| 16 |
router = APIRouter(prefix="/webhook/telegram", tags=["Telegram Webhooks"])
|
| 17 |
|
|
|
|
| 18 |
@router.post("/{tenant_id}")
|
| 19 |
async def handle_telegram_webhook(
|
| 20 |
tenant_id: UUID,
|
|
@@ -22,25 +28,23 @@ async def handle_telegram_webhook(
|
|
| 22 |
background_tasks: BackgroundTasks,
|
| 23 |
session: AsyncSession = Depends(get_async_session)
|
| 24 |
):
|
| 25 |
-
"""
|
| 26 |
-
Handle incoming Telegram updates.
|
| 27 |
-
"""
|
| 28 |
try:
|
| 29 |
data = await request.json()
|
| 30 |
except Exception as e:
|
| 31 |
raise HTTPException(status_code=400, detail="Invalid JSON")
|
| 32 |
-
|
| 33 |
# Check if it's a message
|
| 34 |
if "message" not in data:
|
| 35 |
return {"status": "ignored"}
|
| 36 |
-
|
| 37 |
message_data = data["message"]
|
| 38 |
logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
|
| 39 |
|
| 40 |
chat_id = str(message_data.get("chat", {}).get("id"))
|
| 41 |
text = message_data.get("text", "")
|
| 42 |
|
| 43 |
-
# Check for Voice OR Audio
|
| 44 |
voice = message_data.get("voice") or message_data.get("audio") or {}
|
| 45 |
voice_file_id = voice.get("file_id")
|
| 46 |
|
|
@@ -51,7 +55,7 @@ async def handle_telegram_webhook(
|
|
| 51 |
if not text and not voice_file_id:
|
| 52 |
logger.warning(f"⚠️ Ignored message with no text/voice. Keys: {list(message_data.keys())}")
|
| 53 |
return {"status": "no_text_or_voice"}
|
| 54 |
-
|
| 55 |
# Process in background
|
| 56 |
background_tasks.add_task(
|
| 57 |
process_telegram_message,
|
|
@@ -65,6 +69,7 @@ async def handle_telegram_webhook(
|
|
| 65 |
|
| 66 |
return {"status": "ok"}
|
| 67 |
|
|
|
|
| 68 |
async def process_telegram_message(
|
| 69 |
tenant_id: UUID,
|
| 70 |
chat_id: str,
|
|
@@ -73,157 +78,88 @@ async def process_telegram_message(
|
|
| 73 |
username: str,
|
| 74 |
first_name: str
|
| 75 |
):
|
| 76 |
-
"""
|
| 77 |
-
Background task: Process Telegram message -> AI -> Reply
|
| 78 |
-
"""
|
| 79 |
-
from app.core.database import async_session_maker
|
| 80 |
from app.services.telegram_service import telegram_service
|
| 81 |
|
| 82 |
async with async_session_maker() as session:
|
| 83 |
try:
|
| 84 |
-
# 1. Get Tenant &
|
| 85 |
tenant = await session.get(Tenant, tenant_id)
|
| 86 |
if not tenant:
|
| 87 |
-
logger.error(f"Tenant {tenant_id} not found
|
| 88 |
return
|
| 89 |
-
|
| 90 |
-
bot_token = tenant.telegram_bot_token # Assuming stored in Tenant model or config
|
| 91 |
-
if not bot_token:
|
| 92 |
-
# Fallback to global config if single tenant mode or dev
|
| 93 |
-
from app.core.config import settings
|
| 94 |
-
bot_token = settings.TELEGRAM_NOTIFICATION_TOKEN
|
| 95 |
|
|
|
|
| 96 |
if not bot_token:
|
| 97 |
-
logger.error(f"No Telegram token
|
| 98 |
return
|
| 99 |
-
|
| 100 |
-
# --- VOICE TRANSCRIPTION START ---
|
| 101 |
-
if voice_file_id:
|
| 102 |
-
try:
|
| 103 |
-
logger.info("🎤 Telegram Voice Message Detected. Fetching file...")
|
| 104 |
-
async with httpx.AsyncClient() as client:
|
| 105 |
-
# 1. Get File Path
|
| 106 |
-
file_res = await client.get(f"https://api.telegram.org/bot{bot_token}/getFile?file_id={voice_file_id}")
|
| 107 |
-
file_data = file_res.json()
|
| 108 |
-
if not file_data.get("ok"):
|
| 109 |
-
logger.error(f"Failed to get file path: {file_data}")
|
| 110 |
-
return
|
| 111 |
-
|
| 112 |
-
file_path = file_data["result"]["file_path"]
|
| 113 |
-
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
|
| 114 |
-
|
| 115 |
-
# 2. Download File
|
| 116 |
-
logger.info(f"⬇️ Downloading voice from {download_url}")
|
| 117 |
-
audio_res = await client.get(download_url)
|
| 118 |
-
audio_res.raise_for_status()
|
| 119 |
-
audio_bytes = audio_res.content
|
| 120 |
-
|
| 121 |
-
# 3. Transcribe
|
| 122 |
-
from app.services.llm_client import get_llm_client
|
| 123 |
-
gc = get_llm_client()
|
| 124 |
-
logger.info("🧠 Transcribing with Gemini...")
|
| 125 |
-
transcription = await gc.transcribe_audio(audio_bytes, mime_type="audio/ogg")
|
| 126 |
-
|
| 127 |
-
logger.info(f"✅ Transcription: {transcription}")
|
| 128 |
-
text = f"[Voice Message] {transcription}" # Prefix to indicate source
|
| 129 |
-
|
| 130 |
-
except Exception as e:
|
| 131 |
-
logger.error(f"❌ Voice processing failed: {e}")
|
| 132 |
-
text = "[Voice Message] (Не удалось распознать аудио)"
|
| 133 |
-
# --- VOICE TRANSCRIPTION END ---
|
| 134 |
-
|
| 135 |
-
# 2. Find/Create Lead
|
| 136 |
-
stmt = select(Lead).where(
|
| 137 |
-
Lead.tenant_id == tenant_id,
|
| 138 |
-
Lead.telegram_id == chat_id
|
| 139 |
-
)
|
| 140 |
-
result = await session.execute(stmt)
|
| 141 |
-
lead = result.scalar_one_or_none()
|
| 142 |
-
|
| 143 |
-
if not lead:
|
| 144 |
-
lead = Lead(
|
| 145 |
-
tenant_id=tenant_id,
|
| 146 |
-
telegram_id=chat_id,
|
| 147 |
-
name=f"{first_name} {username}".strip() or f"TG User {chat_id}",
|
| 148 |
-
status="NEW",
|
| 149 |
-
processing_status="idle"
|
| 150 |
-
)
|
| 151 |
-
session.add(lead)
|
| 152 |
-
await session.flush()
|
| 153 |
-
|
| 154 |
-
# 3. Find/Create Conversation
|
| 155 |
-
stmt_conv = select(Conversation).where(
|
| 156 |
-
Conversation.tenant_id == tenant_id,
|
| 157 |
-
Conversation.lead_id == lead.id,
|
| 158 |
-
Conversation.channel == "telegram",
|
| 159 |
-
Conversation.is_active == True
|
| 160 |
-
)
|
| 161 |
-
result_conv = await session.execute(stmt_conv)
|
| 162 |
-
conversation = result_conv.scalar_one_or_none()
|
| 163 |
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
is_active=True
|
| 170 |
-
)
|
| 171 |
-
session.add(conversation)
|
| 172 |
-
await session.flush()
|
| 173 |
-
|
| 174 |
-
# 4. Save User Message
|
| 175 |
-
user_msg = Message(
|
| 176 |
-
tenant_id=tenant_id,
|
| 177 |
-
conversation_id=conversation.id,
|
| 178 |
-
sender_type="user",
|
| 179 |
-
content=text
|
| 180 |
-
)
|
| 181 |
-
session.add(user_msg)
|
| 182 |
-
|
| 183 |
-
lead.last_message_at = datetime.utcnow()
|
| 184 |
-
lead.processing_status = "generating"
|
| 185 |
-
session.add(lead)
|
| 186 |
-
await session.commit()
|
| 187 |
-
|
| 188 |
-
# 5. Generate AI Response
|
| 189 |
-
ai_core = get_ai_core()
|
| 190 |
|
| 191 |
-
#
|
| 192 |
-
|
| 193 |
-
Message.conversation_id == conversation.id
|
| 194 |
-
).order_by(Message.created_at)
|
| 195 |
-
result_hist = await session.execute(stmt_hist)
|
| 196 |
-
history = list(result_hist.scalars().all())
|
| 197 |
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
)
|
| 205 |
|
| 206 |
-
#
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
conversation_id=conversation.id,
|
| 210 |
-
sender_type="ai",
|
| 211 |
-
content=response["text"],
|
| 212 |
-
prompt_tokens=response["prompt_tokens"],
|
| 213 |
-
completion_tokens=response["completion_tokens"],
|
| 214 |
-
model_used=settings.GEMINI_MODEL
|
| 215 |
-
)
|
| 216 |
-
session.add(ai_msg)
|
| 217 |
-
lead.processing_status = "idle"
|
| 218 |
-
session.add(lead)
|
| 219 |
-
await session.commit()
|
| 220 |
|
| 221 |
-
#
|
| 222 |
await telegram_service.send_message(
|
| 223 |
token=bot_token,
|
| 224 |
chat_id=chat_id,
|
| 225 |
-
text=
|
| 226 |
)
|
| 227 |
|
|
|
|
|
|
|
| 228 |
except Exception as e:
|
| 229 |
logger.error(f"Error processing Telegram message: {e}", exc_info=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Telegram Webhook Handler.
|
| 3 |
+
|
| 4 |
+
Uses unified MessageProcessor for message handling.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
from fastapi import APIRouter, Request, HTTPException, BackgroundTasks, Depends
|
| 8 |
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
| 9 |
from uuid import UUID
|
| 10 |
from datetime import datetime
|
| 11 |
import logging
|
| 12 |
+
import httpx
|
| 13 |
|
| 14 |
+
from app.core.database import get_async_session, async_session_maker
|
| 15 |
from app.models.tenant import Tenant
|
| 16 |
+
from app.services.message_processor import IncomingMessage, get_message_processor
|
|
|
|
| 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/telegram", tags=["Telegram Webhooks"])
|
| 22 |
|
| 23 |
+
|
| 24 |
@router.post("/{tenant_id}")
|
| 25 |
async def handle_telegram_webhook(
|
| 26 |
tenant_id: UUID,
|
|
|
|
| 28 |
background_tasks: BackgroundTasks,
|
| 29 |
session: AsyncSession = Depends(get_async_session)
|
| 30 |
):
|
| 31 |
+
"""Handle incoming Telegram updates."""
|
|
|
|
|
|
|
| 32 |
try:
|
| 33 |
data = await request.json()
|
| 34 |
except Exception as e:
|
| 35 |
raise HTTPException(status_code=400, detail="Invalid JSON")
|
| 36 |
+
|
| 37 |
# Check if it's a message
|
| 38 |
if "message" not in data:
|
| 39 |
return {"status": "ignored"}
|
| 40 |
+
|
| 41 |
message_data = data["message"]
|
| 42 |
logger.info(f"📩 Telegram Webhook: {list(data.keys())} | Msg Keys: {list(message_data.keys())}")
|
| 43 |
|
| 44 |
chat_id = str(message_data.get("chat", {}).get("id"))
|
| 45 |
text = message_data.get("text", "")
|
| 46 |
|
| 47 |
+
# Check for Voice OR Audio
|
| 48 |
voice = message_data.get("voice") or message_data.get("audio") or {}
|
| 49 |
voice_file_id = voice.get("file_id")
|
| 50 |
|
|
|
|
| 55 |
if not text and not voice_file_id:
|
| 56 |
logger.warning(f"⚠️ Ignored message with no text/voice. Keys: {list(message_data.keys())}")
|
| 57 |
return {"status": "no_text_or_voice"}
|
| 58 |
+
|
| 59 |
# Process in background
|
| 60 |
background_tasks.add_task(
|
| 61 |
process_telegram_message,
|
|
|
|
| 69 |
|
| 70 |
return {"status": "ok"}
|
| 71 |
|
| 72 |
+
|
| 73 |
async def process_telegram_message(
|
| 74 |
tenant_id: UUID,
|
| 75 |
chat_id: str,
|
|
|
|
| 78 |
username: str,
|
| 79 |
first_name: str
|
| 80 |
):
|
| 81 |
+
"""Background task: Process Telegram message using unified MessageProcessor."""
|
|
|
|
|
|
|
|
|
|
| 82 |
from app.services.telegram_service import telegram_service
|
| 83 |
|
| 84 |
async with async_session_maker() as session:
|
| 85 |
try:
|
| 86 |
+
# 1. Get Tenant & Bot Token
|
| 87 |
tenant = await session.get(Tenant, tenant_id)
|
| 88 |
if not tenant:
|
| 89 |
+
logger.error(f"Tenant {tenant_id} not found")
|
| 90 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
+
bot_token = tenant.telegram_bot_token or settings.TELEGRAM_NOTIFICATION_TOKEN
|
| 93 |
if not bot_token:
|
| 94 |
+
logger.error(f"No Telegram token for tenant {tenant_id}")
|
| 95 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
|
| 97 |
+
# 2. Transcribe voice if present
|
| 98 |
+
is_voice = False
|
| 99 |
+
if voice_file_id:
|
| 100 |
+
text = await transcribe_telegram_voice(bot_token, voice_file_id)
|
| 101 |
+
is_voice = True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
|
| 103 |
+
# 3. Build incoming message
|
| 104 |
+
sender_name = f"{first_name} {username}".strip() or f"TG User {chat_id}"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 105 |
|
| 106 |
+
incoming = IncomingMessage(
|
| 107 |
+
channel="telegram",
|
| 108 |
+
sender_id=chat_id,
|
| 109 |
+
sender_name=sender_name,
|
| 110 |
+
text=text,
|
| 111 |
+
is_voice=is_voice
|
| 112 |
)
|
| 113 |
|
| 114 |
+
# 4. Process with unified MessageProcessor
|
| 115 |
+
processor = get_message_processor()
|
| 116 |
+
result = await processor.process(session, tenant, incoming)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
+
# 5. Send response via Telegram
|
| 119 |
await telegram_service.send_message(
|
| 120 |
token=bot_token,
|
| 121 |
chat_id=chat_id,
|
| 122 |
+
text=result["response_text"]
|
| 123 |
)
|
| 124 |
|
| 125 |
+
logger.info(f"✅ Telegram reply sent to {chat_id}")
|
| 126 |
+
|
| 127 |
except Exception as e:
|
| 128 |
logger.error(f"Error processing Telegram message: {e}", exc_info=True)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
async def transcribe_telegram_voice(bot_token: str, file_id: str) -> str:
|
| 132 |
+
"""Download and transcribe Telegram voice message."""
|
| 133 |
+
try:
|
| 134 |
+
logger.info("🎤 Processing Telegram voice message...")
|
| 135 |
+
|
| 136 |
+
async with httpx.AsyncClient() as client:
|
| 137 |
+
# Get file path
|
| 138 |
+
file_res = await client.get(
|
| 139 |
+
f"https://api.telegram.org/bot{bot_token}/getFile?file_id={file_id}"
|
| 140 |
+
)
|
| 141 |
+
file_data = file_res.json()
|
| 142 |
+
|
| 143 |
+
if not file_data.get("ok"):
|
| 144 |
+
logger.error(f"Failed to get file path: {file_data}")
|
| 145 |
+
return "[Voice Message] (Ошибка загрузки)"
|
| 146 |
+
|
| 147 |
+
file_path = file_data["result"]["file_path"]
|
| 148 |
+
download_url = f"https://api.telegram.org/file/bot{bot_token}/{file_path}"
|
| 149 |
+
|
| 150 |
+
# Download file
|
| 151 |
+
audio_res = await client.get(download_url)
|
| 152 |
+
audio_res.raise_for_status()
|
| 153 |
+
audio_bytes = audio_res.content
|
| 154 |
+
|
| 155 |
+
# Transcribe with Gemini
|
| 156 |
+
from app.services.llm_client import get_llm_client
|
| 157 |
+
llm = get_llm_client()
|
| 158 |
+
transcription = await llm.transcribe_audio(audio_bytes, mime_type="audio/ogg")
|
| 159 |
+
|
| 160 |
+
logger.info(f"✅ Transcription: {transcription[:50]}...")
|
| 161 |
+
return f"[Voice] {transcription}"
|
| 162 |
+
|
| 163 |
+
except Exception as e:
|
| 164 |
+
logger.error(f"❌ Voice transcription failed: {e}")
|
| 165 |
+
return "[Voice Message] (Не удалось распознать)"
|
backend/app/schemas/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Schemas Package
|
| 3 |
+
|
| 4 |
+
Centralized Pydantic schemas for the API.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
# Common
|
| 8 |
+
from .common import (
|
| 9 |
+
SuccessResponse,
|
| 10 |
+
ErrorResponse,
|
| 11 |
+
PaginatedResponse,
|
| 12 |
+
StatusResponse,
|
| 13 |
+
ConnectionStatus
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
# Channels
|
| 17 |
+
from .channels import (
|
| 18 |
+
TelegramConnectRequest,
|
| 19 |
+
TelegramConnectResponse,
|
| 20 |
+
TelegramStatusResponse,
|
| 21 |
+
WhatsAppConnectRequest,
|
| 22 |
+
WhatsAppConnectResponse,
|
| 23 |
+
WhatsAppStatusResponse,
|
| 24 |
+
LinkedInConnectRequest,
|
| 25 |
+
LinkedInConnectResponse,
|
| 26 |
+
LinkedInStatusResponse
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Auth
|
| 30 |
+
from .auth import (
|
| 31 |
+
UserRegisterRequest,
|
| 32 |
+
UserRegisterResponse,
|
| 33 |
+
LoginRequest,
|
| 34 |
+
TokenResponse,
|
| 35 |
+
LoginResponse,
|
| 36 |
+
PasswordResetRequest,
|
| 37 |
+
PasswordResetConfirm,
|
| 38 |
+
UserProfileResponse
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
__all__ = [
|
| 42 |
+
# Common
|
| 43 |
+
"SuccessResponse",
|
| 44 |
+
"ErrorResponse",
|
| 45 |
+
"PaginatedResponse",
|
| 46 |
+
"StatusResponse",
|
| 47 |
+
"ConnectionStatus",
|
| 48 |
+
# Channels
|
| 49 |
+
"TelegramConnectRequest",
|
| 50 |
+
"TelegramConnectResponse",
|
| 51 |
+
"TelegramStatusResponse",
|
| 52 |
+
"WhatsAppConnectRequest",
|
| 53 |
+
"WhatsAppConnectResponse",
|
| 54 |
+
"WhatsAppStatusResponse",
|
| 55 |
+
"LinkedInConnectRequest",
|
| 56 |
+
"LinkedInConnectResponse",
|
| 57 |
+
"LinkedInStatusResponse",
|
| 58 |
+
# Auth
|
| 59 |
+
"UserRegisterRequest",
|
| 60 |
+
"UserRegisterResponse",
|
| 61 |
+
"LoginRequest",
|
| 62 |
+
"TokenResponse",
|
| 63 |
+
"LoginResponse",
|
| 64 |
+
"PasswordResetRequest",
|
| 65 |
+
"PasswordResetConfirm",
|
| 66 |
+
"UserProfileResponse"
|
| 67 |
+
]
|
backend/app/schemas/auth.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Authentication Schemas
|
| 3 |
+
|
| 4 |
+
Pydantic schemas for auth API.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Optional
|
| 8 |
+
from pydantic import BaseModel, EmailStr
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# =============================================================================
|
| 12 |
+
# Registration
|
| 13 |
+
# =============================================================================
|
| 14 |
+
|
| 15 |
+
class UserRegisterRequest(BaseModel):
|
| 16 |
+
"""User registration request."""
|
| 17 |
+
email: EmailStr
|
| 18 |
+
password: str
|
| 19 |
+
name: str
|
| 20 |
+
company_name: Optional[str] = None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class UserRegisterResponse(BaseModel):
|
| 24 |
+
"""User registration response."""
|
| 25 |
+
ok: bool
|
| 26 |
+
message: str
|
| 27 |
+
user_id: Optional[str] = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# =============================================================================
|
| 31 |
+
# Login
|
| 32 |
+
# =============================================================================
|
| 33 |
+
|
| 34 |
+
class LoginRequest(BaseModel):
|
| 35 |
+
"""User login request."""
|
| 36 |
+
email: EmailStr
|
| 37 |
+
password: str
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class TokenResponse(BaseModel):
|
| 41 |
+
"""JWT token response."""
|
| 42 |
+
access_token: str
|
| 43 |
+
token_type: str = "bearer"
|
| 44 |
+
expires_in: Optional[int] = None
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class LoginResponse(BaseModel):
|
| 48 |
+
"""Login response with user info."""
|
| 49 |
+
ok: bool
|
| 50 |
+
access_token: str
|
| 51 |
+
token_type: str = "bearer"
|
| 52 |
+
user: Optional[dict] = None
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# =============================================================================
|
| 56 |
+
# Password Reset
|
| 57 |
+
# =============================================================================
|
| 58 |
+
|
| 59 |
+
class PasswordResetRequest(BaseModel):
|
| 60 |
+
"""Password reset request."""
|
| 61 |
+
email: EmailStr
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class PasswordResetConfirm(BaseModel):
|
| 65 |
+
"""Password reset confirmation."""
|
| 66 |
+
token: str
|
| 67 |
+
new_password: str
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# =============================================================================
|
| 71 |
+
# User Profile
|
| 72 |
+
# =============================================================================
|
| 73 |
+
|
| 74 |
+
class UserProfileResponse(BaseModel):
|
| 75 |
+
"""Current user profile."""
|
| 76 |
+
id: str
|
| 77 |
+
email: str
|
| 78 |
+
name: str
|
| 79 |
+
role: str
|
| 80 |
+
tenant_id: Optional[str] = None
|
| 81 |
+
is_active: bool = True
|
backend/app/schemas/channels.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Channel Schemas
|
| 3 |
+
|
| 4 |
+
Pydantic schemas for channels API (Telegram, WhatsApp, LinkedIn).
|
| 5 |
+
Extracted from api/channels.py for better organization.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from typing import Optional
|
| 9 |
+
from pydantic import BaseModel
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
# =============================================================================
|
| 13 |
+
# Telegram
|
| 14 |
+
# =============================================================================
|
| 15 |
+
|
| 16 |
+
class TelegramConnectRequest(BaseModel):
|
| 17 |
+
"""Telegram bot connection request."""
|
| 18 |
+
bot_token: str
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class TelegramConnectResponse(BaseModel):
|
| 22 |
+
"""Telegram bot connection response."""
|
| 23 |
+
ok: bool
|
| 24 |
+
status: str
|
| 25 |
+
webhook_url: str
|
| 26 |
+
message: str
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class TelegramStatusResponse(BaseModel):
|
| 30 |
+
"""Telegram connection status."""
|
| 31 |
+
ok: bool
|
| 32 |
+
connected: bool
|
| 33 |
+
webhook_url: Optional[str] = None
|
| 34 |
+
bot_info: Optional[dict] = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# =============================================================================
|
| 38 |
+
# WhatsApp (Cloud API)
|
| 39 |
+
# =============================================================================
|
| 40 |
+
|
| 41 |
+
class WhatsAppConnectRequest(BaseModel):
|
| 42 |
+
"""WhatsApp Cloud API connection request."""
|
| 43 |
+
access_token: str
|
| 44 |
+
phone_number_id: str
|
| 45 |
+
business_account_id: str
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class WhatsAppConnectResponse(BaseModel):
|
| 49 |
+
"""WhatsApp connection response."""
|
| 50 |
+
ok: bool
|
| 51 |
+
status: str
|
| 52 |
+
message: str
|
| 53 |
+
phone_number_id: Optional[str] = None
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class WhatsAppStatusResponse(BaseModel):
|
| 57 |
+
"""WhatsApp connection status."""
|
| 58 |
+
connected: bool
|
| 59 |
+
status: str
|
| 60 |
+
phone_number_id: Optional[str] = None
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# =============================================================================
|
| 64 |
+
# LinkedIn
|
| 65 |
+
# =============================================================================
|
| 66 |
+
|
| 67 |
+
class LinkedInConnectRequest(BaseModel):
|
| 68 |
+
"""LinkedIn channel connection request."""
|
| 69 |
+
access_token: str
|
| 70 |
+
organization_id: str = "personal"
|
| 71 |
+
verify_token: str
|
| 72 |
+
jsession_id: Optional[str] = None
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
class LinkedInConnectResponse(BaseModel):
|
| 76 |
+
"""LinkedIn connection response."""
|
| 77 |
+
ok: bool
|
| 78 |
+
status: str
|
| 79 |
+
message: str
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class LinkedInStatusResponse(BaseModel):
|
| 83 |
+
"""LinkedIn connection status."""
|
| 84 |
+
ok: bool
|
| 85 |
+
connected: bool
|
| 86 |
+
config: Optional[dict] = None
|
backend/app/schemas/common.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Common Pydantic Schemas
|
| 3 |
+
|
| 4 |
+
Shared response models and base schemas for the API.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from typing import Optional, Any, List
|
| 8 |
+
from pydantic import BaseModel
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# =============================================================================
|
| 12 |
+
# Base Response Models
|
| 13 |
+
# =============================================================================
|
| 14 |
+
|
| 15 |
+
class SuccessResponse(BaseModel):
|
| 16 |
+
"""Standard success response."""
|
| 17 |
+
ok: bool = True
|
| 18 |
+
message: Optional[str] = None
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ErrorResponse(BaseModel):
|
| 22 |
+
"""Standard error response."""
|
| 23 |
+
ok: bool = False
|
| 24 |
+
detail: str
|
| 25 |
+
code: Optional[str] = None
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class PaginatedResponse(BaseModel):
|
| 29 |
+
"""Paginated list response."""
|
| 30 |
+
items: List[Any]
|
| 31 |
+
total: int
|
| 32 |
+
page: int
|
| 33 |
+
page_size: int
|
| 34 |
+
has_more: bool
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# =============================================================================
|
| 38 |
+
# Status Responses
|
| 39 |
+
# =============================================================================
|
| 40 |
+
|
| 41 |
+
class StatusResponse(BaseModel):
|
| 42 |
+
"""Generic status response."""
|
| 43 |
+
ok: bool
|
| 44 |
+
status: str
|
| 45 |
+
message: Optional[str] = None
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class ConnectionStatus(BaseModel):
|
| 49 |
+
"""Channel connection status."""
|
| 50 |
+
connected: bool
|
| 51 |
+
status: str
|
| 52 |
+
config: Optional[dict] = None
|
backend/app/services/message_processor.py
ADDED
|
@@ -0,0 +1,339 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Message Processor Service
|
| 3 |
+
|
| 4 |
+
Unified message processing logic for all webhook handlers.
|
| 5 |
+
Handles: Lead/Conversation lookup, message storage, AI response, sending.
|
| 6 |
+
|
| 7 |
+
Used by:
|
| 8 |
+
- telegram_webhook.py
|
| 9 |
+
- meta_webhooks.py
|
| 10 |
+
- webhook.py (email)
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from typing import List, Optional, Dict, Any
|
| 14 |
+
from uuid import UUID
|
| 15 |
+
from datetime import datetime
|
| 16 |
+
from sqlalchemy.ext.asyncio import AsyncSession
|
| 17 |
+
from sqlalchemy import select
|
| 18 |
+
import logging
|
| 19 |
+
|
| 20 |
+
from app.models.tenant import Tenant
|
| 21 |
+
from app.models.lead import Lead, Message, Conversation, MessageStatus
|
| 22 |
+
from app.services.ai_core import get_ai_core
|
| 23 |
+
from app.core.config import settings
|
| 24 |
+
|
| 25 |
+
logger = logging.getLogger(__name__)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
# =============================================================================
|
| 29 |
+
# Data Classes for Clean Interface
|
| 30 |
+
# =============================================================================
|
| 31 |
+
|
| 32 |
+
class IncomingMessage:
|
| 33 |
+
"""Represents an incoming message from any channel."""
|
| 34 |
+
|
| 35 |
+
def __init__(
|
| 36 |
+
self,
|
| 37 |
+
channel: str, # "telegram", "whatsapp", "instagram", "email"
|
| 38 |
+
sender_id: str, # Unique ID (phone, telegram_id, email)
|
| 39 |
+
sender_name: str,
|
| 40 |
+
text: str,
|
| 41 |
+
is_voice: bool = False,
|
| 42 |
+
media_url: Optional[str] = None,
|
| 43 |
+
raw_payload: Optional[Dict[str, Any]] = None
|
| 44 |
+
):
|
| 45 |
+
self.channel = channel
|
| 46 |
+
self.sender_id = sender_id
|
| 47 |
+
self.sender_name = sender_name
|
| 48 |
+
self.text = text
|
| 49 |
+
self.is_voice = is_voice
|
| 50 |
+
self.media_url = media_url
|
| 51 |
+
self.raw_payload = raw_payload or {}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# =============================================================================
|
| 55 |
+
# Lead/Conversation Management
|
| 56 |
+
# =============================================================================
|
| 57 |
+
|
| 58 |
+
async def get_or_create_lead(
|
| 59 |
+
session: AsyncSession,
|
| 60 |
+
tenant_id: UUID,
|
| 61 |
+
channel: str,
|
| 62 |
+
sender_id: str,
|
| 63 |
+
sender_name: str
|
| 64 |
+
) -> Lead:
|
| 65 |
+
"""
|
| 66 |
+
Find existing lead or create new one.
|
| 67 |
+
|
| 68 |
+
Matches by channel-specific ID (telegram_id, whatsapp_id, email).
|
| 69 |
+
"""
|
| 70 |
+
# Build query based on channel
|
| 71 |
+
if channel == "telegram":
|
| 72 |
+
stmt = select(Lead).where(
|
| 73 |
+
Lead.tenant_id == tenant_id,
|
| 74 |
+
Lead.telegram_id == sender_id
|
| 75 |
+
)
|
| 76 |
+
elif channel in ("whatsapp", "instagram"):
|
| 77 |
+
stmt = select(Lead).where(
|
| 78 |
+
Lead.tenant_id == tenant_id,
|
| 79 |
+
Lead.whatsapp_id == sender_id
|
| 80 |
+
)
|
| 81 |
+
else: # email
|
| 82 |
+
stmt = select(Lead).where(
|
| 83 |
+
Lead.tenant_id == tenant_id,
|
| 84 |
+
Lead.email == sender_id
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
result = await session.execute(stmt)
|
| 88 |
+
lead = result.scalar_one_or_none()
|
| 89 |
+
|
| 90 |
+
if not lead:
|
| 91 |
+
# Create new lead with channel-specific ID
|
| 92 |
+
lead_data = {
|
| 93 |
+
"tenant_id": tenant_id,
|
| 94 |
+
"name": sender_name,
|
| 95 |
+
"status": "NEW",
|
| 96 |
+
"processing_status": "idle"
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
if channel == "telegram":
|
| 100 |
+
lead_data["telegram_id"] = sender_id
|
| 101 |
+
elif channel in ("whatsapp", "instagram"):
|
| 102 |
+
lead_data["whatsapp_id"] = sender_id
|
| 103 |
+
else:
|
| 104 |
+
lead_data["email"] = sender_id
|
| 105 |
+
|
| 106 |
+
lead = Lead(**lead_data)
|
| 107 |
+
session.add(lead)
|
| 108 |
+
await session.flush()
|
| 109 |
+
logger.info(f"✨ Created new lead {lead.id} for {channel}:{sender_id}")
|
| 110 |
+
|
| 111 |
+
return lead
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
async def get_or_create_conversation(
|
| 115 |
+
session: AsyncSession,
|
| 116 |
+
tenant_id: UUID,
|
| 117 |
+
lead_id: UUID,
|
| 118 |
+
channel: str
|
| 119 |
+
) -> Conversation:
|
| 120 |
+
"""Find active conversation or create new one."""
|
| 121 |
+
stmt = select(Conversation).where(
|
| 122 |
+
Conversation.tenant_id == tenant_id,
|
| 123 |
+
Conversation.lead_id == lead_id,
|
| 124 |
+
Conversation.channel == channel,
|
| 125 |
+
Conversation.is_active == True
|
| 126 |
+
)
|
| 127 |
+
result = await session.execute(stmt)
|
| 128 |
+
conversation = result.scalar_one_or_none()
|
| 129 |
+
|
| 130 |
+
if not conversation:
|
| 131 |
+
conversation = Conversation(
|
| 132 |
+
tenant_id=tenant_id,
|
| 133 |
+
lead_id=lead_id,
|
| 134 |
+
channel=channel,
|
| 135 |
+
is_active=True
|
| 136 |
+
)
|
| 137 |
+
session.add(conversation)
|
| 138 |
+
await session.flush()
|
| 139 |
+
logger.info(f"✨ Created new conversation {conversation.id}")
|
| 140 |
+
|
| 141 |
+
return conversation
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
async def get_conversation_history(
|
| 145 |
+
session: AsyncSession,
|
| 146 |
+
conversation_id: UUID
|
| 147 |
+
) -> List[Message]:
|
| 148 |
+
"""Get all messages in conversation ordered by time."""
|
| 149 |
+
stmt = select(Message).where(
|
| 150 |
+
Message.conversation_id == conversation_id
|
| 151 |
+
).order_by(Message.created_at)
|
| 152 |
+
|
| 153 |
+
result = await session.execute(stmt)
|
| 154 |
+
return list(result.scalars().all())
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
# =============================================================================
|
| 158 |
+
# Message Processing
|
| 159 |
+
# =============================================================================
|
| 160 |
+
|
| 161 |
+
async def save_user_message(
|
| 162 |
+
session: AsyncSession,
|
| 163 |
+
tenant_id: UUID,
|
| 164 |
+
conversation_id: UUID,
|
| 165 |
+
text: str
|
| 166 |
+
) -> Message:
|
| 167 |
+
"""Save incoming user message to database."""
|
| 168 |
+
message = Message(
|
| 169 |
+
tenant_id=tenant_id,
|
| 170 |
+
conversation_id=conversation_id,
|
| 171 |
+
sender_type="user",
|
| 172 |
+
content=text
|
| 173 |
+
)
|
| 174 |
+
session.add(message)
|
| 175 |
+
await session.flush()
|
| 176 |
+
return message
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
async def save_ai_message(
|
| 180 |
+
session: AsyncSession,
|
| 181 |
+
tenant_id: UUID,
|
| 182 |
+
conversation_id: UUID,
|
| 183 |
+
text: str,
|
| 184 |
+
tokens: Dict[str, int] = None
|
| 185 |
+
) -> Message:
|
| 186 |
+
"""Save AI response message to database."""
|
| 187 |
+
tokens = tokens or {}
|
| 188 |
+
message = Message(
|
| 189 |
+
tenant_id=tenant_id,
|
| 190 |
+
conversation_id=conversation_id,
|
| 191 |
+
sender_type="ai",
|
| 192 |
+
content=text,
|
| 193 |
+
prompt_tokens=tokens.get("prompt_tokens"),
|
| 194 |
+
completion_tokens=tokens.get("completion_tokens"),
|
| 195 |
+
model_used=settings.GEMINI_MODEL,
|
| 196 |
+
status=MessageStatus.PENDING
|
| 197 |
+
)
|
| 198 |
+
session.add(message)
|
| 199 |
+
await session.flush()
|
| 200 |
+
return message
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
async def generate_ai_response(
|
| 204 |
+
session: AsyncSession,
|
| 205 |
+
tenant: Tenant,
|
| 206 |
+
lead: Lead,
|
| 207 |
+
user_message: str,
|
| 208 |
+
conversation_history: List[Message]
|
| 209 |
+
) -> Dict[str, Any]:
|
| 210 |
+
"""Generate AI sales response using AICore."""
|
| 211 |
+
ai_core = get_ai_core()
|
| 212 |
+
|
| 213 |
+
response = await ai_core.generate_sales_response(
|
| 214 |
+
session=session,
|
| 215 |
+
tenant=tenant,
|
| 216 |
+
lead=lead,
|
| 217 |
+
user_message=user_message,
|
| 218 |
+
conversation_history=conversation_history
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
return response
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
# =============================================================================
|
| 225 |
+
# Main Processing Function
|
| 226 |
+
# =============================================================================
|
| 227 |
+
|
| 228 |
+
async def process_incoming_message(
|
| 229 |
+
session: AsyncSession,
|
| 230 |
+
tenant: Tenant,
|
| 231 |
+
message: IncomingMessage
|
| 232 |
+
) -> Dict[str, Any]:
|
| 233 |
+
"""
|
| 234 |
+
Unified message processing pipeline.
|
| 235 |
+
|
| 236 |
+
Steps:
|
| 237 |
+
1. Find/Create Lead
|
| 238 |
+
2. Find/Create Conversation
|
| 239 |
+
3. Save User Message
|
| 240 |
+
4. Generate AI Response
|
| 241 |
+
5. Save AI Message
|
| 242 |
+
6. Return response for sending
|
| 243 |
+
|
| 244 |
+
Returns:
|
| 245 |
+
Dict with keys: lead, conversation, user_message, ai_message, response_text
|
| 246 |
+
"""
|
| 247 |
+
# 1. Find/Create Lead
|
| 248 |
+
lead = await get_or_create_lead(
|
| 249 |
+
session=session,
|
| 250 |
+
tenant_id=tenant.id,
|
| 251 |
+
channel=message.channel,
|
| 252 |
+
sender_id=message.sender_id,
|
| 253 |
+
sender_name=message.sender_name
|
| 254 |
+
)
|
| 255 |
+
|
| 256 |
+
lead.last_message_at = datetime.utcnow()
|
| 257 |
+
lead.processing_status = "generating"
|
| 258 |
+
session.add(lead)
|
| 259 |
+
|
| 260 |
+
# 2. Find/Create Conversation
|
| 261 |
+
conversation = await get_or_create_conversation(
|
| 262 |
+
session=session,
|
| 263 |
+
tenant_id=tenant.id,
|
| 264 |
+
lead_id=lead.id,
|
| 265 |
+
channel=message.channel
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
# 3. Save User Message
|
| 269 |
+
user_msg = await save_user_message(
|
| 270 |
+
session=session,
|
| 271 |
+
tenant_id=tenant.id,
|
| 272 |
+
conversation_id=conversation.id,
|
| 273 |
+
text=message.text
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
await session.commit()
|
| 277 |
+
|
| 278 |
+
# 4. Get History & Generate AI Response
|
| 279 |
+
history = await get_conversation_history(session, conversation.id)
|
| 280 |
+
|
| 281 |
+
response = await generate_ai_response(
|
| 282 |
+
session=session,
|
| 283 |
+
tenant=tenant,
|
| 284 |
+
lead=lead,
|
| 285 |
+
user_message=message.text,
|
| 286 |
+
conversation_history=history
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
# 5. Save AI Message
|
| 290 |
+
ai_msg = await save_ai_message(
|
| 291 |
+
session=session,
|
| 292 |
+
tenant_id=tenant.id,
|
| 293 |
+
conversation_id=conversation.id,
|
| 294 |
+
text=response["text"],
|
| 295 |
+
tokens={
|
| 296 |
+
"prompt_tokens": response.get("prompt_tokens"),
|
| 297 |
+
"completion_tokens": response.get("completion_tokens")
|
| 298 |
+
}
|
| 299 |
+
)
|
| 300 |
+
|
| 301 |
+
lead.processing_status = "idle"
|
| 302 |
+
session.add(lead)
|
| 303 |
+
await session.commit()
|
| 304 |
+
|
| 305 |
+
return {
|
| 306 |
+
"lead": lead,
|
| 307 |
+
"conversation": conversation,
|
| 308 |
+
"user_message": user_msg,
|
| 309 |
+
"ai_message": ai_msg,
|
| 310 |
+
"response_text": response["text"],
|
| 311 |
+
"is_voice_reply": message.is_voice
|
| 312 |
+
}
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
# =============================================================================
|
| 316 |
+
# Singleton
|
| 317 |
+
# =============================================================================
|
| 318 |
+
|
| 319 |
+
class MessageProcessor:
|
| 320 |
+
"""Facade for message processing service."""
|
| 321 |
+
|
| 322 |
+
async def process(
|
| 323 |
+
self,
|
| 324 |
+
session: AsyncSession,
|
| 325 |
+
tenant: Tenant,
|
| 326 |
+
message: IncomingMessage
|
| 327 |
+
) -> Dict[str, Any]:
|
| 328 |
+
return await process_incoming_message(session, tenant, message)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
_processor_instance: Optional[MessageProcessor] = None
|
| 332 |
+
|
| 333 |
+
|
| 334 |
+
def get_message_processor() -> MessageProcessor:
|
| 335 |
+
"""Get message processor instance."""
|
| 336 |
+
global _processor_instance
|
| 337 |
+
if _processor_instance is None:
|
| 338 |
+
_processor_instance = MessageProcessor()
|
| 339 |
+
return _processor_instance
|