Spaces:
Sleeping
Sleeping
axeronis commited on
Commit ·
b5833df
1
Parent(s): c3b853e
fix: restore missing migration, update lead models and re-apply parallel analysis
Browse files
backend/alembic/versions/2026_01_26_add_psychotype_enums.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add new psychotype enum values for extended DISC classification.
|
| 2 |
+
|
| 3 |
+
Revision ID: add_psychotype_enums
|
| 4 |
+
Revises: 2026_01_24_granular_notif
|
| 5 |
+
Create Date: 2026-01-26
|
| 6 |
+
"""
|
| 7 |
+
from alembic import op
|
| 8 |
+
import sqlalchemy as sa
|
| 9 |
+
|
| 10 |
+
# revision identifiers
|
| 11 |
+
revision = 'add_psychotype_enums'
|
| 12 |
+
down_revision = '2026_01_24_granular_notif'
|
| 13 |
+
branch_labels = None
|
| 14 |
+
depends_on = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def upgrade():
|
| 19 |
+
"""Add new psychotype values to the PostgreSQL ENUM."""
|
| 20 |
+
# In PostgreSQL, we need to ALTER TYPE to add new enum values
|
| 21 |
+
# These must be added one by one
|
| 22 |
+
|
| 23 |
+
# Add 'analytical' value
|
| 24 |
+
op.execute("ALTER TYPE psychotype ADD VALUE IF NOT EXISTS 'analytical'")
|
| 25 |
+
|
| 26 |
+
# Add 'driven' value
|
| 27 |
+
op.execute("ALTER TYPE psychotype ADD VALUE IF NOT EXISTS 'driven'")
|
| 28 |
+
|
| 29 |
+
# Add 'emotional' value
|
| 30 |
+
op.execute("ALTER TYPE psychotype ADD VALUE IF NOT EXISTS 'emotional'")
|
| 31 |
+
|
| 32 |
+
# Add 'harmonic' value
|
| 33 |
+
op.execute("ALTER TYPE psychotype ADD VALUE IF NOT EXISTS 'harmonic'")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def downgrade():
|
| 37 |
+
"""
|
| 38 |
+
PostgreSQL does not support removing values from ENUMs.
|
| 39 |
+
This is a one-way migration.
|
| 40 |
+
"""
|
| 41 |
+
pass
|
backend/app/api/webhook.py
CHANGED
|
@@ -2338,73 +2338,86 @@ async def process_background_ai_tasks(
|
|
| 2338 |
result = await session.execute(stmt)
|
| 2339 |
conversation_history = result.scalars().all()
|
| 2340 |
|
| 2341 |
-
# 1. ESCALATION
|
| 2342 |
-
try:
|
| 2343 |
-
# Build context for escalation
|
| 2344 |
-
esc_history = []
|
| 2345 |
-
for msg in conversation_history[-10:]:
|
| 2346 |
-
esc_history.append({"sender_type": msg.sender_type, "content": msg.content})
|
| 2347 |
-
|
| 2348 |
-
# Get last AI response
|
| 2349 |
-
last_ai_response = ""
|
| 2350 |
-
if conversation_history:
|
| 2351 |
-
last_msg = conversation_history[-1]
|
| 2352 |
-
if last_msg.sender_type == 'ai':
|
| 2353 |
-
last_ai_response = last_msg.content
|
| 2354 |
-
|
| 2355 |
-
escalation_result = await escalation_service.analyze_message_smart(
|
| 2356 |
-
user_message=user_message_text,
|
| 2357 |
-
ai_response=last_ai_response,
|
| 2358 |
-
conversation_history=esc_history,
|
| 2359 |
-
heat_score=lead.heat_score or 0,
|
| 2360 |
-
business_type=getattr(tenant, 'business_type', ''),
|
| 2361 |
-
current_stage=None
|
| 2362 |
-
)
|
| 2363 |
-
|
| 2364 |
-
if escalation_result.should_escalate:
|
| 2365 |
-
logger.info(f"🚨 Escalation triggered in background: {escalation_result.reason}")
|
| 2366 |
-
lead.needs_attention = True
|
| 2367 |
-
lead.escalation_reason = escalation_result.reason
|
| 2368 |
-
session.add(lead)
|
| 2369 |
-
await session.commit()
|
| 2370 |
-
|
| 2371 |
-
# Notify Manager using EscalationService directly
|
| 2372 |
-
await escalation_service.send_escalation_notification(
|
| 2373 |
-
lead_id=str(lead.id),
|
| 2374 |
-
lead_name=lead.name or "Unknown",
|
| 2375 |
-
reason=escalation_result.reason,
|
| 2376 |
-
urgency=escalation_result.urgency,
|
| 2377 |
-
details=escalation_result.details,
|
| 2378 |
-
last_message=user_message_text,
|
| 2379 |
-
tenant_id=str(tenant.id),
|
| 2380 |
-
channel=channel
|
| 2381 |
-
)
|
| 2382 |
-
except Exception as e:
|
| 2383 |
-
logger.error(f"Background escalation check failed: {e}")
|
| 2384 |
-
|
| 2385 |
-
# 2. DEEP LEAD ANALYSIS (Psychotype, Heat, Summary)
|
| 2386 |
try:
|
| 2387 |
# Set status to analyzing
|
| 2388 |
lead.processing_status = "analyzing"
|
| 2389 |
session.add(lead)
|
| 2390 |
await session.commit()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2391 |
|
| 2392 |
-
|
| 2393 |
-
|
| 2394 |
-
|
| 2395 |
-
|
| 2396 |
-
|
| 2397 |
-
|
| 2398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2399 |
|
| 2400 |
-
|
| 2401 |
-
|
| 2402 |
-
|
| 2403 |
-
|
| 2404 |
-
|
| 2405 |
-
|
| 2406 |
|
| 2407 |
-
# Refresh lead to get latest data
|
| 2408 |
await session.refresh(lead)
|
| 2409 |
|
| 2410 |
# 3. WEBSOCKET UPDATE
|
|
@@ -2412,13 +2425,13 @@ async def process_background_ai_tasks(
|
|
| 2412 |
await notify_lead_updated(str(lead.id), {
|
| 2413 |
"id": str(lead.id),
|
| 2414 |
"ai_summary_json": lead.ai_summary_json,
|
| 2415 |
-
"qualification_data": lead.qualification_data,
|
| 2416 |
-
"qualification_complete": lead.qualification_complete,
|
| 2417 |
"heat_score": lead.heat_score,
|
| 2418 |
"heat_level": lead.heat_level.value if lead.heat_level and hasattr(lead.heat_level, 'value') else str(lead.heat_level),
|
| 2419 |
"psychotype": lead.psychotype.value if lead.psychotype and hasattr(lead.psychotype, 'value') else str(lead.psychotype),
|
| 2420 |
"name": lead.name,
|
| 2421 |
-
"processing_status": "idle",
|
| 2422 |
"needs_attention": lead.needs_attention,
|
| 2423 |
"current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None
|
| 2424 |
})
|
|
@@ -2426,7 +2439,8 @@ async def process_background_ai_tasks(
|
|
| 2426 |
logger.warning(f"WebSocket update failed: {ws_err}")
|
| 2427 |
|
| 2428 |
except Exception as e:
|
| 2429 |
-
logger.error(f"
|
|
|
|
| 2430 |
|
| 2431 |
# Finally set status back to idle
|
| 2432 |
lead.processing_status = "idle"
|
|
|
|
| 2338 |
result = await session.execute(stmt)
|
| 2339 |
conversation_history = result.scalars().all()
|
| 2340 |
|
| 2341 |
+
# 1. & 2. PARALLEL PROCESSING: ESCALATION + DEEP ANALYSIS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2342 |
try:
|
| 2343 |
# Set status to analyzing
|
| 2344 |
lead.processing_status = "analyzing"
|
| 2345 |
session.add(lead)
|
| 2346 |
await session.commit()
|
| 2347 |
+
|
| 2348 |
+
async def run_escalation():
|
| 2349 |
+
try:
|
| 2350 |
+
# Build context for escalation
|
| 2351 |
+
esc_history = []
|
| 2352 |
+
for msg in conversation_history[-10:]:
|
| 2353 |
+
esc_history.append({"sender_type": msg.sender_type, "content": msg.content})
|
| 2354 |
+
|
| 2355 |
+
# Get last AI response
|
| 2356 |
+
last_ai_response = ""
|
| 2357 |
+
if conversation_history:
|
| 2358 |
+
last_msg = conversation_history[-1]
|
| 2359 |
+
if last_msg.sender_type == 'ai':
|
| 2360 |
+
last_ai_response = last_msg.content
|
| 2361 |
|
| 2362 |
+
escalation_result = await escalation_service.analyze_message_smart(
|
| 2363 |
+
user_message=user_message_text,
|
| 2364 |
+
ai_response=last_ai_response,
|
| 2365 |
+
conversation_history=esc_history,
|
| 2366 |
+
heat_score=lead.heat_score or 0,
|
| 2367 |
+
business_type=getattr(tenant, 'business_type', ''),
|
| 2368 |
+
current_stage=None
|
| 2369 |
+
)
|
| 2370 |
+
|
| 2371 |
+
if escalation_result.should_escalate:
|
| 2372 |
+
logger.info(f"🚨 Escalation triggered in background: {escalation_result.reason}")
|
| 2373 |
+
# Use a separate session or careful commit logic to avoid conflicts
|
| 2374 |
+
async with async_session_maker() as esc_session:
|
| 2375 |
+
esc_lead = await esc_session.get(Lead, lead.id)
|
| 2376 |
+
esc_lead.needs_attention = True
|
| 2377 |
+
esc_lead.escalation_reason = escalation_result.reason
|
| 2378 |
+
esc_session.add(esc_lead)
|
| 2379 |
+
await esc_session.commit()
|
| 2380 |
+
|
| 2381 |
+
# Notify Manager
|
| 2382 |
+
await escalation_service.send_escalation_notification(
|
| 2383 |
+
lead_id=str(lead.id),
|
| 2384 |
+
lead_name=lead.name or "Unknown",
|
| 2385 |
+
reason=escalation_result.reason,
|
| 2386 |
+
urgency=escalation_result.urgency,
|
| 2387 |
+
details=escalation_result.details,
|
| 2388 |
+
last_message=user_message_text,
|
| 2389 |
+
tenant_id=str(tenant.id),
|
| 2390 |
+
channel=channel
|
| 2391 |
+
)
|
| 2392 |
+
except Exception as e:
|
| 2393 |
+
logger.error(f"Background escalation check failed: {e}")
|
| 2394 |
+
|
| 2395 |
+
async def run_analysis():
|
| 2396 |
+
try:
|
| 2397 |
+
ai_core = get_ai_core()
|
| 2398 |
+
# Use same session here for analysis as it's the main task
|
| 2399 |
+
return await ai_core.analyze_lead(
|
| 2400 |
+
session=session,
|
| 2401 |
+
lead=lead,
|
| 2402 |
+
conversation_history=conversation_history,
|
| 2403 |
+
tenant=tenant
|
| 2404 |
+
)
|
| 2405 |
+
except Exception as e:
|
| 2406 |
+
logger.error(f"Background lead analysis failed: {e}")
|
| 2407 |
+
return None
|
| 2408 |
+
|
| 2409 |
+
# Execute both in parallel
|
| 2410 |
+
results = await asyncio.gather(run_escalation(), run_analysis())
|
| 2411 |
+
analysis = results[1] # Analysis result
|
| 2412 |
|
| 2413 |
+
if analysis:
|
| 2414 |
+
logger.info(
|
| 2415 |
+
"✅ Background analysis complete",
|
| 2416 |
+
lead_id=str(lead.id),
|
| 2417 |
+
heat_score=analysis.get('heat_score')
|
| 2418 |
+
)
|
| 2419 |
|
| 2420 |
+
# Refresh lead to get latest data
|
| 2421 |
await session.refresh(lead)
|
| 2422 |
|
| 2423 |
# 3. WEBSOCKET UPDATE
|
|
|
|
| 2425 |
await notify_lead_updated(str(lead.id), {
|
| 2426 |
"id": str(lead.id),
|
| 2427 |
"ai_summary_json": lead.ai_summary_json,
|
| 2428 |
+
"qualification_data": lead.qualification_data,
|
| 2429 |
+
"qualification_complete": lead.qualification_complete,
|
| 2430 |
"heat_score": lead.heat_score,
|
| 2431 |
"heat_level": lead.heat_level.value if lead.heat_level and hasattr(lead.heat_level, 'value') else str(lead.heat_level),
|
| 2432 |
"psychotype": lead.psychotype.value if lead.psychotype and hasattr(lead.psychotype, 'value') else str(lead.psychotype),
|
| 2433 |
"name": lead.name,
|
| 2434 |
+
"processing_status": "idle",
|
| 2435 |
"needs_attention": lead.needs_attention,
|
| 2436 |
"current_stage_id": str(lead.current_stage_id) if lead.current_stage_id else None
|
| 2437 |
})
|
|
|
|
| 2439 |
logger.warning(f"WebSocket update failed: {ws_err}")
|
| 2440 |
|
| 2441 |
except Exception as e:
|
| 2442 |
+
logger.error(f"Parallel background tasks failed: {e}")
|
| 2443 |
+
|
| 2444 |
|
| 2445 |
# Finally set status back to idle
|
| 2446 |
lead.processing_status = "idle"
|
backend/app/models/lead.py
CHANGED
|
@@ -25,14 +25,23 @@ class LeadHeat(str, Enum):
|
|
| 25 |
|
| 26 |
|
| 27 |
class Psychotype(str, Enum):
|
| 28 |
-
"""DISC personality types."""
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
UNKNOWN = "unknown"
|
| 34 |
|
| 35 |
|
|
|
|
| 36 |
class ProcessingStatus(str, Enum):
|
| 37 |
"""AI processing status for real-time updates."""
|
| 38 |
IDLE = "idle" # lowercase values to match DB
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
class Psychotype(str, Enum):
|
| 28 |
+
"""DISC personality types & New Psychological Models."""
|
| 29 |
+
# Classic DISC
|
| 30 |
+
DOMINANT = "dominant"
|
| 31 |
+
INFLUENTIAL = "influential"
|
| 32 |
+
STEADY = "steady"
|
| 33 |
+
CONSCIENTIOUS = "conscientious"
|
| 34 |
+
|
| 35 |
+
# New Models (Analytical, Driven, Emotional, Harmonic)
|
| 36 |
+
ANALYTICAL = "analytical"
|
| 37 |
+
DRIVEN = "driven"
|
| 38 |
+
EMOTIONAL = "emotional"
|
| 39 |
+
HARMONIC = "harmonic"
|
| 40 |
+
|
| 41 |
UNKNOWN = "unknown"
|
| 42 |
|
| 43 |
|
| 44 |
+
|
| 45 |
class ProcessingStatus(str, Enum):
|
| 46 |
"""AI processing status for real-time updates."""
|
| 47 |
IDLE = "idle" # lowercase values to match DB
|
backend/app/services/ai_core/lead_analyzer.py
CHANGED
|
@@ -635,212 +635,152 @@ async def analyze_lead_impl(
|
|
| 635 |
print(conversation_text[:500])
|
| 636 |
print(f"{'='*80}\n")
|
| 637 |
|
| 638 |
-
#
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
# Update heat level
|
| 667 |
-
if heat_score >= 70:
|
| 668 |
-
lead.heat_level = LeadHeat.HOT
|
| 669 |
-
elif heat_score >= 50:
|
| 670 |
-
lead.heat_level = LeadHeat.WARM
|
| 671 |
-
elif heat_score >= 30:
|
| 672 |
-
lead.heat_level = LeadHeat.COLD
|
| 673 |
-
else:
|
| 674 |
-
lead.heat_level = LeadHeat.JUNK
|
| 675 |
-
|
| 676 |
-
# 🔥 HOT LEAD NOTIFICATION
|
| 677 |
-
if previous_heat_level != LeadHeat.HOT and lead.heat_level == LeadHeat.HOT:
|
| 678 |
-
print(f"🔥 Lead {lead.id} became HOT! Sending notification...")
|
| 679 |
-
try:
|
| 680 |
-
from app.services.notification import notification_service
|
| 681 |
-
await notification_service.notify_hot_lead(
|
| 682 |
-
session=session,
|
| 683 |
-
lead=lead,
|
| 684 |
-
tenant=tenant
|
| 685 |
-
)
|
| 686 |
-
print(f"✅ HOT lead notification sent successfully")
|
| 687 |
-
except Exception as e:
|
| 688 |
-
print(f"⚠️ Failed to send HOT lead notification: {e}")
|
| 689 |
-
|
| 690 |
-
# 3. Generate and merge summary
|
| 691 |
-
try:
|
| 692 |
ai_settings = getattr(lead.tenant, 'ai_settings', None) if hasattr(lead, 'tenant') else None
|
| 693 |
business_desc = (ai_settings or {}).get('business_description', 'General business')
|
| 694 |
business_type = getattr(lead.tenant, 'business_type', 'hybrid') if hasattr(lead, 'tenant') else 'hybrid'
|
| 695 |
ai_identity = getattr(lead.tenant, 'ai_identity', None) if hasattr(lead, 'tenant') else None
|
| 696 |
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
new_summary = await ai_core.llm.generate_11_point_summary(
|
| 700 |
conversation_text=conversation_text,
|
| 701 |
lead_name=lead.name or "Customer",
|
| 702 |
psychotype=lead.psychotype.value,
|
| 703 |
-
heat_score=
|
| 704 |
business_description=business_desc,
|
| 705 |
tenant_settings=ai_settings,
|
| 706 |
business_type=business_type,
|
| 707 |
-
ai_identity=ai_identity
|
| 708 |
)
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
# Only update if current name is default (from Telegram/channel) or unknown
|
| 719 |
-
current_name = lead.name or ""
|
| 720 |
-
# Check if name looks like a username (contains @, numbers, or underscores)
|
| 721 |
-
is_username = any(c in current_name for c in ['@', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
|
| 722 |
-
is_generic = current_name.lower() in ['unknown', 'клиент', 'client', 'user', '']
|
| 723 |
-
|
| 724 |
-
if is_username or is_generic or current_name != extracted_name:
|
| 725 |
-
old_name = lead.name
|
| 726 |
-
lead.name = extracted_name
|
| 727 |
-
print(f"✅ LEAD NAME UPDATED from summary: '{old_name}' → '{extracted_name}'")
|
| 728 |
-
|
| 729 |
-
print(f"🔀 Merged summary applied")
|
| 730 |
-
|
| 731 |
-
except Exception as e:
|
| 732 |
-
print(f"❌ CRITICAL: 11-point summary generation failed: {e}")
|
| 733 |
-
import traceback
|
| 734 |
-
traceback.print_exc()
|
| 735 |
-
|
| 736 |
-
if not lead.ai_summary_json:
|
| 737 |
-
lead.ai_summary_json = {
|
| 738 |
-
"intent": "Анализ в процессе",
|
| 739 |
-
"psychotype": lead.psychotype.value,
|
| 740 |
-
"heat_score": heat_score,
|
| 741 |
-
"_error": str(e)
|
| 742 |
-
}
|
| 743 |
-
|
| 744 |
-
merged_summary = lead.ai_summary_json
|
| 745 |
|
| 746 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 747 |
session.add(lead)
|
| 748 |
await session.commit()
|
| 749 |
-
|
| 750 |
-
|
|
|
|
| 751 |
try:
|
| 752 |
qualification_data = await extract_qualification_data(
|
| 753 |
ai_core, session, lead, conversation_history, tenant, summary=merged_summary
|
| 754 |
)
|
| 755 |
-
|
| 756 |
-
# We use a case-insensitive match for merging
|
| 757 |
from sqlalchemy.orm.attributes import flag_modified
|
| 758 |
existing_qual = lead.qualification_data or {}
|
| 759 |
-
|
| 760 |
-
# 1. Create a map of lowercased existing keys to original keys
|
| 761 |
lower_to_orig = {k.lower().strip(): k for k in existing_qual.keys()}
|
| 762 |
-
|
| 763 |
updated_qual = existing_qual.copy()
|
| 764 |
|
| 765 |
for field, value in qualification_data.items():
|
| 766 |
field_norm = field.lower().strip()
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
if isinstance(value, str):
|
| 770 |
-
value = value.strip()
|
| 771 |
-
|
| 772 |
-
is_new_value_valid = value and str(value).lower() not in ["не выявлено", "не указано", "нет данных", "unknown", "none", ""]
|
| 773 |
|
| 774 |
if field_norm in lower_to_orig:
|
| 775 |
-
# Key already exists (case-insensitive)
|
| 776 |
orig_key = lower_to_orig[field_norm]
|
| 777 |
-
|
| 778 |
-
# Only overwrite if new value is more informative than old one
|
| 779 |
old_value = updated_qual[orig_key]
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
if is_new_value_valid or not is_old_value_valid:
|
| 783 |
updated_qual[orig_key] = value
|
| 784 |
else:
|
| 785 |
-
# New key
|
| 786 |
updated_qual[field] = value
|
| 787 |
lower_to_orig[field_norm] = field
|
| 788 |
|
| 789 |
lead.qualification_data = updated_qual
|
| 790 |
flag_modified(lead, "qualification_data")
|
| 791 |
|
| 792 |
-
#
|
| 793 |
-
|
| 794 |
-
field_mapping = {
|
| 795 |
-
"имя": "name",
|
| 796 |
-
"имя клиента": "name",
|
| 797 |
-
"fio": "name",
|
| 798 |
-
"фио": "name",
|
| 799 |
-
"бюджет": "budget",
|
| 800 |
-
"цена": "budget",
|
| 801 |
-
"срок": "timeline",
|
| 802 |
-
"когда": "timeline",
|
| 803 |
-
"таймлайн": "timeline",
|
| 804 |
-
"потребность": "need",
|
| 805 |
-
"запрос": "need",
|
| 806 |
-
"бизнес": "niche",
|
| 807 |
-
"ниша": "niche",
|
| 808 |
-
"сфера": "niche",
|
| 809 |
-
}
|
| 810 |
-
|
| 811 |
for q_field, q_value in lead.qualification_data.items():
|
| 812 |
q_field_lower = q_field.lower().strip()
|
| 813 |
-
if q_field_lower in field_mapping:
|
| 814 |
attr_name = field_mapping[q_field_lower]
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
if attr_name == "name":
|
| 819 |
-
# Names are special - update if changed significantly
|
| 820 |
-
if lead.name != q_value:
|
| 821 |
-
lead.name = q_value
|
| 822 |
-
elif not current_val or current_val.lower() in ["неизвестно", "unknown", ""]:
|
| 823 |
-
setattr(lead, attr_name, q_value)
|
| 824 |
|
| 825 |
-
#
|
| 826 |
-
|
| 827 |
-
|
| 828 |
-
|
| 829 |
-
|
| 830 |
-
flag_modified(lead, "ai_summary_json")
|
| 831 |
|
| 832 |
session.add(lead)
|
| 833 |
await session.commit()
|
| 834 |
await session.refresh(lead)
|
| 835 |
|
| 836 |
-
# Check
|
| 837 |
await check_and_notify_qualification_complete(session, lead, tenant)
|
| 838 |
-
|
| 839 |
-
print(f"📋 Qualification data updated & synced: {lead.qualification_data}")
|
| 840 |
except Exception as qe:
|
| 841 |
print(f"⚠️ Qualification extraction failed: {qe}")
|
| 842 |
-
|
| 843 |
-
|
|
|
|
| 844 |
|
| 845 |
# Trigger CRM auto-sync
|
| 846 |
await trigger_crm_auto_sync(session, lead)
|
|
|
|
| 635 |
print(conversation_text[:500])
|
| 636 |
print(f"{'='*80}\n")
|
| 637 |
|
| 638 |
+
# --- PARALLEL ANALYSIS START ---
|
| 639 |
+
async def get_psychotype():
|
| 640 |
+
if len(user_messages) > 0:
|
| 641 |
+
pst = await ai_core.llm.analyze_psychotype(user_messages)
|
| 642 |
+
pst = pst.replace("*", "").strip().lower()
|
| 643 |
+
# Support both DISC and New Models
|
| 644 |
+
valid_pst = [
|
| 645 |
+
'analytical', 'driven', 'emotional', 'harmonic',
|
| 646 |
+
'dominant', 'influential', 'steady', 'conscientious', 'unknown'
|
| 647 |
+
]
|
| 648 |
+
return Psychotype(pst) if pst in valid_pst else Psychotype.UNKNOWN
|
| 649 |
+
return Psychotype.UNKNOWN
|
| 650 |
+
|
| 651 |
+
async def get_heat_score():
|
| 652 |
+
bant_data = {
|
| 653 |
+
"budget": lead.budget,
|
| 654 |
+
"authority": lead.authority,
|
| 655 |
+
"need": lead.need,
|
| 656 |
+
"timeline": lead.timeline
|
| 657 |
+
}
|
| 658 |
+
score = await ai_core.llm.calculate_heat_score(
|
| 659 |
+
conversation_text=conversation_text,
|
| 660 |
+
bant_data=bant_data
|
| 661 |
+
)
|
| 662 |
+
return score
|
| 663 |
+
|
| 664 |
+
async def get_summary(h_score):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 665 |
ai_settings = getattr(lead.tenant, 'ai_settings', None) if hasattr(lead, 'tenant') else None
|
| 666 |
business_desc = (ai_settings or {}).get('business_description', 'General business')
|
| 667 |
business_type = getattr(lead.tenant, 'business_type', 'hybrid') if hasattr(lead, 'tenant') else 'hybrid'
|
| 668 |
ai_identity = getattr(lead.tenant, 'ai_identity', None) if hasattr(lead, 'tenant') else None
|
| 669 |
|
| 670 |
+
return await ai_core.llm.generate_11_point_summary(
|
|
|
|
|
|
|
| 671 |
conversation_text=conversation_text,
|
| 672 |
lead_name=lead.name or "Customer",
|
| 673 |
psychotype=lead.psychotype.value,
|
| 674 |
+
heat_score=h_score,
|
| 675 |
business_description=business_desc,
|
| 676 |
tenant_settings=ai_settings,
|
| 677 |
business_type=business_type,
|
| 678 |
+
ai_identity=ai_identity
|
| 679 |
)
|
| 680 |
+
|
| 681 |
+
# 1. Start tasks in parallel
|
| 682 |
+
psy_task = asyncio.create_task(get_psychotype())
|
| 683 |
+
heat_task = asyncio.create_task(get_heat_score())
|
| 684 |
+
|
| 685 |
+
# Wait for heat score first to trigger notification ASAP
|
| 686 |
+
heat_score = await heat_task
|
| 687 |
+
previous_heat_level = lead.heat_level
|
| 688 |
+
lead.heat_score = heat_score
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 689 |
|
| 690 |
+
if heat_score >= 70: lead.heat_level = LeadHeat.HOT
|
| 691 |
+
elif heat_score >= 50: lead.heat_level = LeadHeat.WARM
|
| 692 |
+
elif heat_score >= 30: lead.heat_level = LeadHeat.COLD
|
| 693 |
+
else: lead.heat_level = LeadHeat.JUNK
|
| 694 |
+
|
| 695 |
+
# 🔥 HOT LEAD NOTIFICATION (Immediate)
|
| 696 |
+
if previous_heat_level != LeadHeat.HOT and lead.heat_level == LeadHeat.HOT:
|
| 697 |
+
print(f"🔥 Lead {lead.id} became HOT! Sending notification...")
|
| 698 |
+
try:
|
| 699 |
+
from app.services.notification import notification_service
|
| 700 |
+
await notification_service.notify_hot_lead(session=session, lead=lead, tenant=tenant)
|
| 701 |
+
except Exception as e:
|
| 702 |
+
print(f"⚠️ HOT lead notification failed: {e}")
|
| 703 |
+
|
| 704 |
+
# 2. Wait for psychotype and start summary
|
| 705 |
+
lead.psychotype = await psy_task
|
| 706 |
+
summary_task = asyncio.create_task(get_summary(heat_score))
|
| 707 |
+
|
| 708 |
+
# 3. Wait for summary and merge
|
| 709 |
+
new_summary = await summary_task
|
| 710 |
+
old_summary = lead.ai_summary_json or {}
|
| 711 |
+
merged_summary = merge_summaries(old_summary, new_summary)
|
| 712 |
+
lead.ai_summary_json = merged_summary
|
| 713 |
+
|
| 714 |
+
# Update lead name if found
|
| 715 |
+
extracted_name = new_summary.get('client_name')
|
| 716 |
+
if extracted_name and isinstance(extracted_name, str) and len(extracted_name) >= 2:
|
| 717 |
+
current_name = lead.name or ""
|
| 718 |
+
is_username = any(c in current_name for c in ['@', '_', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'])
|
| 719 |
+
is_generic = current_name.lower() in ['unknown', 'клиент', 'client', 'user', '']
|
| 720 |
+
if is_username or is_generic or current_name != extracted_name:
|
| 721 |
+
lead.name = extracted_name
|
| 722 |
+
|
| 723 |
+
# Save progress before qualification (which might also commit)
|
| 724 |
session.add(lead)
|
| 725 |
await session.commit()
|
| 726 |
+
await session.refresh(lead)
|
| 727 |
+
|
| 728 |
+
# 4. Qualification Data Extraction
|
| 729 |
try:
|
| 730 |
qualification_data = await extract_qualification_data(
|
| 731 |
ai_core, session, lead, conversation_history, tenant, summary=merged_summary
|
| 732 |
)
|
| 733 |
+
|
|
|
|
| 734 |
from sqlalchemy.orm.attributes import flag_modified
|
| 735 |
existing_qual = lead.qualification_data or {}
|
|
|
|
|
|
|
| 736 |
lower_to_orig = {k.lower().strip(): k for k in existing_qual.keys()}
|
|
|
|
| 737 |
updated_qual = existing_qual.copy()
|
| 738 |
|
| 739 |
for field, value in qualification_data.items():
|
| 740 |
field_norm = field.lower().strip()
|
| 741 |
+
if isinstance(value, str): value = value.strip()
|
| 742 |
+
is_new_valid = value and str(value).lower() not in ["не выявлено", "не указано", "нет данных", "unknown", "none", ""]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 743 |
|
| 744 |
if field_norm in lower_to_orig:
|
|
|
|
| 745 |
orig_key = lower_to_orig[field_norm]
|
|
|
|
|
|
|
| 746 |
old_value = updated_qual[orig_key]
|
| 747 |
+
is_old_valid = old_value and str(old_value).lower() not in ["не выявлено", "не указано", "нет данных", "unknown", "none", ""]
|
| 748 |
+
if is_new_valid or not is_old_valid:
|
|
|
|
| 749 |
updated_qual[orig_key] = value
|
| 750 |
else:
|
|
|
|
| 751 |
updated_qual[field] = value
|
| 752 |
lower_to_orig[field_norm] = field
|
| 753 |
|
| 754 |
lead.qualification_data = updated_qual
|
| 755 |
flag_modified(lead, "qualification_data")
|
| 756 |
|
| 757 |
+
# Sync fields mapping
|
| 758 |
+
field_mapping = {"имя": "name", "имя клиента": "name", "фио": "name", "бюджет": "budget", "срок": "timeline", "потребность": "need", "ниша": "niche"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 759 |
for q_field, q_value in lead.qualification_data.items():
|
| 760 |
q_field_lower = q_field.lower().strip()
|
| 761 |
+
if q_field_lower in field_mapping and q_value and q_value.lower() not in ["не выявлено", "не указано", ""]:
|
| 762 |
attr_name = field_mapping[q_field_lower]
|
| 763 |
+
if attr_name == "name": lead.name = q_value
|
| 764 |
+
elif not getattr(lead, attr_name) or getattr(lead, attr_name).lower() in ["неизвестно", "unknown", ""]:
|
| 765 |
+
setattr(lead, attr_name, q_value)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 766 |
|
| 767 |
+
# Mirror to Summary
|
| 768 |
+
summary = lead.ai_summary_json.copy()
|
| 769 |
+
summary['qualification'] = lead.qualification_data
|
| 770 |
+
lead.ai_summary_json = summary
|
| 771 |
+
flag_modified(lead, "ai_summary_json")
|
|
|
|
| 772 |
|
| 773 |
session.add(lead)
|
| 774 |
await session.commit()
|
| 775 |
await session.refresh(lead)
|
| 776 |
|
| 777 |
+
# Check qualification complete notification
|
| 778 |
await check_and_notify_qualification_complete(session, lead, tenant)
|
|
|
|
|
|
|
| 779 |
except Exception as qe:
|
| 780 |
print(f"⚠️ Qualification extraction failed: {qe}")
|
| 781 |
+
|
| 782 |
+
# --- PARALLEL ANALYSIS END ---
|
| 783 |
+
|
| 784 |
|
| 785 |
# Trigger CRM auto-sync
|
| 786 |
await trigger_crm_auto_sync(session, lead)
|