Spaces:
Running

axeronis commited on
Commit
a345825
·
1 Parent(s): b92f979

feat: BOOK_SLOT tag handler - auto-create appointments from AI response

Browse files

- Add tag extraction [BOOK_SLOT: YYYY-MM-DD HH:MM ResourceName]
- Auto-create appointment in database with date, time, resource
- Update prompt format with example and resource name instruction

backend/app/api/webhook.py CHANGED
@@ -1706,6 +1706,56 @@ async def process_ai_response_background(
1706
  logger.info(f"↩️ AI wants to reply to media {reply_to_media_id}")
1707
  ai_response["text"] = re.sub(reply_pattern, '', ai_response["text"]).strip()
1708
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1709
  ai_message = Message(
1710
  tenant_id=tenant.id,
1711
  conversation_id=conversation.id,
 
1706
  logger.info(f"↩️ AI wants to reply to media {reply_to_media_id}")
1707
  ai_response["text"] = re.sub(reply_pattern, '', ai_response["text"]).strip()
1708
 
1709
+ # Process [BOOK_SLOT: YYYY-MM-DD HH:MM] tags - auto-create appointment
1710
+ book_slot_pattern = r'\[BOOK_SLOT:\s*(\d{4}-\d{2}-\d{2})\s+(\d{2}:\d{2})(?:\s+(.+?))?\s*\]'
1711
+ book_slot_match = re.search(book_slot_pattern, ai_response["text"], re.IGNORECASE)
1712
+ if book_slot_match:
1713
+ try:
1714
+ from datetime import datetime, timedelta
1715
+ from app.models.booking import Appointment, Resource
1716
+
1717
+ slot_date = book_slot_match.group(1) # 2024-12-09
1718
+ slot_time = book_slot_match.group(2) # 10:00
1719
+ resource_hint = book_slot_match.group(3) # Optional: resource name
1720
+
1721
+ # Parse datetime
1722
+ start_dt = datetime.fromisoformat(f"{slot_date}T{slot_time}:00")
1723
+ end_dt = start_dt + timedelta(minutes=tenant.booking_settings.get("slot_duration", 30) if tenant.booking_settings else 30)
1724
+
1725
+ # Find resource if mentioned
1726
+ resource_id = None
1727
+ if resource_hint:
1728
+ resource_stmt = select(Resource).where(
1729
+ Resource.tenant_id == tenant.id,
1730
+ Resource.is_active == True,
1731
+ Resource.name.ilike(f"%{resource_hint.strip()}%")
1732
+ )
1733
+ resource_result = await session.execute(resource_stmt)
1734
+ resource = resource_result.scalars().first()
1735
+ if resource:
1736
+ resource_id = resource.id
1737
+ logger.info(f"📅 Found resource '{resource.name}' for booking")
1738
+
1739
+ # Create appointment
1740
+ new_appointment = Appointment(
1741
+ tenant_id=tenant.id,
1742
+ lead_id=lead_id,
1743
+ start_time=start_dt,
1744
+ end_time=end_dt,
1745
+ resource_id=resource_id,
1746
+ status="pending",
1747
+ notes=f"Автоматическая запись через AI (диалог #{conversation.id})"
1748
+ )
1749
+ session.add(new_appointment)
1750
+ await session.flush()
1751
+ logger.info(f"📅 Created appointment: {slot_date} {slot_time} for lead {lead_id}, resource={resource_id}")
1752
+
1753
+ except Exception as e:
1754
+ logger.error(f"❌ Failed to create booking slot: {e}")
1755
+
1756
+ # Clean tag from response
1757
+ ai_response["text"] = re.sub(book_slot_pattern, '', ai_response["text"]).strip()
1758
+
1759
  ai_message = Message(
1760
  tenant_id=tenant.id,
1761
  conversation_id=conversation.id,
backend/app/services/ai_core/prompt_builder.py CHANGED
@@ -228,7 +228,9 @@ def build_system_prompt(
228
  ═══════════════════════════════════════════════════════════════
229
  {booking_context}
230
 
231
- 📝 Для записи используй: [BOOK_SLOT: YYYY-MM-DD HH:MM]
 
 
232
  """
233
 
234
  # Build order section
 
228
  ═══════════════════════════════════════════════════════════════
229
  {booking_context}
230
 
231
+ 📝 Для записи используй: [BOOK_SLOT: YYYY-MM-DD HH:MM Имя_специалиста]
232
+ Пример: [BOOK_SLOT: 2026-01-22 12:00 Джарвис]
233
+ ВАЖНО: Если клиент выбрал специалиста — ОБЯЗАТЕЛЬНО добавь его имя в тег!
234
  """
235
 
236
  # Build order section