Spaces:
Running
Running
axeronis commited on
Commit ·
bc65edb
1
Parent(s): 95a8757
feat: resource-specific booking and notifications + unified ai_identity
Browse files
backend/app/api/webhook.py
CHANGED
|
@@ -1221,10 +1221,11 @@ async def process_ai_response_background(
|
|
| 1221 |
# --- BOOKING INTERCEPTION START ---
|
| 1222 |
import re
|
| 1223 |
from datetime import datetime
|
| 1224 |
-
from app.models.booking import Appointment, AppointmentStatus, Service #
|
| 1225 |
|
| 1226 |
ai_text = ai_response["text"]
|
| 1227 |
-
|
|
|
|
| 1228 |
|
| 1229 |
if booking_match:
|
| 1230 |
try:
|
|
@@ -1347,10 +1348,33 @@ async def process_ai_response_background(
|
|
| 1347 |
notes_parts.append(f"Тема: {booking_info['topic']}")
|
| 1348 |
notes = " | ".join(notes_parts)
|
| 1349 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1350 |
new_appt = Appointment(
|
| 1351 |
tenant_id=tenant_id,
|
| 1352 |
lead_id=lead_id,
|
| 1353 |
service_id=default_srv.id,
|
|
|
|
| 1354 |
start_time=start_time,
|
| 1355 |
end_time=end_time,
|
| 1356 |
status=AppointmentStatus.SCHEDULED,
|
|
@@ -1359,19 +1383,28 @@ async def process_ai_response_background(
|
|
| 1359 |
session.add(new_appt)
|
| 1360 |
await session.commit()
|
| 1361 |
|
| 1362 |
-
logger.info(f"📅 AI Booked Appointment: {date_str} for Lead {lead_id}"
|
|
|
|
| 1363 |
|
| 1364 |
-
# 🔔 NOTIFY
|
| 1365 |
if not is_rescheduled:
|
| 1366 |
try:
|
| 1367 |
from app.services.notification import notification_service
|
| 1368 |
new_appt.lead = lead
|
| 1369 |
new_appt.service = default_srv
|
| 1370 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1371 |
await notification_service.notify_new_appointment(
|
| 1372 |
tenant,
|
| 1373 |
new_appt,
|
| 1374 |
-
ai_summary=lead.ai_summary_json
|
|
|
|
| 1375 |
)
|
| 1376 |
except Exception as ns_err:
|
| 1377 |
logger.error(f"⚠️ Notification failed: {ns_err}")
|
|
@@ -1390,6 +1423,7 @@ async def process_ai_response_background(
|
|
| 1390 |
ai_response["text"] += "\n\n⚠️ (Система: Ошибка при сохранении записи. Менеджер свяжется с вами.)"
|
| 1391 |
# --- BOOKING INTERCEPTION END ---
|
| 1392 |
|
|
|
|
| 1393 |
# --- ORDER INTERCEPTION START ---
|
| 1394 |
import json
|
| 1395 |
from app.models.order import Order, OrderItem, OrderStatus
|
|
|
|
| 1221 |
# --- BOOKING INTERCEPTION START ---
|
| 1222 |
import re
|
| 1223 |
from datetime import datetime
|
| 1224 |
+
from app.models.booking import Appointment, AppointmentStatus, Service, Resource # Added Resource
|
| 1225 |
|
| 1226 |
ai_text = ai_response["text"]
|
| 1227 |
+
# Updated regex to capture optional resource: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM] or [BOOK_CONFIRMED: YYYY-MM-DD HH:MM | Resource Name]
|
| 1228 |
+
booking_match = re.search(r'\[BOOK_CONFIRMED:\s*([\d\-]+\s[\d:]+)(?:\s*\|\s*(.+?))?\]', ai_text)
|
| 1229 |
|
| 1230 |
if booking_match:
|
| 1231 |
try:
|
|
|
|
| 1348 |
notes_parts.append(f"Тема: {booking_info['topic']}")
|
| 1349 |
notes = " | ".join(notes_parts)
|
| 1350 |
|
| 1351 |
+
# RESOURCE LOOKUP: Find resource by name if specified in tag
|
| 1352 |
+
resource_name = booking_match.group(2) if booking_match.lastindex >= 2 else None
|
| 1353 |
+
resource_id = None
|
| 1354 |
+
selected_resource = None
|
| 1355 |
+
|
| 1356 |
+
if resource_name:
|
| 1357 |
+
resource_name = resource_name.strip()
|
| 1358 |
+
# Search for resource by name (case-insensitive partial match)
|
| 1359 |
+
resource_stmt = select(Resource).where(
|
| 1360 |
+
Resource.tenant_id == tenant_id,
|
| 1361 |
+
Resource.is_active == True,
|
| 1362 |
+
Resource.name.ilike(f"%{resource_name}%")
|
| 1363 |
+
)
|
| 1364 |
+
resource_result = await session.execute(resource_stmt)
|
| 1365 |
+
selected_resource = resource_result.scalar_one_or_none()
|
| 1366 |
+
|
| 1367 |
+
if selected_resource:
|
| 1368 |
+
resource_id = selected_resource.id
|
| 1369 |
+
logger.info(f"📌 Booking to resource: {selected_resource.name} (ID: {resource_id})")
|
| 1370 |
+
else:
|
| 1371 |
+
logger.warning(f"⚠️ Resource '{resource_name}' not found, booking without resource")
|
| 1372 |
+
|
| 1373 |
new_appt = Appointment(
|
| 1374 |
tenant_id=tenant_id,
|
| 1375 |
lead_id=lead_id,
|
| 1376 |
service_id=default_srv.id,
|
| 1377 |
+
resource_id=resource_id, # Now saves resource!
|
| 1378 |
start_time=start_time,
|
| 1379 |
end_time=end_time,
|
| 1380 |
status=AppointmentStatus.SCHEDULED,
|
|
|
|
| 1383 |
session.add(new_appt)
|
| 1384 |
await session.commit()
|
| 1385 |
|
| 1386 |
+
logger.info(f"📅 AI Booked Appointment: {date_str} for Lead {lead_id}" +
|
| 1387 |
+
(f" with Resource {resource_name}" if resource_name else ""))
|
| 1388 |
|
| 1389 |
+
# 🔔 NOTIFY: Send to resource owner if telegram_chat_id set, else to tenant
|
| 1390 |
if not is_rescheduled:
|
| 1391 |
try:
|
| 1392 |
from app.services.notification import notification_service
|
| 1393 |
new_appt.lead = lead
|
| 1394 |
new_appt.service = default_srv
|
| 1395 |
+
|
| 1396 |
+
# Determine notification target
|
| 1397 |
+
resource_telegram_id = None
|
| 1398 |
+
if selected_resource and selected_resource.telegram_chat_id:
|
| 1399 |
+
resource_telegram_id = selected_resource.telegram_chat_id
|
| 1400 |
+
logger.info(f"📱 Sending notification to resource: {selected_resource.name} ({resource_telegram_id})")
|
| 1401 |
+
|
| 1402 |
+
# Pass AI summary and resource notification target
|
| 1403 |
await notification_service.notify_new_appointment(
|
| 1404 |
tenant,
|
| 1405 |
new_appt,
|
| 1406 |
+
ai_summary=lead.ai_summary_json,
|
| 1407 |
+
resource_telegram_id=resource_telegram_id # New: notify resource directly
|
| 1408 |
)
|
| 1409 |
except Exception as ns_err:
|
| 1410 |
logger.error(f"⚠️ Notification failed: {ns_err}")
|
|
|
|
| 1423 |
ai_response["text"] += "\n\n⚠️ (Система: Ошибка при сохранении записи. Менеджер свяжется с вами.)"
|
| 1424 |
# --- BOOKING INTERCEPTION END ---
|
| 1425 |
|
| 1426 |
+
|
| 1427 |
# --- ORDER INTERCEPTION START ---
|
| 1428 |
import json
|
| 1429 |
from app.models.order import Order, OrderItem, OrderStatus
|
backend/app/services/ai_memory_manager.py
CHANGED
|
@@ -154,7 +154,9 @@ class AIMemoryManager:
|
|
| 154 |
|
| 155 |
# A. EXTRACT ALL SETTINGS
|
| 156 |
ai_settings = tenant.ai_settings or {}
|
| 157 |
-
|
|
|
|
|
|
|
| 158 |
bot_name = ai_identity.get("bot_name", "AI Assistant")
|
| 159 |
bot_role = ai_identity.get("bot_role", "Эксперт по продажам") # User-defined role
|
| 160 |
bot_gender = ai_identity.get("bot_gender", "male") # male or female
|
|
|
|
| 154 |
|
| 155 |
# A. EXTRACT ALL SETTINGS
|
| 156 |
ai_settings = tenant.ai_settings or {}
|
| 157 |
+
|
| 158 |
+
# UNIFIED AI IDENTITY: Check tenant.ai_identity first (new), fallback to ai_settings (legacy)
|
| 159 |
+
ai_identity = getattr(tenant, 'ai_identity', None) or ai_settings.get("ai_identity", {}) or {}
|
| 160 |
bot_name = ai_identity.get("bot_name", "AI Assistant")
|
| 161 |
bot_role = ai_identity.get("bot_role", "Эксперт по продажам") # User-defined role
|
| 162 |
bot_gender = ai_identity.get("bot_gender", "male") # male or female
|
backend/app/services/notification.py
CHANGED
|
@@ -33,41 +33,60 @@ class NotificationService:
|
|
| 33 |
)
|
| 34 |
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
|
| 35 |
|
| 36 |
-
async def notify_new_appointment(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"""Send alert about a new booking with smart context from AI."""
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
settings = tenant.notification_settings
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
pain_text = ', '.join(pain_points[:2]) if pain_points else '—'
|
| 54 |
-
heat_score = ai_summary.get("heat_score", 0) if ai_summary else 0
|
| 55 |
-
|
| 56 |
-
# Heat indicator emoji
|
| 57 |
-
heat_emoji = "🔥" if heat_score >= 70 else "🟡" if heat_score >= 50 else "❄️"
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 71 |
|
| 72 |
async def notify_escalation(self, tenant: Tenant, lead, reason: str = None, last_message: str = None):
|
| 73 |
"""Send alert when client requests human manager (escalation)."""
|
|
|
|
| 33 |
)
|
| 34 |
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
|
| 35 |
|
| 36 |
+
async def notify_new_appointment(
|
| 37 |
+
self,
|
| 38 |
+
tenant: Tenant,
|
| 39 |
+
appointment: Appointment,
|
| 40 |
+
ai_summary: dict = None,
|
| 41 |
+
resource_telegram_id: str = None # New: notify resource owner directly
|
| 42 |
+
):
|
| 43 |
"""Send alert about a new booking with smart context from AI."""
|
| 44 |
+
# Determine notification target: resource owner first, then tenant settings
|
| 45 |
+
tg_chat_id = resource_telegram_id
|
| 46 |
+
notify_enabled = True
|
|
|
|
| 47 |
|
| 48 |
+
if not tg_chat_id:
|
| 49 |
+
# Fallback to tenant notification settings
|
| 50 |
+
if not tenant.notification_settings:
|
| 51 |
+
return
|
| 52 |
+
settings = tenant.notification_settings
|
| 53 |
+
tg_chat_id = settings.get("telegram_chat_id")
|
| 54 |
+
notify_enabled = settings.get("notify_on_booking", True)
|
| 55 |
+
|
| 56 |
+
if not tg_chat_id or not notify_enabled:
|
| 57 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
+
# Format time
|
| 60 |
+
start = appointment.start_time.strftime('%d.%m %H:%M')
|
| 61 |
+
|
| 62 |
+
# Extract smart context from AI summary
|
| 63 |
+
lead_name = appointment.lead.name if appointment.lead else 'Неизвестно'
|
| 64 |
+
intent = ai_summary.get("intent", "Не определено") if ai_summary else "—"
|
| 65 |
+
pain_points = ai_summary.get("pain_points", []) if ai_summary else []
|
| 66 |
+
pain_text = ', '.join(pain_points[:2]) if pain_points else '—'
|
| 67 |
+
heat_score = ai_summary.get("heat_score", 0) if ai_summary else 0
|
| 68 |
+
|
| 69 |
+
# Heat indicator emoji
|
| 70 |
+
heat_emoji = "🔥" if heat_score >= 70 else "🟡" if heat_score >= 50 else "❄️"
|
| 71 |
+
|
| 72 |
+
# Add resource info if booking to specific resource
|
| 73 |
+
resource_info = ""
|
| 74 |
+
if hasattr(appointment, 'resource') and appointment.resource:
|
| 75 |
+
resource_info = f"📌 Ресурс: {appointment.resource.name}\n"
|
| 76 |
+
|
| 77 |
+
message = (
|
| 78 |
+
f"📅 **НОВАЯ ЗАПИСЬ** 📅\n\n"
|
| 79 |
+
f"👤 Клиент: {lead_name}\n"
|
| 80 |
+
f"{heat_emoji} Теплота: {heat_score}%\n"
|
| 81 |
+
f"🎯 Интерес: {intent}\n"
|
| 82 |
+
f"💡 Боли: {pain_text}\n"
|
| 83 |
+
f"───────────────\n"
|
| 84 |
+
f"🕒 Время: {start}\n"
|
| 85 |
+
f"{resource_info}"
|
| 86 |
+
f"📝 Услуга: {appointment.service.name if appointment.service else 'Общая'}\n"
|
| 87 |
+
f"💬 Заметка: {appointment.notes}"
|
| 88 |
+
)
|
| 89 |
+
await self._send_telegram(tenant.telegram_bot_token, tg_chat_id, message)
|
| 90 |
|
| 91 |
async def notify_escalation(self, tenant: Tenant, lead, reason: str = None, last_message: str = None):
|
| 92 |
"""Send alert when client requests human manager (escalation)."""
|