Spaces:
Running
Running
axeronis commited on
Commit ·
5152823
1
Parent(s): bd1374d
fix: booking resources optional, existing usage check, hot lead notifications
Browse files
backend/app/api/chats.py
CHANGED
|
@@ -260,7 +260,8 @@ async def send_message(
|
|
| 260 |
analysis = await ai_core.analyze_lead(
|
| 261 |
session=session,
|
| 262 |
lead=lead,
|
| 263 |
-
conversation_history=all_messages
|
|
|
|
| 264 |
)
|
| 265 |
|
| 266 |
logger.info(
|
|
@@ -649,7 +650,8 @@ async def generate_ai_reply(
|
|
| 649 |
analysis = await ai_core.analyze_lead(
|
| 650 |
session=session,
|
| 651 |
lead=lead,
|
| 652 |
-
conversation_history=all_messages
|
|
|
|
| 653 |
)
|
| 654 |
|
| 655 |
logger.info(
|
|
|
|
| 260 |
analysis = await ai_core.analyze_lead(
|
| 261 |
session=session,
|
| 262 |
lead=lead,
|
| 263 |
+
conversation_history=all_messages,
|
| 264 |
+
tenant=tenant
|
| 265 |
)
|
| 266 |
|
| 267 |
logger.info(
|
|
|
|
| 650 |
analysis = await ai_core.analyze_lead(
|
| 651 |
session=session,
|
| 652 |
lead=lead,
|
| 653 |
+
conversation_history=all_messages,
|
| 654 |
+
tenant=tenant
|
| 655 |
)
|
| 656 |
|
| 657 |
logger.info(
|
backend/app/api/leads.py
CHANGED
|
@@ -454,7 +454,8 @@ async def force_analyze_lead(
|
|
| 454 |
analysis_result = await ai_core.analyze_lead(
|
| 455 |
session=session,
|
| 456 |
lead=lead,
|
| 457 |
-
conversation_history=messages
|
|
|
|
| 458 |
)
|
| 459 |
|
| 460 |
print(f"\n✅ AI Core returned successfully!")
|
|
|
|
| 454 |
analysis_result = await ai_core.analyze_lead(
|
| 455 |
session=session,
|
| 456 |
lead=lead,
|
| 457 |
+
conversation_history=messages,
|
| 458 |
+
tenant=tenant
|
| 459 |
)
|
| 460 |
|
| 461 |
print(f"\n✅ AI Core returned successfully!")
|
backend/app/api/webhook.py
CHANGED
|
@@ -2060,7 +2060,8 @@ Answer with ONE word:
|
|
| 2060 |
analysis = await ai_core.analyze_lead(
|
| 2061 |
session=session,
|
| 2062 |
lead=lead,
|
| 2063 |
-
conversation_history=all_messages
|
|
|
|
| 2064 |
)
|
| 2065 |
|
| 2066 |
logger.info(
|
|
@@ -2163,11 +2164,17 @@ async def analyze_lead_background(
|
|
| 2163 |
|
| 2164 |
# Run analysis
|
| 2165 |
ai_core = get_ai_core()
|
| 2166 |
-
|
| 2167 |
-
|
| 2168 |
-
|
| 2169 |
-
|
| 2170 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2171 |
|
| 2172 |
# Set back to IDLE after analysis complete
|
| 2173 |
lead.processing_status = "idle"
|
|
|
|
| 2060 |
analysis = await ai_core.analyze_lead(
|
| 2061 |
session=session,
|
| 2062 |
lead=lead,
|
| 2063 |
+
conversation_history=all_messages,
|
| 2064 |
+
tenant=tenant
|
| 2065 |
)
|
| 2066 |
|
| 2067 |
logger.info(
|
|
|
|
| 2164 |
|
| 2165 |
# Run analysis
|
| 2166 |
ai_core = get_ai_core()
|
| 2167 |
+
# Load tenant for analysis
|
| 2168 |
+
from app.models.tenant import Tenant
|
| 2169 |
+
tenant = await session.get(Tenant, lead.tenant_id)
|
| 2170 |
+
|
| 2171 |
+
if tenant:
|
| 2172 |
+
analysis = await ai_core.analyze_lead(
|
| 2173 |
+
session=session,
|
| 2174 |
+
lead=lead,
|
| 2175 |
+
conversation_history=list(messages),
|
| 2176 |
+
tenant=tenant
|
| 2177 |
+
)
|
| 2178 |
|
| 2179 |
# Set back to IDLE after analysis complete
|
| 2180 |
lead.processing_status = "idle"
|
backend/app/services/ai_core/base.py
CHANGED
|
@@ -67,7 +67,8 @@ class AICore:
|
|
| 67 |
self,
|
| 68 |
session: AsyncSession,
|
| 69 |
lead: Lead,
|
| 70 |
-
conversation_history: List[Message]
|
|
|
|
| 71 |
) -> Dict[str, Any]:
|
| 72 |
"""
|
| 73 |
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
|
@@ -75,7 +76,7 @@ class AICore:
|
|
| 75 |
Delegates to lead_analyzer module.
|
| 76 |
"""
|
| 77 |
from .lead_analyzer import analyze_lead_impl
|
| 78 |
-
return await analyze_lead_impl(self, session, lead, conversation_history)
|
| 79 |
|
| 80 |
# =========================================================================
|
| 81 |
# Reactivation (from lead_analyzer.py)
|
|
|
|
| 67 |
self,
|
| 68 |
session: AsyncSession,
|
| 69 |
lead: Lead,
|
| 70 |
+
conversation_history: List[Message],
|
| 71 |
+
tenant: Tenant
|
| 72 |
) -> Dict[str, Any]:
|
| 73 |
"""
|
| 74 |
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
|
|
|
| 76 |
Delegates to lead_analyzer module.
|
| 77 |
"""
|
| 78 |
from .lead_analyzer import analyze_lead_impl
|
| 79 |
+
return await analyze_lead_impl(self, session, lead, conversation_history, tenant)
|
| 80 |
|
| 81 |
# =========================================================================
|
| 82 |
# Reactivation (from lead_analyzer.py)
|
backend/app/services/ai_core/lead_analyzer.py
CHANGED
|
@@ -387,7 +387,8 @@ async def analyze_lead_impl(
|
|
| 387 |
ai_core: "AICore",
|
| 388 |
session: AsyncSession,
|
| 389 |
lead: Lead,
|
| 390 |
-
conversation_history: List[Message]
|
|
|
|
| 391 |
) -> Dict[str, Any]:
|
| 392 |
"""
|
| 393 |
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
|
@@ -460,10 +461,11 @@ async def analyze_lead_impl(
|
|
| 460 |
try:
|
| 461 |
from app.services.notification_service import get_notification_service
|
| 462 |
notification_service = get_notification_service()
|
|
|
|
| 463 |
await notification_service.notify_hot_lead(
|
| 464 |
session=session,
|
| 465 |
lead=lead,
|
| 466 |
-
tenant=
|
| 467 |
)
|
| 468 |
print(f"✅ HOT lead notification sent successfully")
|
| 469 |
except Exception as e:
|
|
|
|
| 387 |
ai_core: "AICore",
|
| 388 |
session: AsyncSession,
|
| 389 |
lead: Lead,
|
| 390 |
+
conversation_history: List[Message],
|
| 391 |
+
tenant: "Tenant"
|
| 392 |
) -> Dict[str, Any]:
|
| 393 |
"""
|
| 394 |
Background task: Analyze lead and update heat score, psychotype, AI summary.
|
|
|
|
| 461 |
try:
|
| 462 |
from app.services.notification_service import get_notification_service
|
| 463 |
notification_service = get_notification_service()
|
| 464 |
+
# USE PASSED TENANT - avoid lazy load error
|
| 465 |
await notification_service.notify_hot_lead(
|
| 466 |
session=session,
|
| 467 |
lead=lead,
|
| 468 |
+
tenant=tenant
|
| 469 |
)
|
| 470 |
print(f"✅ HOT lead notification sent successfully")
|
| 471 |
except Exception as e:
|
backend/app/services/ai_core/response_generator.py
CHANGED
|
@@ -72,6 +72,33 @@ async def generate_sales_response_impl(
|
|
| 72 |
tenant=tenant # Pass tenant for working hours
|
| 73 |
)
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
# 3. MEMORY RETRIEVAL (The "Big Brain")
|
| 76 |
memory_manager = get_memory_manager()
|
| 77 |
# cache_name = await memory_manager.get_valid_memory(session, tenant) # Deprecating single cache ref
|
|
@@ -175,6 +202,7 @@ Message Count: {ai_message_count} (0-1 = Первое сообщение, исп
|
|
| 175 |
|
| 176 |
[BOOKING AVAILABILITY]
|
| 177 |
{booking_context if booking_context else "No specific slots needed yet."}
|
|
|
|
| 178 |
|
| 179 |
[VOICE MESSAGE CAPABILITY]
|
| 180 |
Ты можешь отправлять ГОЛОСОВЫЕ сообщения, добавив тег [SEND_VOICE] в конец ответа.
|
|
|
|
| 72 |
tenant=tenant # Pass tenant for working hours
|
| 73 |
)
|
| 74 |
|
| 75 |
+
# 2.5 CHECK EXISTING APPOINTMENT FOR THIS LEAD
|
| 76 |
+
# If lead already has a scheduled appointment, tell AI to NOT re-book
|
| 77 |
+
existing_appointment_info = ""
|
| 78 |
+
try:
|
| 79 |
+
from sqlmodel import select
|
| 80 |
+
from app.models.booking import Appointment, AppointmentStatus
|
| 81 |
+
|
| 82 |
+
existing_appt_stmt = select(Appointment).where(
|
| 83 |
+
Appointment.lead_id == lead.id,
|
| 84 |
+
Appointment.status == AppointmentStatus.SCHEDULED
|
| 85 |
+
)
|
| 86 |
+
existing_appt_result = await session.execute(existing_appt_stmt)
|
| 87 |
+
existing_appt = existing_appt_result.scalar_one_or_none()
|
| 88 |
+
|
| 89 |
+
if existing_appt:
|
| 90 |
+
appt_date = existing_appt.start_time.strftime('%d.%m.%Y в %H:%M')
|
| 91 |
+
existing_appointment_info = f"""
|
| 92 |
+
⚠️⚠️⚠️ КРИТИЧЕСКИ ВАЖНО ⚠️⚠️⚠️
|
| 93 |
+
ЭТОТ КЛИЕНТ УЖЕ ЗАПИСАН: {appt_date}
|
| 94 |
+
НЕ предлагай новую запись! У него УЖЕ есть!
|
| 95 |
+
Если спрашивает про запись — напомни что он УЖЕ записан на {appt_date}.
|
| 96 |
+
Если хочет ПЕРЕНЕСТИ — предложи новое время, и тогда можно [BOOK_CONFIRMED].
|
| 97 |
+
"""
|
| 98 |
+
logger.info(f"📅 Lead {lead.id} already has appointment at {appt_date}")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
logger.warning(f"Failed to check existing appointment: {e}")
|
| 101 |
+
|
| 102 |
# 3. MEMORY RETRIEVAL (The "Big Brain")
|
| 103 |
memory_manager = get_memory_manager()
|
| 104 |
# cache_name = await memory_manager.get_valid_memory(session, tenant) # Deprecating single cache ref
|
|
|
|
| 202 |
|
| 203 |
[BOOKING AVAILABILITY]
|
| 204 |
{booking_context if booking_context else "No specific slots needed yet."}
|
| 205 |
+
{existing_appointment_info}
|
| 206 |
|
| 207 |
[VOICE MESSAGE CAPABILITY]
|
| 208 |
Ты можешь отправлять ГОЛОСОВЫЕ сообщения, добавив тег [SEND_VOICE] в конец ответа.
|
backend/app/services/ai_memory_manager.py
CHANGED
|
@@ -668,9 +668,10 @@ class AIMemoryManager:
|
|
| 668 |
context += "═══════════════════════════════════════════════════════════════\n"
|
| 669 |
context += """⚠️ ВАЖНО ПО РЕСУРСАМ:
|
| 670 |
- Ресурс может быть: стол, мастер, врач, кабинет, компьютер и т.д.
|
| 671 |
-
- При записи
|
| 672 |
- Если ресурс занят — предложи другой свободный или другое время
|
| 673 |
-
-
|
|
|
|
| 674 |
|
| 675 |
"""
|
| 676 |
# Current date for checking occupancy
|
|
|
|
| 668 |
context += "═══════════════════════════════════════════════════════════════\n"
|
| 669 |
context += """⚠️ ВАЖНО ПО РЕСУРСАМ:
|
| 670 |
- Ресурс может быть: стол, мастер, врач, кабинет, компьютер и т.д.
|
| 671 |
+
- При записи проверяй занятость ресурса на нужное время
|
| 672 |
- Если ресурс занят — предложи другой свободный или другое время
|
| 673 |
+
- ФОРМАТ с ресурсом: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM | Название ресурса]
|
| 674 |
+
- Если клиент не указал конкретный ресурс — запиши на ЛЮБОЙ свободный
|
| 675 |
|
| 676 |
"""
|
| 677 |
# Current date for checking occupancy
|