Spaces:
Running
Running
axeronis commited on
Commit ·
c6f8a06
1
Parent(s): aecbce0
Final fix for AISummary validation and booking duplication robustness
Browse files- backend/app/api/webhook.py +28 -42
- backend/app/models/ai_summary.py +2 -3
backend/app/api/webhook.py
CHANGED
|
@@ -1442,10 +1442,11 @@ async def process_ai_response_background(
|
|
| 1442 |
logger.info(f"🆕 Auto-created default service for tenant {tenant_id}")
|
| 1443 |
|
| 1444 |
# CHECK FOR DUPLICATE: Same lead + same time = already booked
|
|
|
|
| 1445 |
duplicate_stmt = select(Appointment).where(
|
| 1446 |
Appointment.lead_id == lead_id,
|
| 1447 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1448 |
-
Appointment.start_time == start_time
|
| 1449 |
)
|
| 1450 |
duplicate_result = await session.execute(duplicate_stmt)
|
| 1451 |
existing_matching = duplicate_result.scalar_one_or_none()
|
|
@@ -1455,7 +1456,7 @@ async def process_ai_response_background(
|
|
| 1455 |
logger.info(f"📅 Booking already exists for lead {lead_id} at {start_time}, skipping duplicate logic")
|
| 1456 |
# Remove the tag and add confirmation (so user knows it's active)
|
| 1457 |
ai_text = ai_text.replace(booking_match.group(0), "").strip()
|
| 1458 |
-
if "(Система: Запись
|
| 1459 |
ai_text += "\n\n✅ (Система: Запись уже подтверждена!)"
|
| 1460 |
ai_response["text"] = ai_text
|
| 1461 |
else:
|
|
@@ -1465,7 +1466,7 @@ async def process_ai_response_background(
|
|
| 1465 |
old_appts_stmt = select(Appointment).where(
|
| 1466 |
Appointment.lead_id == lead_id,
|
| 1467 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1468 |
-
Appointment.start_time != start_time
|
| 1469 |
)
|
| 1470 |
old_appts_result = await session.execute(old_appts_stmt)
|
| 1471 |
old_appointments = old_appts_result.scalars().all()
|
|
@@ -1500,54 +1501,39 @@ async def process_ai_response_background(
|
|
| 1500 |
conflict_stmt = select(Appointment).where(
|
| 1501 |
Appointment.tenant_id == tenant_id,
|
| 1502 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1503 |
-
Appointment.start_time == start_time,
|
| 1504 |
Appointment.lead_id != lead_id # Not us
|
| 1505 |
)
|
| 1506 |
conflict_result = await session.execute(conflict_stmt)
|
| 1507 |
existing_booking = conflict_result.scalar_one_or_none()
|
| 1508 |
|
| 1509 |
-
|
| 1510 |
-
|
| 1511 |
-
|
| 1512 |
-
|
| 1513 |
-
|
| 1514 |
-
|
| 1515 |
-
|
| 1516 |
-
|
| 1517 |
-
|
| 1518 |
-
|
| 1519 |
-
|
| 1520 |
-
|
| 1521 |
-
ai_text = ai_text.replace(booking_match.group(0), "").strip()
|
| 1522 |
-
|
| 1523 |
-
if available_slots:
|
| 1524 |
-
# Format slots nicely
|
| 1525 |
-
slots_formatted = []
|
| 1526 |
-
for slot in available_slots:
|
| 1527 |
-
slots_formatted.append(slot.strftime("%d.%m в %H:%M"))
|
| 1528 |
|
| 1529 |
-
ai_text += f"\n\n⚠️ К сожалению, это время уже занято.\n\n📅 Ближайшие свободные слоты:\n• " + "\n• ".join(slots_formatted) + "\n\nКакое время вам подходит?"
|
| 1530 |
-
else:
|
| 1531 |
-
ai_text += "\n\n⚠️ К сожалению, это время уже занято. Пожалуйста, предложите другое время."
|
| 1532 |
-
|
| 1533 |
-
ai_response["text"] = ai_text
|
| 1534 |
-
else:
|
| 1535 |
-
# CHECK FOR DUPLICATE: Same lead + same time = already booked
|
| 1536 |
-
duplicate_stmt = select(Appointment).where(
|
| 1537 |
-
Appointment.lead_id == lead_id,
|
| 1538 |
-
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1539 |
-
Appointment.start_time == start_time
|
| 1540 |
-
)
|
| 1541 |
-
duplicate_result = await session.execute(duplicate_stmt)
|
| 1542 |
-
existing_for_lead = duplicate_result.scalar_one_or_none()
|
| 1543 |
-
|
| 1544 |
-
if existing_for_lead:
|
| 1545 |
-
# Already booked for this lead at this time - just confirm, don't create duplicate
|
| 1546 |
-
logger.info(f"📅 Booking already exists for lead {lead_id} at {start_time}, skipping duplicate")
|
| 1547 |
-
# Remove the BOOK_CONFIRMED tag from response since booking already exists
|
| 1548 |
ai_text = ai_text.replace(booking_match.group(0), "").strip()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1549 |
ai_response["text"] = ai_text
|
| 1550 |
else:
|
|
|
|
| 1551 |
# Create new appointment with comprehensive notes
|
| 1552 |
booking_info = _extract_booking_info_from_conversation(conversation_history, lead, user_text)
|
| 1553 |
|
|
|
|
| 1442 |
logger.info(f"🆕 Auto-created default service for tenant {tenant_id}")
|
| 1443 |
|
| 1444 |
# CHECK FOR DUPLICATE: Same lead + same time = already booked
|
| 1445 |
+
# Use minute-level comparison to avoid seconds/milliseconds mismatches
|
| 1446 |
duplicate_stmt = select(Appointment).where(
|
| 1447 |
Appointment.lead_id == lead_id,
|
| 1448 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1449 |
+
func.date_trunc('minute', Appointment.start_time) == start_time
|
| 1450 |
)
|
| 1451 |
duplicate_result = await session.execute(duplicate_stmt)
|
| 1452 |
existing_matching = duplicate_result.scalar_one_or_none()
|
|
|
|
| 1456 |
logger.info(f"📅 Booking already exists for lead {lead_id} at {start_time}, skipping duplicate logic")
|
| 1457 |
# Remove the tag and add confirmation (so user knows it's active)
|
| 1458 |
ai_text = ai_text.replace(booking_match.group(0), "").strip()
|
| 1459 |
+
if "(Система: Запись уже подтверждена!)" not in ai_text:
|
| 1460 |
ai_text += "\n\n✅ (Система: Запись уже подтверждена!)"
|
| 1461 |
ai_response["text"] = ai_text
|
| 1462 |
else:
|
|
|
|
| 1466 |
old_appts_stmt = select(Appointment).where(
|
| 1467 |
Appointment.lead_id == lead_id,
|
| 1468 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1469 |
+
func.date_trunc('minute', Appointment.start_time) != start_time # Explicitly different time
|
| 1470 |
)
|
| 1471 |
old_appts_result = await session.execute(old_appts_stmt)
|
| 1472 |
old_appointments = old_appts_result.scalars().all()
|
|
|
|
| 1501 |
conflict_stmt = select(Appointment).where(
|
| 1502 |
Appointment.tenant_id == tenant_id,
|
| 1503 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1504 |
+
func.date_trunc('minute', Appointment.start_time) == start_time,
|
| 1505 |
Appointment.lead_id != lead_id # Not us
|
| 1506 |
)
|
| 1507 |
conflict_result = await session.execute(conflict_stmt)
|
| 1508 |
existing_booking = conflict_result.scalar_one_or_none()
|
| 1509 |
|
| 1510 |
+
if existing_booking:
|
| 1511 |
+
# Slot is taken - find alternatives and suggest them
|
| 1512 |
+
logger.warning(f"⚠️ Time slot {start_time} taken by another client, searching alternatives")
|
| 1513 |
+
|
| 1514 |
+
# Find next 3 available slots
|
| 1515 |
+
available_slots = await _find_available_slots(
|
| 1516 |
+
session=session,
|
| 1517 |
+
tenant_id=tenant_id,
|
| 1518 |
+
requested_time=start_time,
|
| 1519 |
+
count=3
|
| 1520 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1521 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1522 |
ai_text = ai_text.replace(booking_match.group(0), "").strip()
|
| 1523 |
+
|
| 1524 |
+
if available_slots:
|
| 1525 |
+
# Format slots nicely
|
| 1526 |
+
slots_formatted = []
|
| 1527 |
+
for slot in available_slots:
|
| 1528 |
+
slots_formatted.append(slot.strftime("%d.%m в %H:%M"))
|
| 1529 |
+
|
| 1530 |
+
ai_text += f"\n\n⚠️ К сожалению, это время уже занято.\n\n📅 Ближайшие свободные слоты:\n• " + "\n• ".join(slots_formatted) + "\n\nКакое время вам подходит?"
|
| 1531 |
+
else:
|
| 1532 |
+
ai_text += "\n\n⚠️ К сожалению, это время уже занято. Пожалуйста, предложите другое время."
|
| 1533 |
+
|
| 1534 |
ai_response["text"] = ai_text
|
| 1535 |
else:
|
| 1536 |
+
# ALL CLEAR - CREATE NEW APPOINTMENT
|
| 1537 |
# Create new appointment with comprehensive notes
|
| 1538 |
booking_info = _extract_booking_info_from_conversation(conversation_history, lead, user_text)
|
| 1539 |
|
backend/app/models/ai_summary.py
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
from pydantic import BaseModel, Field
|
| 2 |
from typing import List, Optional
|
| 3 |
|
| 4 |
|
|
@@ -7,8 +7,7 @@ class AISummary(BaseModel):
|
|
| 7 |
11-Point Lead Summary Schema with Confidence Tracking.
|
| 8 |
Enhanced with confidence scores (0.0-1.0) for each key field.
|
| 9 |
"""
|
| 10 |
-
|
| 11 |
-
extra = "allow"
|
| 12 |
|
| 13 |
# CLIENT IDENTIFICATION
|
| 14 |
client_name: Optional[str] = Field(
|
|
|
|
| 1 |
+
from pydantic import BaseModel, Field, ConfigDict
|
| 2 |
from typing import List, Optional
|
| 3 |
|
| 4 |
|
|
|
|
| 7 |
11-Point Lead Summary Schema with Confidence Tracking.
|
| 8 |
Enhanced with confidence scores (0.0-1.0) for each key field.
|
| 9 |
"""
|
| 10 |
+
model_config = ConfigDict(extra="allow")
|
|
|
|
| 11 |
|
| 12 |
# CLIENT IDENTIFICATION
|
| 13 |
client_name: Optional[str] = Field(
|