Spaces:
Running

File size: 12,560 Bytes
5e04bce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
"""
Lead Qualification Service

Automatically qualifies leads based on conversation analysis:
- BANT scoring (Budget, Authority, Need, Timeline)
- Heat score calculation (0-100)
- Intent detection
- Psychotype analysis
"""

from typing import List, Dict, Any, Optional
from pydantic import BaseModel
from datetime import datetime

from app.models.lead import Lead, LeadHeat, Psychotype, LeadStatus, Message


class BANTScore(BaseModel):
    """BANT qualification scores."""
    budget: int = 0  # 0-25
    authority: int = 0  # 0-25
    need: int = 0  # 0-25
    timeline: int = 0  # 0-25
    total: int = 0  # 0-100
    confidence: float = 0.0  # 0-1


class QualificationResult(BaseModel):
    """Result of lead qualification analysis."""
    heat_score: int
    heat_level: LeadHeat
    bant: BANTScore
    intent: str
    psychotype: Psychotype
    should_sync_to_crm: bool
    extracted_fields: Dict[str, Any]
    analysis_summary: str


class LeadQualificationService:
    """Service for analyzing and qualifying leads."""
    
    def __init__(self):
        self.min_hot_score = 70
        self.min_warm_score = 50
        self.min_cold_score = 30
        
    async def analyze_conversation(
        self,
        lead: Lead,
        messages: List[Message],
        ai_summary: Dict[str, Any]
    ) -> QualificationResult:
        """
        Analyze conversation and qualify the lead.
        
        Args:
            lead: The lead to analyze
            messages: Conversation messages
            ai_summary: AI-generated summary with extracted info
            
        Returns:
            QualificationResult with scores and recommendations
        """
        # Extract BANT from AI summary
        bant = self._extract_bant_from_summary(ai_summary, messages)
        
        # Calculate heat score
        heat_score = self.calculate_heat_score(bant, lead, ai_summary)
        heat_level = self._calculate_heat_level(heat_score)
        
        # Detect intent
        intent = self._detect_intent(ai_summary, messages)
        
        # Analyze psychotype
        psychotype = self._analyze_psychotype(ai_summary, messages)
        
        # Determine if should sync to CRM
        should_sync = self._should_sync_to_crm(heat_score, lead, bant)
        
        # Extract fields for CRM
        extracted_fields = self._extract_crm_fields(ai_summary, lead)
        
        # Generate analysis summary
        analysis_summary = self._generate_analysis_summary(
            bant, heat_score, intent, psychotype
        )
        
        return QualificationResult(
            heat_score=heat_score,
            heat_level=heat_level,
            bant=bant,
            intent=intent,
            psychotype=psychotype,
            should_sync_to_crm=should_sync,
            extracted_fields=extracted_fields,
            analysis_summary=analysis_summary
        )
    
    def _extract_bant_from_summary(
        self,
        ai_summary: Dict[str, Any],
        messages: List[Message]
    ) -> BANTScore:
        """Extract BANT scores from AI summary."""
        
        # Budget (0-25 points)
        budget_score = 0
        budget_text = ai_summary.get("budget", "").lower()
        
        if "million" in budget_text or "млн" in budget_text:
            budget_score = 25
        elif any(word in budget_text for word in ["ready", "готов", "выделен"]):
            budget_score = 20
        elif any(word in budget_text for word in ["range", "диапазон", "approximate", "примерно"]):
            budget_score = 15
        elif any(word in budget_text for word in ["considering", "рассматриваю", "depends", "зависит"]):
            budget_score = 10
        elif any(word in budget_text for word in ["limited", "ограничен", "small", "небольшой"]):
            budget_score = 5
        
        # Authority (0-25 points)
        authority_score = 0
        authority_text = ai_summary.get("authority", "").lower()
        
        if any(word in authority_text for word in ["owner", "ceo", "director", "владелец", "директор"]):
            authority_score = 25
        elif any(word in authority_text for word in ["head", "руководитель", "manager", "менеджер"]):
            authority_score = 20
        elif any(word in authority_text for word in ["team lead", "тимлид", "decision maker", "принимаю решения"]):
            authority_score = 15
        elif any(word in authority_text for word in ["influence", "влияние", "recommend", "рекомендую"]):
            authority_score = 10
        elif any(word in authority_text for word in ["employee", "сотрудник", "check with", "согласую"]):
            authority_score = 5
        
        # Need (0-25 points)
        need_score = 0
        need_text = ai_summary.get("need", "").lower()
        pain_points = ai_summary.get("pain_points", "").lower()
        
        urgency_keywords = ["urgent", "срочно", "critical", "критично", "losing", "теряем"]
        moderate_keywords = ["need", "нужно", "want", "хочу", "improve", "улучшить"]
        
        if any(word in need_text for word in urgency_keywords) or \
           any(word in pain_points for word in urgency_keywords):
            need_score = 25
        elif "pain" in pain_points or "проблема" in pain_points:
            need_score = 20
        elif any(word in need_text for word in moderate_keywords):
            need_score = 15
        elif "nice to have" in need_text or "было бы неплохо" in need_text:
            need_score = 10
        
        # Timeline (0-25 points)
        timeline_score = 0
        timeline_text = ai_summary.get("timeline", "").lower()
        
        if any(word in timeline_text for word in ["now", "immediately", "сейчас", "немедленно", "asap"]):
            timeline_score = 25
        elif any(word in timeline_text for word in ["week", "неделя", "days", "дней"]):
            timeline_score = 20
        elif any(word in timeline_text for word in ["month", "месяц", "quarter", "квартал"]):
            timeline_score = 15
        elif any(word in timeline_text for word in ["half year", "полгода", "year", "год"]):
            timeline_score = 10
        elif any(word in timeline_text for word in ["future", "будущем", "someday", "когда-нибудь"]):
            timeline_score = 5
        
        total = budget_score + authority_score + need_score + timeline_score
        
        # Calculate confidence based on how much information we have
        filled_fields = sum([
            1 if budget_score > 0 else 0,
            1 if authority_score > 0 else 0,
            1 if need_score > 0 else 0,
            1 if timeline_score > 0 else 0
        ])
        confidence = filled_fields / 4.0
        
        return BANTScore(
            budget=budget_score,
            authority=authority_score,
            need=need_score,
            timeline=timeline_score,
            total=total,
            confidence=confidence
        )
    
    def calculate_heat_score(
        self,
        bant: BANTScore,
        lead: Lead,
        ai_summary: Dict[str, Any]
    ) -> int:
        """Calculate overall heat score (0-100)."""
        
        # Base score from BANT
        score = bant.total
        
        # Bonus points for having contact info
        if lead.email:
            score += 5
        if lead.phone:
            score += 5
        
        # Bonus for engagement
        if ai_summary.get("objections_addressed"):
            score += 5
        
        # Reduce for negative indicators
        if ai_summary.get("intent") in ["just_browsing", "competitor_research"]:
            score -= 15
        
        # Ensure 0-100 range
        return max(0, min(100, score))
    
    def _calculate_heat_level(self, heat_score: int) -> LeadHeat:
        """Convert numerical score to heat level."""
        if heat_score >= self.min_hot_score:
            return LeadHeat.HOT
        elif heat_score >= self.min_warm_score:
            return LeadHeat.WARM
        elif heat_score >= self.min_cold_score:
            return LeadHeat.COLD
        else:
            return LeadHeat.JUNK
    
    def _detect_intent(
        self,
        ai_summary: Dict[str, Any],
        messages: List[Message]
    ) -> str:
        """Detect user intent from conversation."""
        intent = ai_summary.get("intent", "unknown")
        
        # Map AI summary intent to standard values
        intent_mapping = {
            "ready_to_buy": "ready_to_buy",
            "готов_купить": "ready_to_buy",
            "evaluating": "evaluating",
            "оценивает": "evaluating",
            "researching": "researching",
            "исследует": "researching",
            "competitor_check": "competitor_research",
            "сравнение": "competitor_research",
            "price_shopping": "price_shopping",
            "ценовой_запрос": "price_shopping",
            "just_browsing": "just_browsing",
            "просто_смотрит": "just_browsing"
        }
        
        return intent_mapping.get(intent, intent)
    
    def _analyze_psychotype(
        self,
        ai_summary: Dict[str, Any],
        messages: List[Message]
    ) -> Psychotype:
        """Analyze psychotype from conversation."""
        psycho = ai_summary.get("psychotype", "unknown").lower()
        
        psychotype_mapping = {
            "driver": Psychotype.DOMINANT,
            "доминантный": Psychotype.DOMINANT,
            "analytical": Psychotype.CONSCIENTIOUS,
            "аналитический": Psychotype.CONSCIENTIOUS,
            "expressive": Psychotype.INFLUENTIAL,
            "влиятельный": Psychotype.INFLUENTIAL,
            "amiable": Psychotype.STEADY,
            "стабильный": Psychotype.STEADY,
        }
        
        return psychotype_mapping.get(psycho, Psychotype.UNKNOWN)
    
    def _should_sync_to_crm(
        self,
        heat_score: int,
        lead: Lead,
        bant: BANTScore
    ) -> bool:
        """Determine if lead should be synced to CRM."""
        
        # Must be hot lead
        if heat_score < self.min_hot_score:
            return False
        
        # Must have contact info
        if not lead.email and not lead.phone:
            return False
        
        # Must have decent confidence in BANT scoring
        if bant.confidence < 0.5:
            return False
        
        return True
    
    def _extract_crm_fields(
        self,
        ai_summary: Dict[str, Any],
        lead: Lead
    ) -> Dict[str, Any]:
        """Extract fields suitable for CRM sync."""
        
        fields = {
            "name": lead.name,
            "email": lead.email,
            "phone": lead.phone,
            "company": ai_summary.get("company"),
            "position": ai_summary.get("position"),
            "industry": ai_summary.get("industry"),
            "budget": ai_summary.get("budget"),
            "timeline": ai_summary.get("timeline"),
            "use_case": ai_summary.get("use_case"),
            "pain_points": ai_summary.get("pain_points"),
            "decision_context": ai_summary.get("decision_context"),
        }
        
        # Remove None values
        return {k: v for k, v in fields.items() if v is not None}
    
    def _generate_analysis_summary(
        self,
        bant: BANTScore,
        heat_score: int,
        intent: str,
        psychotype: Psychotype
    ) -> str:
        """Generate human-readable analysis summary."""
        
        parts = [
            f"Heat Score: {heat_score}/100",
            f"BANT Total: {bant.total}/100",
            f"Intent: {intent}",
            f"Psychotype: {psychotype.value}"
        ]
        
        if bant.confidence < 0.5:
            parts.append("⚠️ Need more information for accurate qualification")
        
        return " | ".join(parts)


# Singleton instance
_qualification_service: Optional[LeadQualificationService] = None


def get_qualification_service() -> LeadQualificationService:
    """Get lead qualification service singleton."""
    global _qualification_service
    if _qualification_service is None:
        _qualification_service = LeadQualificationService()
    return _qualification_service