Spaces:
Running
Running
axeronis commited on
Commit ·
aecbce0
1
Parent(s): e58beec
Fix qualification visibility, LLM robustness, and duplicate booking logic
Browse files
backend/app/api/webhook.py
CHANGED
|
@@ -1441,48 +1441,70 @@ async def process_ai_response_background(
|
|
| 1441 |
await session.refresh(default_srv)
|
| 1442 |
logger.info(f"🆕 Auto-created default service for tenant {tenant_id}")
|
| 1443 |
|
| 1444 |
-
#
|
| 1445 |
-
|
| 1446 |
Appointment.lead_id == lead_id,
|
| 1447 |
-
Appointment.status == AppointmentStatus.SCHEDULED
|
| 1448 |
-
)
|
| 1449 |
-
old_appts_result = await session.execute(old_appts_stmt)
|
| 1450 |
-
old_appointments = old_appts_result.scalars().all()
|
| 1451 |
-
|
| 1452 |
-
is_rescheduled = len(old_appointments) > 0 # Track if this is a reschedule
|
| 1453 |
-
|
| 1454 |
-
for old_appt in old_appointments:
|
| 1455 |
-
old_time = old_appt.start_time
|
| 1456 |
-
old_appt.status = AppointmentStatus.CANCELLED
|
| 1457 |
-
old_appt.notes = f"[Перенесено на {start_time.strftime('%d.%m в %H:%M')}] {old_appt.notes or ''}"
|
| 1458 |
-
session.add(old_appt)
|
| 1459 |
-
logger.info(f"🔄 Auto-cancelled old appointment {old_appt.id} for lead {lead_id}")
|
| 1460 |
-
|
| 1461 |
-
# 🔔 NOTIFY ADMIN about reschedule
|
| 1462 |
-
try:
|
| 1463 |
-
from app.services.notification import notification_service
|
| 1464 |
-
old_appt.lead = lead
|
| 1465 |
-
await notification_service.notify_reschedule(
|
| 1466 |
-
tenant=tenant,
|
| 1467 |
-
old_appointment=old_appt,
|
| 1468 |
-
old_time=old_time,
|
| 1469 |
-
new_time=start_time,
|
| 1470 |
-
lead_name=lead.name or "Клиент"
|
| 1471 |
-
)
|
| 1472 |
-
except Exception as ns_err:
|
| 1473 |
-
logger.error(f"⚠️ Reschedule notification failed: {ns_err}")
|
| 1474 |
-
|
| 1475 |
-
if old_appointments:
|
| 1476 |
-
await session.commit()
|
| 1477 |
-
|
| 1478 |
-
# CHECK FOR TIME SLOT CONFLICT
|
| 1479 |
-
conflict_stmt = select(Appointment).where(
|
| 1480 |
-
Appointment.tenant_id == tenant_id,
|
| 1481 |
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1482 |
Appointment.start_time == start_time
|
| 1483 |
)
|
| 1484 |
-
|
| 1485 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1486 |
|
| 1487 |
if existing_booking:
|
| 1488 |
# Slot is taken - find alternatives and suggest them
|
|
|
|
| 1441 |
await session.refresh(default_srv)
|
| 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()
|
| 1452 |
+
|
| 1453 |
+
if existing_matching:
|
| 1454 |
+
# Already booked for this lead at this time - just confirm, don't create duplicate or notify reschedule
|
| 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 "(Система: Запись создана успешно!)" not in ai_text:
|
| 1459 |
+
ai_text += "\n\n✅ (Система: Запись уже подтверждена!)"
|
| 1460 |
+
ai_response["text"] = ai_text
|
| 1461 |
+
else:
|
| 1462 |
+
# NEW OR CHANGED TIME - Proceed with auto-cancel and new booking
|
| 1463 |
+
|
| 1464 |
+
# AUTO-CANCEL OLD BOOKINGS for this lead (other than the same time which we checked above)
|
| 1465 |
+
old_appts_stmt = select(Appointment).where(
|
| 1466 |
+
Appointment.lead_id == lead_id,
|
| 1467 |
+
Appointment.status == AppointmentStatus.SCHEDULED,
|
| 1468 |
+
Appointment.start_time != start_time # Explicitly different time
|
| 1469 |
+
)
|
| 1470 |
+
old_appts_result = await session.execute(old_appts_stmt)
|
| 1471 |
+
old_appointments = old_appts_result.scalars().all()
|
| 1472 |
+
|
| 1473 |
+
is_rescheduled = len(old_appointments) > 0 # Track if this is a reschedule
|
| 1474 |
+
|
| 1475 |
+
for old_appt in old_appointments:
|
| 1476 |
+
old_time = old_appt.start_time
|
| 1477 |
+
old_appt.status = AppointmentStatus.CANCELLED
|
| 1478 |
+
old_appt.notes = f"[Перенесено на {start_time.strftime('%d.%m в %H:%M')}] {old_appt.notes or ''}"
|
| 1479 |
+
session.add(old_appt)
|
| 1480 |
+
logger.info(f"🔄 Auto-cancelled old appointment {old_appt.id} for lead {lead_id}")
|
| 1481 |
+
|
| 1482 |
+
# 🔔 NOTIFY ADMIN about reschedule
|
| 1483 |
+
try:
|
| 1484 |
+
from app.services.notification import notification_service
|
| 1485 |
+
old_appt.lead = lead
|
| 1486 |
+
await notification_service.notify_reschedule(
|
| 1487 |
+
tenant=tenant,
|
| 1488 |
+
old_appointment=old_appt,
|
| 1489 |
+
old_time=old_time,
|
| 1490 |
+
new_time=start_time,
|
| 1491 |
+
lead_name=lead.name or "Клиент"
|
| 1492 |
+
)
|
| 1493 |
+
except Exception as ns_err:
|
| 1494 |
+
logger.error(f"⚠️ Reschedule notification failed: {ns_err}")
|
| 1495 |
+
|
| 1496 |
+
if old_appointments:
|
| 1497 |
+
await session.commit()
|
| 1498 |
+
|
| 1499 |
+
# CHECK FOR TIME SLOT CONFLICT (with OTHER leads)
|
| 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 |
if existing_booking:
|
| 1510 |
# Slot is taken - find alternatives and suggest them
|
backend/app/models/ai_summary.py
CHANGED
|
@@ -7,6 +7,8 @@ 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 |
# CLIENT IDENTIFICATION
|
| 12 |
client_name: Optional[str] = Field(
|
|
|
|
| 7 |
11-Point Lead Summary Schema with Confidence Tracking.
|
| 8 |
Enhanced with confidence scores (0.0-1.0) for each key field.
|
| 9 |
"""
|
| 10 |
+
class Config:
|
| 11 |
+
extra = "allow"
|
| 12 |
|
| 13 |
# CLIENT IDENTIFICATION
|
| 14 |
client_name: Optional[str] = Field(
|
backend/app/services/ai_core/lead_analyzer.py
CHANGED
|
@@ -793,12 +793,35 @@ async def analyze_lead_impl(
|
|
| 793 |
ai_core, session, lead, conversation_history, tenant
|
| 794 |
)
|
| 795 |
# Merge with existing (preserve already collected data)
|
|
|
|
| 796 |
existing_qual = lead.qualification_data or {}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 797 |
for field, value in qualification_data.items():
|
| 798 |
-
|
| 799 |
-
|
| 800 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 801 |
existing_qual[field] = value
|
|
|
|
| 802 |
|
| 803 |
lead.qualification_data = existing_qual
|
| 804 |
|
|
|
|
| 793 |
ai_core, session, lead, conversation_history, tenant
|
| 794 |
)
|
| 795 |
# Merge with existing (preserve already collected data)
|
| 796 |
+
# We use a case-insensitive match for merging
|
| 797 |
existing_qual = lead.qualification_data or {}
|
| 798 |
+
|
| 799 |
+
# 1. Create a map of lowercased existing keys to original keys
|
| 800 |
+
lower_to_orig = {k.lower().strip(): k for k in existing_qual.keys()}
|
| 801 |
+
|
| 802 |
for field, value in qualification_data.items():
|
| 803 |
+
field_norm = field.lower().strip()
|
| 804 |
+
|
| 805 |
+
# Clean value
|
| 806 |
+
if isinstance(value, str):
|
| 807 |
+
value = value.strip()
|
| 808 |
+
|
| 809 |
+
is_new_value_valid = value and str(value).lower() not in ["не выявлено", "не указано", "нет данных", "unknown", "none", ""]
|
| 810 |
+
|
| 811 |
+
if field_norm in lower_to_orig:
|
| 812 |
+
# Key already exists (case-insensitive)
|
| 813 |
+
orig_key = lower_to_orig[field_norm]
|
| 814 |
+
|
| 815 |
+
# Only overwrite if new value is more informative than old one
|
| 816 |
+
old_value = existing_qual[orig_key]
|
| 817 |
+
is_old_value_valid = old_value and str(old_value).lower() not in ["не выявлено", "не указано", "нет данных", "unknown", "none", ""]
|
| 818 |
+
|
| 819 |
+
if is_new_value_valid or not is_old_value_valid:
|
| 820 |
+
existing_qual[orig_key] = value
|
| 821 |
+
else:
|
| 822 |
+
# New key
|
| 823 |
existing_qual[field] = value
|
| 824 |
+
lower_to_orig[field_norm] = field
|
| 825 |
|
| 826 |
lead.qualification_data = existing_qual
|
| 827 |
|
backend/app/services/llm_client.py
CHANGED
|
@@ -303,11 +303,35 @@ All text fields in RUSSIAN.
|
|
| 303 |
# Validation via Pydantic but return clean dict
|
| 304 |
return AISummary(**data).model_dump()
|
| 305 |
except Exception as e:
|
| 306 |
-
logger.error(f"Summary failed: {e}")
|
| 307 |
-
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
async def analyze_escalation(
|
| 313 |
self,
|
|
|
|
| 303 |
# Validation via Pydantic but return clean dict
|
| 304 |
return AISummary(**data).model_dump()
|
| 305 |
except Exception as e:
|
| 306 |
+
logger.error(f"Summary generation failed (Native JSON mode): {e}")
|
| 307 |
+
# Try plain text fallback if JSON schema failed
|
| 308 |
+
try:
|
| 309 |
+
fallback_res = await loop.run_in_executor(
|
| 310 |
+
None,
|
| 311 |
+
lambda: self.client.models.generate_content(
|
| 312 |
+
model=self.default_model_name,
|
| 313 |
+
contents=f"{prompt}\n\nВАЖНО: Если не получается JSON, просто напиши краткое саммари текстом.",
|
| 314 |
+
config=types.GenerateContentConfig(temperature=0.7)
|
| 315 |
+
)
|
| 316 |
+
)
|
| 317 |
+
return {
|
| 318 |
+
"intent": "Анализ (текст)",
|
| 319 |
+
"recommendation": fallback_res.text[:500],
|
| 320 |
+
"heat_score": heat_score,
|
| 321 |
+
"psychotype": psychotype,
|
| 322 |
+
"pain_points": [],
|
| 323 |
+
"objections": []
|
| 324 |
+
}
|
| 325 |
+
except:
|
| 326 |
+
return {
|
| 327 |
+
"intent": "Ошибка анализа",
|
| 328 |
+
"recommendation": "Пожалуйста, просмотрите диалог вручную.",
|
| 329 |
+
"heat_score": heat_score,
|
| 330 |
+
"psychotype": psychotype,
|
| 331 |
+
"pain_points": [],
|
| 332 |
+
"objections": [],
|
| 333 |
+
"_error": str(e)
|
| 334 |
+
}
|
| 335 |
|
| 336 |
async def analyze_escalation(
|
| 337 |
self,
|
frontend/components/ClientCard.tsx
CHANGED
|
@@ -181,10 +181,17 @@ export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversat
|
|
| 181 |
// Filter out points that are already in the qualification card to avoid duplication
|
| 182 |
const qualData = (lead as any).qualification_data || {}
|
| 183 |
const hasQualField = (label: string) => {
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
}
|
| 189 |
|
| 190 |
const realSummaryPoints = [
|
|
@@ -241,28 +248,41 @@ export function ClientCard({ lead, onTakeover, isAnalyzing, onRefresh, conversat
|
|
| 241 |
// Wait for stages to load once to prevent flickering
|
| 242 |
if (!fieldsLoaded) return false
|
| 243 |
|
| 244 |
-
//
|
|
|
|
|
|
|
|
|
|
| 245 |
const isNotFound = !value ||
|
| 246 |
(typeof value === 'string' && (
|
| 247 |
value.toLowerCase().includes('не выявлено') ||
|
| 248 |
value.toLowerCase().includes('не указано') ||
|
| 249 |
-
value.toLowerCase().includes('нет данных')
|
|
|
|
|
|
|
| 250 |
))
|
| 251 |
|
| 252 |
if (isNotFound) {
|
| 253 |
-
// Only show "Not found"
|
| 254 |
-
return selectedFields.some(sf =>
|
| 255 |
-
sf.toLowerCase()
|
| 256 |
-
|
| 257 |
-
|
| 258 |
-
|
|
|
|
| 259 |
}
|
| 260 |
|
| 261 |
-
// If it HAS data, ALWAYS show it
|
| 262 |
return true
|
| 263 |
})
|
| 264 |
.map(([field, value]: [string, any]) => {
|
| 265 |
-
const isNotFound = !value ||
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 266 |
|
| 267 |
// Dynamic Icon selection
|
| 268 |
let Icon = Target
|
|
|
|
| 181 |
// Filter out points that are already in the qualification card to avoid duplication
|
| 182 |
const qualData = (lead as any).qualification_data || {}
|
| 183 |
const hasQualField = (label: string) => {
|
| 184 |
+
const labelLower = label.toLowerCase().trim()
|
| 185 |
+
return Object.entries(qualData).some(([k, v]) => {
|
| 186 |
+
const kLower = k.toLowerCase().trim()
|
| 187 |
+
const isNotFound = !v || (typeof v === 'string' && (
|
| 188 |
+
v.toLowerCase().includes('не выявлено') ||
|
| 189 |
+
v.toLowerCase().includes('не указано') ||
|
| 190 |
+
v.toLowerCase() === 'none' ||
|
| 191 |
+
v.toLowerCase() === 'unknown'
|
| 192 |
+
))
|
| 193 |
+
return (kLower === labelLower || kLower.includes(labelLower) || labelLower.includes(kLower)) && !isNotFound
|
| 194 |
+
})
|
| 195 |
}
|
| 196 |
|
| 197 |
const realSummaryPoints = [
|
|
|
|
| 248 |
// Wait for stages to load once to prevent flickering
|
| 249 |
if (!fieldsLoaded) return false
|
| 250 |
|
| 251 |
+
// Use lowercased key for matching
|
| 252 |
+
const fieldLower = field.toLowerCase().trim()
|
| 253 |
+
|
| 254 |
+
// Check if this field or its value is "empty"
|
| 255 |
const isNotFound = !value ||
|
| 256 |
(typeof value === 'string' && (
|
| 257 |
value.toLowerCase().includes('не выявлено') ||
|
| 258 |
value.toLowerCase().includes('не указано') ||
|
| 259 |
+
value.toLowerCase().includes('нет данных') ||
|
| 260 |
+
value.toLowerCase() === 'none' ||
|
| 261 |
+
value.toLowerCase() === 'unknown'
|
| 262 |
))
|
| 263 |
|
| 264 |
if (isNotFound) {
|
| 265 |
+
// Only show "Not found" placeholder if it's explicitly required in exit_criteria
|
| 266 |
+
return selectedFields.some(sf => {
|
| 267 |
+
const sfLower = sf.toLowerCase().trim()
|
| 268 |
+
return sfLower === fieldLower ||
|
| 269 |
+
fieldLower.includes(sfLower) ||
|
| 270 |
+
sfLower.includes(fieldLower)
|
| 271 |
+
})
|
| 272 |
}
|
| 273 |
|
| 274 |
+
// If it HAS data, ALWAYS show it
|
| 275 |
return true
|
| 276 |
})
|
| 277 |
.map(([field, value]: [string, any]) => {
|
| 278 |
+
const isNotFound = !value ||
|
| 279 |
+
(typeof value === 'string' && (
|
| 280 |
+
value.toLowerCase().includes('не выявлено') ||
|
| 281 |
+
value.toLowerCase().includes('не указано') ||
|
| 282 |
+
value.toLowerCase().includes('нет данных') ||
|
| 283 |
+
value.toLowerCase() === 'none' ||
|
| 284 |
+
value.toLowerCase() === 'unknown'
|
| 285 |
+
))
|
| 286 |
|
| 287 |
// Dynamic Icon selection
|
| 288 |
let Icon = Target
|