Spaces:
Running

axeronis commited on
Commit
e3cd75f
·
1 Parent(s): 2400a38

fix: auto-cancel old bookings, AI asks contact info before booking

Browse files
backend/app/api/webhook.py CHANGED
@@ -20,23 +20,20 @@ from app.core.logging import get_logger
20
  logger = get_logger(__name__)
21
 
22
 
23
- def _extract_booking_notes(lead, user_message: str, conversation_history) -> str:
24
  """
25
- Extract booking notes from conversation context.
26
- Includes: client name, topic/reason for booking.
27
  """
28
- # 1. Get client name
29
- client_name = lead.name if lead and lead.name else "Unknown"
30
-
31
- # 2. Extract topic from recent user messages
32
  topic_keywords = []
33
  keywords_to_find = [
34
  "автоматизация", "продажи", "консультация", "внедрение",
35
  "аудит", "ai", "бот", "crm", "интеграция", "помощь",
36
- "партнер", "цена", "стоимость", "демо", "обучение"
 
37
  ]
38
 
39
- # Check last 5 user messages for keywords
40
  user_messages = [msg.content.lower() for msg in conversation_history[-10:] if msg.sender_type == "user"]
41
  user_messages.append(user_message.lower())
42
 
@@ -47,11 +44,7 @@ def _extract_booking_notes(lead, user_message: str, conversation_history) -> str
47
  if len(topic_keywords) >= 3:
48
  break
49
 
50
- # 3. Build notes string
51
- topic_str = ", ".join(topic_keywords) if topic_keywords else "общий вопрос"
52
- notes = f"Клиент: {client_name} | Тема: {topic_str} | Booked via AI Chat"
53
-
54
- return notes
55
 
56
 
57
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
@@ -555,6 +548,28 @@ async def process_ai_response_background(
555
  await session.refresh(default_srv)
556
  logger.info(f"🆕 Auto-created default service for tenant {tenant_id}")
557
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
558
  new_appt = Appointment(
559
  tenant_id=tenant_id,
560
  lead_id=lead_id,
@@ -562,7 +577,7 @@ async def process_ai_response_background(
562
  start_time=start_time,
563
  end_time=end_time,
564
  status=AppointmentStatus.SCHEDULED,
565
- notes=_extract_booking_notes(lead, user_text, conversation_history)
566
  )
567
  session.add(new_appt)
568
  await session.commit()
 
20
  logger = get_logger(__name__)
21
 
22
 
23
+ def _extract_topic_from_conversation(conversation_history, user_message: str) -> str:
24
  """
25
+ Extract topic from conversation for booking notes.
26
+ Returns topic string like "автоматизация, продажи"
27
  """
 
 
 
 
28
  topic_keywords = []
29
  keywords_to_find = [
30
  "автоматизация", "продажи", "консультация", "внедрение",
31
  "аудит", "ai", "бот", "crm", "интеграция", "помощь",
32
+ "партнер", "цена", "стоимость", "демо", "обучение",
33
+ "вопрос", "услуга", "тариф", "подписка"
34
  ]
35
 
36
+ # Check last 10 user messages for keywords
37
  user_messages = [msg.content.lower() for msg in conversation_history[-10:] if msg.sender_type == "user"]
38
  user_messages.append(user_message.lower())
39
 
 
44
  if len(topic_keywords) >= 3:
45
  break
46
 
47
+ return ", ".join(topic_keywords) if topic_keywords else "Консультация"
 
 
 
 
48
 
49
 
50
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
 
548
  await session.refresh(default_srv)
549
  logger.info(f"🆕 Auto-created default service for tenant {tenant_id}")
550
 
551
+ # AUTO-CANCEL OLD BOOKINGS for this lead
552
+ old_appts_stmt = select(Appointment).where(
553
+ Appointment.lead_id == lead_id,
554
+ Appointment.status == AppointmentStatus.SCHEDULED
555
+ )
556
+ old_appts_result = await session.execute(old_appts_stmt)
557
+ old_appointments = old_appts_result.scalars().all()
558
+
559
+ for old_appt in old_appointments:
560
+ old_appt.status = AppointmentStatus.CANCELLED
561
+ old_appt.notes = f"[Перенесено] {old_appt.notes or ''}"
562
+ session.add(old_appt)
563
+ logger.info(f"🔄 Auto-cancelled old appointment {old_appt.id} for lead {lead_id}")
564
+
565
+ if old_appointments:
566
+ await session.commit()
567
+
568
+ # Create new appointment with better notes
569
+ client_name = lead.name if lead and lead.name else "Клиент"
570
+ topic = _extract_topic_from_conversation(conversation_history, user_text)
571
+ notes = f"{client_name} | {topic}"
572
+
573
  new_appt = Appointment(
574
  tenant_id=tenant_id,
575
  lead_id=lead_id,
 
577
  start_time=start_time,
578
  end_time=end_time,
579
  status=AppointmentStatus.SCHEDULED,
580
+ notes=notes
581
  )
582
  session.add(new_appt)
583
  await session.commit()
backend/app/services/ai_memory_manager.py CHANGED
@@ -269,16 +269,24 @@ class AIMemoryManager:
269
  ═══════════════════════════════════════════════════════════════
270
  [📅 СИСТЕМА ЗАПИСИ]
271
  ═══════════════════════════════════════════════════════════════
272
- Когда клиент хочет записаться:
273
- 1. Уточни дату и время если не указаны
274
- 2. КОНВЕРТИРУЙ относительные даты в YYYY-MM-DD:
275
- - "завтра" = следующий день
276
- - "послезавтра" = через 2 дня
277
- - "в среду" = ближайшая среда
278
- 3. Подтверди запись ТЕГОМ: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM]
279
-
280
- Пример: клиент пишет "завтра в 15:00" (сегодня 2025-12-20)
281
- → Твой ответ включает: [BOOK_CONFIRMED: 2025-12-21 15:00]
 
 
 
 
 
 
 
 
282
 
283
  """
284
  # E. PRODUCT CATALOG
 
269
  ═══════════════════════════════════════════════════════════════
270
  [📅 СИСТЕМА ЗАПИСИ]
271
  ═══════════════════════════════════════════════════════════════
272
+ Когда клиент хочет записаться, ОБЯЗАТЕЛЬНО уточни:
273
+
274
+ 1. ИМЯ — если не знаешь, спроси: "Как вас зовут?"
275
+ 2. КОНТАКТ — спроси: "Оставьте номер телефона для связи"
276
+ 3. ДАТА И ВРЕМЯ — если не указаны, уточни
277
+
278
+ После получения ВСЕХ данных:
279
+ - Конвертируй "завтра" → следующий день, "послезавтра" → +2 дня
280
+ - Подтверди: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM]
281
+
282
+ ПРИМЕР ДИАЛОГА:
283
+ Клиент: Хочу записаться на консультацию
284
+ Ты: Отлично! Как вас зовут и на какое время удобно?
285
+ Клиент: Иван, завтра в 15:00
286
+ Ты: Иван, оставьте номер телефона для подтверждения
287
+ Клиент: +7 999 123 4567
288
+ Ты: Иван, записала вас на завтра в 15:00. Перезвоним на +7 999 123 4567!
289
+ [BOOK_CONFIRMED: 2025-12-21 15:00]
290
 
291
  """
292
  # E. PRODUCT CATALOG