Spaces:
Running

axeronis commited on
Commit
6404030
·
1 Parent(s): 8c29deb

feat: AI Booking (availability+booking) and Daily Reminders Job

Browse files
backend/app/api/jobs.py ADDED
@@ -0,0 +1,88 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks
2
+ from sqlalchemy.ext.asyncio import AsyncSession
3
+ from sqlmodel import select, col
4
+ from datetime import datetime, date, timedelta
5
+ from typing import List, Dict, Any
6
+ from uuid import UUID
7
+
8
+ from app.core.database import get_session
9
+ from app.core.logging import get_logger
10
+ from app.models.tenant import Tenant
11
+ from app.models.booking import Appointment, AppointmentStatus
12
+ from app.models.lead import Lead
13
+ from app.utils.telegram import send_telegram_message
14
+
15
+ router = APIRouter(prefix="/jobs", tags=["Jobs"])
16
+ logger = get_logger(__name__)
17
+
18
+ @router.post("/reminders/daily")
19
+ async def trigger_daily_reminders(
20
+ background_tasks: BackgroundTasks,
21
+ session: AsyncSession = Depends(get_session)
22
+ # secret: str = Depends(verify_cron_secret) # TODO for security
23
+ ):
24
+ """
25
+ Daily Cron Job: Send reminders for appointments scheduled for TODAY.
26
+ Should be called every morning (e.g. 08:00 or 09:00).
27
+ """
28
+ logger.info("⏰ Starting Daily Reminder Job")
29
+
30
+ # 1. Find appointments for today
31
+ today = date.today()
32
+ start_of_day = datetime.combine(today, datetime.min.time())
33
+ end_of_day = datetime.combine(today, datetime.max.time())
34
+
35
+ stmt = select(Appointment).where(
36
+ Appointment.start_time >= start_of_day,
37
+ Appointment.start_time <= end_of_day,
38
+ Appointment.status == AppointmentStatus.SCHEDULED
39
+ )
40
+ result = await session.execute(stmt)
41
+ appointments = result.scalars().all()
42
+
43
+ logger.info(f"📅 Found {len(appointments)} appointments for today")
44
+
45
+ sent_count = 0
46
+
47
+ for appt in appointments:
48
+ try:
49
+ # Get Tenant & Lead
50
+ tenant = await session.get(Tenant, appt.tenant_id)
51
+ lead = await session.get(Lead, appt.lead_id)
52
+
53
+ if not tenant or not lead or not lead.telegram_chat_id:
54
+ continue
55
+
56
+ # Get Settings
57
+ settings = tenant.booking_settings or {}
58
+ reminder_enabled = settings.get('reminders_enabled', True)
59
+
60
+ if not reminder_enabled:
61
+ continue
62
+
63
+ # Construct Message
64
+ time_str = appt.start_time.strftime("%H:%M")
65
+ template = settings.get('reminder_template',
66
+ "👋 Здравствуйте, {name}! Напоминаем о вашей встрече сегодня в {time}. Будем ждать вас!"
67
+ )
68
+
69
+ message_text = template.format(
70
+ name=lead.name or "Клиент",
71
+ time=time_str
72
+ )
73
+
74
+ # Send (Background Task? No, calling directly to ensure completion or use background_tasks.add_task)
75
+ # Since this is a job, we can await.
76
+ if tenant.telegram_bot_token:
77
+ await send_telegram_message(
78
+ token=tenant.telegram_bot_token,
79
+ chat_id=lead.telegram_chat_id,
80
+ text=message_text
81
+ )
82
+ sent_count += 1
83
+ logger.info(f"✅ Sent reminder to {lead.id}")
84
+
85
+ except Exception as e:
86
+ logger.error(f"❌ Failed to send reminder for appt {appt.id}: {e}")
87
+
88
+ return {"status": "ok", "processed": len(appointments), "sent": sent_count}
backend/app/api/webhook.py CHANGED
@@ -267,7 +267,8 @@ async def send_telegram_message(
267
  chat_id: str,
268
  text: str
269
  ) -> bool:
270
- """Send message via Telegram Bot API."""
 
271
 
272
  if not bot_token or not bot_token.strip():
