Spaces:
Sleeping

axeronis commited on
Commit
12aef18
·
1 Parent(s): 9023f15

feat: comprehensive booking notes, currency selector (RUB/KGS), remove last msg

Browse files
backend/app/api/webhook.py CHANGED
@@ -47,35 +47,76 @@ def _extract_topic_from_conversation(conversation_history, user_message: str) ->
47
  return ", ".join(topic_keywords) if topic_keywords else "Консультация"
48
 
49
 
50
- def _extract_client_name_from_conversation(conversation_history, lead) -> str:
51
  """
52
- Extract client name from conversation history.
53
- Looks for patterns like 'меня зовут Илгис', 'я Илгис', etc.
54
- Falls back to lead.name if not found.
55
  """
56
  import re
57
 
58
- # Patterns to find name in messages
 
 
 
 
 
 
 
 
 
59
  name_patterns = [
60
- r'(?:меня зовут|я|мое имя|зовут меня|это)\s+([А-ЯЁа-яё]{2,})', # Russian names
61
- r'^([А-ЯЁ][а-яё]{2,})\s+[\d\+]', # Name followed by phone number like "Илгис 999..."
62
- r'^([A-Z][a-z]{2,})\s+[\d\+]', # English name followed by phone
63
  ]
64
 
65
- # Check user messages from end (most recent names matter more)
66
- user_messages = [msg.content for msg in conversation_history if msg.sender_type == "user"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
- for msg in reversed(user_messages[-15:]): # Last 15 user messages
69
- for pattern in name_patterns:
70
- match = re.search(pattern, msg, re.IGNORECASE)
71
- if match:
72
- extracted_name = match.group(1).strip()
73
- # Validate it looks like a name (2+ chars, starts with letter)
74
- if len(extracted_name) >= 2 and extracted_name[0].isalpha():
75
- return extracted_name.capitalize()
76
 
77
- # Fallback to lead.name
78
- return lead.name if lead and lead.name else "Клиент"
 
79
 
80
 
81
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
@@ -596,10 +637,15 @@ async def process_ai_response_background(
596
  if old_appointments:
597
  await session.commit()
598
 
599
- # Create new appointment with better notes
600
- client_name = _extract_client_name_from_conversation(conversation_history, lead)
601
- topic = _extract_topic_from_conversation(conversation_history, user_text)
602
- notes = f"{client_name} | {topic}"
 
 
 
 
 
603
 
604
  new_appt = Appointment(
605
  tenant_id=tenant_id,
 
47
  return ", ".join(topic_keywords) if topic_keywords else "Консультация"
48
 
49
 
50
+ def _extract_booking_info_from_conversation(conversation_history, lead, user_text: str) -> dict:
51
  """
52
+ Extract booking info from conversation history.
53
+ Returns dict with: name, phone, topic for comprehensive notes.
 
54
  """
55
  import re
56
 
57
+ info = {
58
+ "name": lead.name if lead and lead.name else "Клиент",
59
+ "phone": lead.phone if lead and lead.phone else None,
60
+ "topic": None
61
+ }
62
+
63
+ # Get user messages
64
+ user_messages = [msg.content for msg in conversation_history if msg.sender_type == "user"]
65
+
66
+ # Patterns for name extraction
67
  name_patterns = [
68
+ r'(?:меня зовут|я|мое имя|зовут меня)\s+([А-ЯЁа-яё]{2,})',
69
+ r'^([А-ЯЁ][а-яё]{2,})\s+[\d\+]',
70
+ r'^([A-Z][a-z]{2,})\s+[\d\+]',
71
  ]
72
 
73
+ # Patterns for phone extraction
74
+ phone_patterns = [
75
+ r'[\+]?[0-9]{10,15}', # International format
76
+ r'[\+]?996\s*\d{9}', # Kyrgyzstan
77
+ r'[\+]?7\s*\d{10}', # Russia
78
+ r'\d{3}[\s\-]?\d{3}[\s\-]?\d{4}', # 999-123-4567
79
+ ]
80
+
81
+ # Extract from messages
82
+ for msg in reversed(user_messages[-15:]):
83
+ # Extract name
84
+ if info["name"] == "Клиент" or info["name"] == lead.name:
85
+ for pattern in name_patterns:
86
+ match = re.search(pattern, msg, re.IGNORECASE)
87
+ if match:
88
+ extracted = match.group(1).strip()
89
+ if len(extracted) >= 2 and extracted[0].isalpha():
90
+ info["name"] = extracted.capitalize()
91
+ break
92
+
93
+ # Extract phone
94
+ if not info["phone"]:
95
+ for pattern in phone_patterns:
96
+ match = re.search(pattern, msg)
97
+ if match:
98
+ info["phone"] = match.group(0).strip()
99
+ break
100
+
101
+ # Extract topic keywords
102
+ topic_keywords = []
103
+ keywords_to_find = [
104
+ "автоматизация", "продажи", "консультация", "внедрение",
105
+ "аудит", "ai", "бот", "crm", "интеграция", "менеджер",
106
+ "нагрузка", "тариф", "цена"
107
+ ]
108
 
109
+ for msg in user_messages[-10:]:
110
+ msg_lower = msg.lower()
111
+ for keyword in keywords_to_find:
112
+ if keyword in msg_lower and keyword not in topic_keywords:
113
+ topic_keywords.append(keyword)
114
+ if len(topic_keywords) >= 2:
115
+ break
 
116
 
117
+ info["topic"] = ", ".join(topic_keywords) if topic_keywords else "Консультация"
118
+
119
+ return info
120
 
121
 
122
  router = APIRouter(prefix="/webhook", tags=["Webhooks"])
 
637
  if old_appointments:
638
  await session.commit()
639
 
640
+ # Create new appointment with comprehensive notes
641
+ booking_info = _extract_booking_info_from_conversation(conversation_history, lead, user_text)
642
+
643
+ # Build informative notes
644
+ notes_parts = [booking_info["name"]]
645
+ if booking_info["phone"]:
646
+ notes_parts.append(f"📞 {booking_info['phone']}")
647
+ notes_parts.append(f"Тема: {booking_info['topic']}")
648
+ notes = " | ".join(notes_parts)
649
 
650
  new_appt = Appointment(
651
  tenant_id=tenant_id,
frontend/components/bookings/AppointmentDetails.tsx CHANGED
@@ -100,8 +100,7 @@ export function AppointmentDetails({ appointment, onClose, onStatusChange }: App
100
  {clientInitial}
101
  </div>
102
  <div>
103
- <h2 className="text-xl font-bold text-white mb-1">{clientName}</h2>
104
- <span className="text-sm text-slate-400">{getLastMessageText()}</span>
105
  </div>
106
  </div>
107
 
 
100
  {clientInitial}
101
  </div>
102
  <div>
103
+ <h2 className="text-xl font-bold text-white">{clientName}</h2>
 
104
  </div>
105
  </div>
106
 
frontend/components/settings/ProductSettings.tsx CHANGED
@@ -44,10 +44,17 @@ export default function ProductSettings() {
44
  name: '',
45
  description: '',
46
  price: 0,
 
47
  category: '',
48
  image_url: ''
49
  })
50
 
 
 
 
 
 
 
51
  useEffect(() => {
52
  loadProducts()
53
  }, [])
@@ -71,6 +78,7 @@ export default function ProductSettings() {
71
  name: product.name,
72
  description: product.description || '',
73
  price: product.price,
 
74
  category: product.category,
75
  image_url: product.image_url || ''
76
  })
@@ -80,6 +88,7 @@ export default function ProductSettings() {
80
  name: '',
81
  description: '',
82
  price: 0,
 
83
  category: '',
84
  image_url: ''
85
  })
@@ -207,7 +216,7 @@ export default function ProductSettings() {
207
  {product.name}
208
  </h3>
209
  <span className="text-emerald-400 font-medium text-sm whitespace-nowrap">
210
- ${product.price}
211
  </span>
212
  </div>
213
  <p className="text-xs text-slate-500 line-clamp-1">
@@ -282,17 +291,32 @@ export default function ProductSettings() {
282
  </div>
283
  </div>
284
  <div>
285
- <label className="block text-xs text-slate-400 mb-1.5">Категория</label>
286
- <input
287
- required
288
- value={formData.category}
289
- onChange={e => setFormData({ ...formData, category: e.target.value })}
290
  className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:border-indigo-500 outline-none"
291
- placeholder="Electronics"
292
- />
 
 
 
 
 
293
  </div>
294
  </div>
295
 
 
 
 
 
 
 
 
 
 
 
 
296
  <div>
297
  <label className="block text-xs text-slate-400 mb-1.5">Изображение</label>
298
  <div className="flex items-center gap-2">
 
44
  name: '',
45
  description: '',
46
  price: 0,
47
+ currency: 'RUB',
48
  category: '',
49
  image_url: ''
50
  })
51
 
52
+ const CURRENCY_OPTIONS = [
53
+ { value: 'RUB', label: '₽ Рубли', symbol: '₽' },
54
+ { value: 'KGS', label: 'сом Сом', symbol: 'сом' },
55
+ { value: 'USD', label: '$ USD', symbol: '$' }
56
+ ]
57
+
58
  useEffect(() => {
59
  loadProducts()
60
  }, [])
 
78
  name: product.name,
79
  description: product.description || '',
80
  price: product.price,
81
+ currency: product.currency || 'RUB',
82
  category: product.category,
83
  image_url: product.image_url || ''
84
  })
 