273
  logger.warning(
@@ -276,58 +277,74 @@ async def send_telegram_message(
276
  )
277
  return False
278
 
279
- url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
 
 
 
 
 
280
 
281
- payload = {
282
- "chat_id": chat_id,
283
- "text": text,
284
- "parse_mode": "Markdown"
285
- }
 
 
 
 
286
 
287
- logger.info(
288
- "📡 Telegram API request",
289
- url=url[:60] + "...",
290
- chat_id=chat_id,
291
- text_length=len(text)
292
- )
293
 
294
- try:
295
- async with httpx.AsyncClient() as client:
296
- # Attempt 1: Try with Markdown
297
- logger.info(
298
- "📡 Telegram API request (Markdown)",
299
- url=url[:60] + "...",
300
- chat_id=chat_id,
301
- text_length=len(text)
302
- )
303
- response = await client.post(url, json=payload, timeout=10.0)
 
304
 
305
- if response.status_code == 400 and "can't parse entities" in response.text:
306
- logger.warning(
307
- "⚠️ Telegram Markdown parse error, retrying as plain text",
308
- chat_id=chat_id,
309
- error=response.text
310
- )
311
- # Attempt 2: Retry as Plain Text
312
- payload["parse_mode"] = None
313
- response = await client.post(url, json=payload, timeout=10.0)
 
 
 
 
314
 
315
- response.raise_for_status()
316
-
317
- logger.info(
318
- "✅ Telegram message sent",
319
- status_code=response.status_code
320
- )
321
- return True
322
-
323
- except Exception as e:
324
- logger.error(
325
- "❌ Failed to send Telegram message",
326
- error=str(e),
327
- chat_id=chat_id,
328
- exc_info=True
329
- )
330
- return False
 
 
 
 
 
 
 
331
 
332
 
333
  async def process_ai_response_background(
@@ -464,6 +481,53 @@ async def process_ai_response_background(
464
  conversation_history=conversation_history
465
  )
466
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
467
  ai_message = Message(
468
  tenant_id=tenant.id,
469
  conversation_id=conversation.id,
 
267
  chat_id: str,
268
  text: str
269
  ) -> bool:
270
+ """Send message via Telegram Bot API (Text or Photo)."""
271
+ import re
272
 
273
  if not bot_token or not bot_token.strip():
274
  logger.warning(
 
277
  )
278
  return False
279
 
280
+ # 1. Extract Image URLs (Supabase or standard extensions)
281
+ # Matches: https://...supabase... or ending in .jpg/png/webp
282
+ img_pattern = r"(https?://[^\s\)]+(?:supabase\.co|products)[^\s\)]+)|(https?://[^\s\)]+\.(?:jpg|jpeg|png|webp))"
283
+ matches = re.findall(img_pattern, text, re.IGNORECASE)
284
+ # Flatten matches and filter empty
285
+ images = [m[0] or m[1] for m in matches if m[0] or m[1]]
286
 
287
+ # 2. Clean Text (Remove links to images to avoid duplicates)
288
+ clean_text = text
289
+ for img in images:
290
+ # Remove Markdown links: [text](url)
291
+ clean_text = re.sub(r"\[.*?\]\(" + re.escape(img) + r"\)", "", clean_text)
292
+ # Remove plain URLs in parens: (url)
293
+ clean_text = clean_text.replace(f"({img})", "")
294
+ # Remove plain URLs
295
+ clean_text = clean_text.replace(img, "")
296
 
297
+ clean_text = clean_text.strip()
 
 
 
 
 
298
 
299
+ async with httpx.AsyncClient() as client:
300
+ success = True
301
+
302
+ # 3. Send Text (if any remains)
303
+ if clean_text:
304
+ text_url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
305
+ payload = {
306
+ "chat_id": chat_id,
307
+ "text": clean_text,
308
+ "parse_mode": "Markdown"
309
+ }
310
 
311
+ try:
312
+ # Attempt 1: Markdown
313
+ response = await client.post(text_url, json=payload, timeout=10.0)
314
+
315
+ # Retry Plain Text if Markdown fails
316
+ if response.status_code == 400 and "can't parse entities" in response.text:
317
+ payload["parse_mode"] = None
318
+ response = await client.post(text_url, json=payload, timeout=10.0)
319
+
320
+ response.raise_for_status()
321
+ except Exception as e:
322
+ logger.error("❌ Failed to send text", error=str(e))
323
+ success = False
324
 
325
+ # 4. Send Images (as Photos)
326
+ photo_url = f"https://api.telegram.org/bot{bot_token}/sendPhoto"
327
+ for img in images:
328
+ try:
329
+ # Check extension, if it's .jfif or unknown, Telegram might reject as photo.
330
+ # But Supabase usually serves content-type correctly.
331
+ # If Telegram rejects generic URL, we might need download/re-upload,
332
+ # but usually passing URL works fine.
333
+ payload = {
334
+ "chat_id": chat_id,
335
+ "photo": img,
336
+ "caption": "" # Optional: add caption?
337
+ }
338
+ logger.info("📸 Sending photo", url=img)
339
+ resp = await client.post(photo_url, json=payload, timeout=20.0)
340
+ resp.raise_for_status()
341
+ except Exception as e:
342
+ logger.error("❌ Failed to send photo", url=img, error=str(e))
343
+ # Don't fail the whole task if one image fails, but log it.
344
+ # If we rely on image for context, this might be bad.
345
+ pass
346
+
347
+ return success
348
 
349
 
350
  async def process_ai_response_background(
 
481
  conversation_history=conversation_history
482
  )
483
 
484
+ # --- BOOKING INTERCEPTION START ---
485
+ import re
486
+ from datetime import datetime
487
+ from app.models.booking import Appointment, AppointmentStatus, Service # Ensure imports
488
+
489
+ ai_text = ai_response["text"]
490
+ booking_match = re.search(r'\[BOOK_CONFIRMED:\s*([\d\-]+\s[\d:]+)\]', ai_text)
491
+
492
+ if booking_match:
493
+ try:
494
+ date_str = booking_match.group(1)
495
+ # Expected format: YYYY-MM-DD HH:MM
496
+ start_time = datetime.strptime(date_str, "%Y-%m-%d %H:%M")
497
+ end_time = start_time.replace(minute=start_time.minute + 30) # Default 30 min
498
+
499
+ # Find default service
500
+ srv_stmt = select(Service).where(Service.tenant_id == tenant_id).limit(1)
501
+ srv_result = await session.execute(srv_stmt)
502
+ default_srv = srv_result.scalar_one_or_none()
503
+
504
+ new_appt = Appointment(
505
+ tenant_id=tenant_id,
506
+ lead_id=lead_id,
507
+ service_id=default_srv.id if default_srv else None,
508
+ start_time=start_time,
509
+ end_time=end_time,
510
+ status=AppointmentStatus.SCHEDULED,
511
+ notes="Booked via AI Chat"
512
+ )
513
+ session.add(new_appt)
514
+ await session.commit()
515
+
516
+ logger.info(f"📅 AI Booked Appointment: {date_str} for Lead {lead_id}")
517
+
518
+ # Remove tag from text
519
+ ai_text = ai_text.replace(booking_match.group(0), "").strip()
520
+ ai_text += "\n\n✅ (Система: Запись создана успешно!)"
521
+
522
+ # Update response text in object
523
+ ai_response["text"] = ai_text
524
+
525
+ except Exception as e:
526
+ logger.error(f"❌ Failed to process AI booking tag: {e}")
527
+ ai_response["text"] += "\n\n⚠️ (Система: Ошибка при сохранении записи. Менеджер свяжется с вами.)"
528
+ # --- BOOKING INTERCEPTION END ---
529
+
530
+
531
  ai_message = Message(
532
  tenant_id=tenant.id,
533
  conversation_id=conversation.id,
backend/app/main.py CHANGED
@@ -7,7 +7,7 @@ from app.core.config import settings
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
- from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, evolution_webhook, telegram_webhook, partners, notifications, products, bookings
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
@@ -184,6 +184,7 @@ app.include_router(team.router, prefix="/api/v1") # Team Management (owner only
184
  app.include_router(notifications.router, prefix="/api/v1") # HOT Lead Notifications
185
  app.include_router(products.router, prefix="/api/v1")
186
  app.include_router(bookings.router, prefix="/api/v1") # Products & Catalog Management
 
187
  # app.include_router(oauth.router, prefix="/api/v1") # OAuth removed
188
 
189
 
 
7
  from app.core.database import init_pgvector
8
  from app.core.logging import configure_logging, get_logger
9
  from app.middleware.request_id import RequestIDMiddleware
10
+ from app.api import webhook, leads, knowledge, channels, auth, tenants, analytics, chats, playbook, billing, ai_training, crm, admin, team, evolution_webhook, telegram_webhook, partners, notifications, products, bookings, jobs
11
  import asyncio
12
  import sys
13
  from slowapi import Limiter, _rate_limit_exceeded_handler
 
184
  app.include_router(notifications.router, prefix="/api/v1") # HOT Lead Notifications
185
  app.include_router(products.router, prefix="/api/v1")
186
  app.include_router(bookings.router, prefix="/api/v1") # Products & Catalog Management
187
+ app.include_router(jobs.router, prefix="/api/v1")
188
  # app.include_router(oauth.router, prefix="/api/v1") # OAuth removed
189
 
190
 
backend/app/services/ai_core.py CHANGED
@@ -1005,6 +1005,7 @@ Core Mindset = КТО ты. Methodology = КАК ты продаёшь.
1005
  ⚠️ НЕ навязывай товары на этапе Discovery. Сначала квалифицируй, потом предлагай.
1006
 
1007
 
 
1008
  {playbook_text}
1009
 
1010
  {booking_instruction}
@@ -1407,6 +1408,108 @@ OUTPUT FORMAT (JSON):
1407
 
1408
  return list(examples)
1409
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1410
  async def _get_learning_rules(
1411
  self,
1412
  session: AsyncSession,
 
1005
  ⚠️ НЕ навязывай товары на этапе Discovery. Сначала квалифицируй, потом предлагай.
1006
 
1007
 
1008
+
1009
  {playbook_text}
1010
 
1011
  {booking_instruction}
 
1408
 
1409
  return list(examples)
1410
 
1411
+ async def _get_booking_context(
1412
+ self,
1413
+ session: AsyncSession,
1414
+ tenant_id: UUID,
1415
+ lead: Lead,
1416
+ user_message: str,
1417
+ stage: SalesStage
1418
+ ) -> str:
1419
+ """
1420
+ Get booking availability context for the prompt.
1421
+ Dynamic calculation of free slots.
1422
+ """
1423
+ # Only relevant if we are in a 'booking' context (Appointment Setting or Closing)
1424
+ # OR if user asks about 'time', 'schedule', 'book', 'call'.
1425
+ keywords = ['когда', 'время', 'запис', 'встреч', 'звон', 'schedule', 'book', 'talk', 'call', 'time']
1426
+ is_relevant = any(k in user_message.lower() for k in keywords)
1427
+
1428
+ # Also always relevant in closing stages
1429
+ if not is_relevant and stage and stage.name.lower() not in ['closing', 'meeting', 'demo', 'booking']:
1430
+ return ""
1431
+
1432
+ stmt = select(Tenant).where(Tenant.id == tenant_id)
1433
+ result = await session.execute(stmt)
1434
+ tenant = result.scalar_one_or_none()
1435
+
1436
+ if not tenant or not tenant.booking_settings:
1437
+ return "Booking System: NOT CONFIGURED. (Do not offer detailed slots, just ask for preferred time)"
1438
+
1439
+ settings = tenant.booking_settings
1440
+ days_map = {'mon': 0, 'tue': 1, 'wed': 2, 'thu': 3, 'fri': 4, 'sat': 5, 'sun': 6}
1441
+ working_days = [days_map[d] for d in settings.get('working_days', []) if d in days_map]
1442
+
1443
+ if not working_days:
1444
+ return "Booking System: NO WORKING DAYS CONFIGURED."
1445
+
1446
+ start_hour_str = settings.get('working_hours', {}).get('start', '09:00')
1447
+ end_hour_str = settings.get('working_hours', {}).get('end', '18:00')
1448
+ start_h, start_m = map(int, start_hour_str.split(':'))
1449
+ end_h, end_m = map(int, end_hour_str.split(':'))
1450
+
1451
+ # Calculate next 3 available days
1452
+ from datetime import datetime, timedelta
1453
+ slots_text = []
1454
+ today = datetime.now()
1455
+
1456
+ # Check existing appointments to block slots
1457
+ # For MVP, we'll just check if there's a heavy overlap, but let's list "potential" slots.
1458
+ # A proper implementation would query 'Appointment' table here.
1459
+
1460
+ # Let's perform a lightweight query for booked slots
1461
+ from app.models.booking import Appointment
1462
+ app_stmt = select(Appointment).where(
1463
+ Appointment.tenant_id == tenant_id,
1464
+ Appointment.start_time >= today,
1465
+ Appointment.status == 'scheduled'
1466
+ )
1467
+ app_result = await session.execute(app_stmt)
1468
+ booked_appointments = app_result.scalars().all()
1469
+ booked_times = [(a.start_time, a.end_time) for a in booked_appointments]
1470
+
1471
+ count = 0
1472
+ check_date = today
1473
+ while count < 3: # Next 3 working days
1474
+ if check_date.weekday() in working_days:
1475
+ date_str = check_date.strftime("%A, %d %B")
1476
+ # Generate a few slots for this day to show examples
1477
+ # We won't dump ALL slots (token limit), just morning/afternoon options
1478
+
1479
+ day_slots = []
1480
+ # Check 10:00, 14:00, 16:00
1481
+ potential_times = [
1482
+ check_date.replace(hour=start_h, minute=0, second=0, microsecond=0),
1483
+ check_date.replace(hour=14, minute=0, second=0, microsecond=0),
1484
+ check_date.replace(hour=end_h-1, minute=0, second=0, microsecond=0)
1485
+ ]
1486
+
1487
+ for pt in potential_times:
1488
+ if pt < datetime.now(): continue # Past
1489
+
1490
+ # Check collision
1491
+ is_free = True
1492
+ for b_start, b_end in booked_times:
1493
+ # Simple collision check: if potential starts during a booking
1494
+ if b_start <= pt < b_end:
1495
+ is_free = False
1496
+ break
1497
+
1498
+ if is_free:
1499
+ day_slots.append(pt.strftime("%H:%M"))
1500
+
1501
+ if day_slots:
1502
+ slots_text.append(f"- {date_str}: {', '.join(day_slots)} (and others)")
1503
+ count += 1
1504
+
1505
+ check_date += timedelta(days=1)
1506
+ if (check_date - today).days > 7: break # Limit
1507
+
1508
+ if not slots_text:
1509
+ return "No slots available in next 7 days."
1510
+
1511
+ return "AVAILABLE SLOTS (Examples):\n" + "\n".join(slots_text) + "\n\nINSTRUCTION: Offer these times. When client selects a time, YOU MUST output this tag at the end: [BOOK_CONFIRMED: YYYY-MM-DD HH:MM] (e.g. 2024-05-20 14:00). Do not output this tag unless client explicitly agrees."
1512
+
1513
  async def _get_learning_rules(
1514
  self,
1515
  session: AsyncSession,
frontend/components/BookingSettings.tsx CHANGED
@@ -148,6 +148,33 @@ export default function BookingSettings({ settings, onSave, loading }: BookingSe
148
  </div>
149
  </div>
150
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  {/* Save Button */}
152
  <div className="pt-4 flex justify-end">
153
  <button
 
148
  </div>
149
  </div>
150
 
151
+ {/* Reminders */}
152
+ <div className="pt-6 border-t border-slate-100">
153
+ <div className="flex items-center gap-2 mb-4">
154
+ <CheckCircle2 className="w-5 h-5 text-green-600" />
155
+ <h3 className="font-bold text-slate-900">Напоминания</h3>
156
+ </div>
157
+
158
+ <label className="flex items-center gap-3 mb-4 cursor-pointer">
159
+ <input
160
+ type="checkbox"
161
+ checked={localSettings.reminders_enabled !== false} // default true
162
+ onChange={(e) => setLocalSettings({ ...localSettings, reminders_enabled: e.target.checked })}
163
+ className="w-5 h-5 rounded border-slate-300 text-blue-600 focus:ring-blue-500"
164
+ />
165
+ <span className="text-sm font-medium text-slate-700">Включить утренние напоминания (Daily Job)</span>
166
+ </label>
167
+
168
+ <label className="block text-sm font-bold text-slate-700 mb-2">Шаблон сообщения</label>
169
+ <p className="text-xs text-slate-500 mb-2">Доступные переменные: {'{name}'}, {'{time}'}</p>
170
+ <textarea
171
+ value={localSettings.reminder_template || "👋 Здравствуйте, {name}! Напоминаем о вашей встрече сегодня в {time}. Будем ждать вас!"}
172
+ onChange={(e) => setLocalSettings({ ...localSettings, reminder_template: e.target.value })}
173
+ className="w-full h-24 p-3 bg-slate-50 border border-slate-200 rounded-xl focus:ring-2 focus:ring-blue-500/20 focus:border-blue-500 outline-none text-sm"
174
+ placeholder="Текст напоминания..."
175
+ />
176
+ </div>
177
+
178
  {/* Save Button */}
179
  <div className="pt-4 flex justify-end">
180
  <button