88
  name: '',
89
  description: '',
90
  price: 0,
91
+ currency: 'RUB',
92
  category: '',
93
  image_url: ''
94
  })
 
216
  {product.name}
217
  </h3>
218
  <span className="text-emerald-400 font-medium text-sm whitespace-nowrap">
219
+ {product.currency === 'RUB' ? '₽' : product.currency === 'KGS' ? 'сом' : '$'}{product.price}
220
  </span>
221
  </div>
222
  <p className="text-xs text-slate-500 line-clamp-1">
 
291
  </div>
292
  </div>
293
  <div>
294
+ <label className="block text-xs text-slate-400 mb-1.5">Валюта</label>
295
+ <select
296
+ value={formData.currency}
297
+ onChange={e => setFormData({ ...formData, currency: e.target.value })}
 
298
  className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:border-indigo-500 outline-none"
299
+ >
300
+ {CURRENCY_OPTIONS.map(opt => (
301
+ <option key={opt.value} value={opt.value} className="bg-[#1a1b2e]">
302
+ {opt.label}
303
+ </option>
304
+ ))}
305
+ </select>
306
  </div>
307
  </div>
308
 
309
+ <div>
310
+ <label className="block text-xs text-slate-400 mb-1.5">Категория</label>
311
+ <input
312
+ required
313
+ value={formData.category}
314
+ onChange={e => setFormData({ ...formData, category: e.target.value })}
315
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-white text-sm focus:border-indigo-500 outline-none"
316
+ placeholder="Electronics"
317
+ />
318
+ </div>
319
+
320
  <div>
321
  <label className="block text-xs text-slate-400 mb-1.5">Изображение</label>
322
  <div className="flex items-center gap-2">