""" Analytics Service Layer - Бизнес-логика расчета метрик Dashboard. Отделено от API routes для: - Тестируемости (можно тестировать без HTTP) - Переиспользования (можно вызывать из других сервисов) - Чистоты архитектуры (Single Responsibility Principle) """ from typing import Dict, Any, List from uuid import UUID from datetime import datetime, timedelta import re from sqlmodel import select, func from sqlmodel.ext.asyncio.session import AsyncSession from app.models import Lead, Message, Tenant, Conversation, SalesStage from app.core.logging import get_logger logger = get_logger(__name__) # ============================================================================ # Response Models (перенесены из analytics.py для переиспользования) # ============================================================================ class DashboardMetrics: """Основные метрики дашборда.""" def __init__( self, total_leads: int, hot_leads: int, warm_leads: int, cold_leads: int, active_leads_24h: int, # NEW conversion_rate: float, pipeline_value: float, avg_response_time_seconds: float, # NEW total_bookings: int, # NEW hours_saved: float, money_saved: float, # Percentage changes # Business Value Metrics weighted_pipeline_value: float = 0.0, # NEW: Forecast sales_velocity: float = 0.0, # NEW: Avg days to close revenue_influenced: float = 0.0, # NEW: ROI metric # AI Performance Metrics ai_autonomy_rate: float = 0.0, # NEW: % of auto-handled leads # Growth Metrics total_leads_change: float = 0.0, conversion_rate_change: float = 0.0, pipeline_value_change: float = 0.0, # Deprecated/Admin only (kept for compatibility but hidden in UI) token_usage_24h: int = 0, ai_cost_usd: float = 0.0, spam_hits_24h: int = 0 ): self.total_leads = total_leads self.hot_leads = hot_leads self.warm_leads = warm_leads self.cold_leads = cold_leads self.active_leads_24h = active_leads_24h self.total_leads_change = total_leads_change self.conversion_rate_change = conversion_rate_change self.pipeline_value_change = pipeline_value_change self.conversion_rate = conversion_rate self.pipeline_value = pipeline_value self.weighted_pipeline_value = weighted_pipeline_value self.sales_velocity = sales_velocity self.avg_response_time_seconds = avg_response_time_seconds self.total_bookings = total_bookings self.hours_saved = hours_saved self.money_saved = money_saved self.revenue_influenced = revenue_influenced self.ai_autonomy_rate = ai_autonomy_rate self.total_leads_change = total_leads_change self.conversion_rate_change = conversion_rate_change self.pipeline_value_change = pipeline_value_change self.token_usage_24h = token_usage_24h self.ai_cost_usd = ai_cost_usd self.spam_hits_24h = spam_hits_24h class FunnelStageData: """Данные по одному этапу воронки.""" def __init__(self, stage: str, count: int, percentage: float): self.stage = stage self.count = count self.percentage = percentage class DISCDistributionData: """Распределение по DISC-психотипам.""" def __init__(self, psychotype: str, count: int, percentage: float): self.psychotype = psychotype self.count = count self.percentage = percentage class ObjectionData: """Данные по возражениям лидов.""" def __init__(self, objection: str, count: int, percentage: float): self.objection = objection self.count = count self.percentage = percentage class LeadValueOverTimeData: """Стоимость лидов по дням.""" def __init__(self, date: str, value: float, count: int): self.date = date self.value = value self.count = count class ChannelStatsData: """Статистика лидов по каналам.""" def __init__(self, channel: str, count: int, percentage: float): self.channel = channel self.count = count self.percentage = percentage class DashboardData: """Полные данные дашборда.""" def __init__( self, metrics: DashboardMetrics, funnel: List[FunnelStageData], disc_distribution: List[DISCDistributionData], top_objections: List[ObjectionData], lead_value_over_time: List[LeadValueOverTimeData], channel_stats: List[ChannelStatsData] # NEW ): self.metrics = metrics self.funnel = funnel self.disc_distribution = disc_distribution self.top_objections = top_objections self.lead_value_over_time = lead_value_over_time self.channel_stats = channel_stats # ============================================================================ # Analytics Service # ============================================================================ class AnalyticsService: """ Сервис для расчета аналитических метрик. Все методы принимают session и tenant_id для обеспечения изоляции. """ async def calculate_dashboard_metrics( self, session: AsyncSession, tenant_id: UUID, date_from: str = None, date_to: str = None ) -> DashboardData: """ Рассчитать все метрики для дашборда. Args: session: Async database session tenant_id: UUID тенанта (для изоляции данных) date_from: Start date (YYYY-MM-DD) or None for all time date_to: End date (YYYY-MM-DD) or None for today Returns: DashboardData с полным набором метрик """ logger.info("Calculating dashboard metrics", tenant_id=str(tenant_id)) # 1. Получить тенанта для ROI расчетов tenant = await self._get_tenant(session, tenant_id) # 2. Parse dates from_date = None to_date = None if date_from: from_date = datetime.strptime(date_from, '%Y-%m-%d') if date_to: to_date = datetime.strptime(date_to, '%Y-%m-%d') else: to_date = datetime.utcnow() # 3. Получить лиды за текущий период leads = await self._get_tenant_leads_filtered(session, tenant_id, from_date, to_date) # 4. Если лидов нет - вернуть пустой дашборд if not leads: return self._empty_dashboard() # 5. Calculate dates for previous period comparison prev_from_date = None prev_to_date = None if from_date and to_date: period_length = (to_date - from_date).days prev_to_date = from_date prev_from_date = from_date - timedelta(days=period_length) else: # Default: compare last 30 days vs previous 30 days prev_to_date = datetime.utcnow() - timedelta(days=30) prev_from_date = prev_to_date - timedelta(days=30) # 6. Get previous period leads for comparison prev_leads = await self._get_tenant_leads_filtered( session, tenant_id, prev_from_date, prev_to_date ) # 7. Рассчитать основные метрики (с сравнением) metrics = await self._calculate_metrics( session, tenant, leads, prev_leads ) # 8. Получить этапы продаж и рассчитать воронку stages_result = await session.execute( select(SalesStage) .where(SalesStage.tenant_id == tenant_id, SalesStage.is_active == True) .order_by(SalesStage.order_index) ) sales_stages = stages_result.scalars().all() funnel = self._calculate_funnel(leads, sales_stages) # 9. Рассчитать DISC распределение disc_distribution = self._calculate_disc_distribution(leads) # 10. Извлечь топ возражений top_objections = self._extract_top_objections(leads) # 11. Рассчитать стоимость лидов по дням lead_value_over_time = self._calculate_lead_value_over_time(leads) logger.info( "Dashboard metrics calculated", tenant_id=str(tenant_id), total_leads=len(leads), hot_leads=metrics.hot_leads ) # 12. Рассчитать статистику по каналам (Real Data) db_channel_counts = {} if leads: try: lead_ids = [l.id for l in leads] # Avoid large IN list if possible, but for dashboard pages it's usually fine (<1000 items) # If leads list is large, this might be slow, but better than N+1 chan_stmt = ( select(Conversation.channel, func.count(func.distinct(Lead.id))) .join(Lead) .where(Lead.id.in_(lead_ids)) .group_by(Conversation.channel) ) chan_res = await session.execute(chan_stmt) db_channel_counts = {row[0]: row[1] for row in chan_res.all()} except Exception as e: logger.error(f"Error fetching channel stats: {e}") channel_stats = self._calculate_channel_stats(leads, db_channel_counts) return DashboardData( metrics=metrics, funnel=funnel, disc_distribution=disc_distribution, top_objections=top_objections, lead_value_over_time=lead_value_over_time, channel_stats=channel_stats ) # ======================================================================== # Приватные методы (бизнес-логика) # ======================================================================== async def _get_tenant(self, session: AsyncSession, tenant_id: UUID) -> Tenant: """Получить тенанта из БД.""" stmt = select(Tenant).where(Tenant.id == tenant_id) result = await session.execute(stmt) tenant = result.scalar_one_or_none() if not tenant: raise ValueError(f"Tenant {tenant_id} not found") return tenant async def _get_tenant_leads(self, session: AsyncSession, tenant_id: UUID) -> List[Lead]: """Получить все лиды тенанта.""" stmt = select(Lead).where(Lead.tenant_id == tenant_id) result = await session.execute(stmt) return list(result.scalars().all()) async def _get_tenant_leads_filtered( self, session: AsyncSession, tenant_id: UUID, date_from: datetime = None, date_to: datetime = None ) -> List[Lead]: """Получить лиды тенанта с фильтрацией по датам.""" stmt = select(Lead).where(Lead.tenant_id == tenant_id) if date_from: stmt = stmt.where(Lead.created_at >= date_from) if date_to: # Add 1 day to include the entire end date end_of_day = date_to + timedelta(days=1) stmt = stmt.where(Lead.created_at < end_of_day) result = await session.execute(stmt) return list(result.scalars().all()) def _empty_dashboard(self) -> DashboardData: """Вернуть пустой дашборд для тенанта без лидов.""" return DashboardData( metrics=DashboardMetrics( total_leads=0, hot_leads=0, warm_leads=0, cold_leads=0, active_leads_24h=0, conversion_rate=0.0, pipeline_value=0.0, avg_response_time_seconds=0.0, total_bookings=0, hours_saved=0.0, money_saved=0.0, total_leads_change=0.0, conversion_rate_change=0.0, pipeline_value_change=0.0, token_usage_24h=0, ai_cost_usd=0.0, spam_hits_24h=0 ), funnel=[], disc_distribution=[], top_objections=[], lead_value_over_time=[], channel_stats=[] ) async def _calculate_metrics( self, session: AsyncSession, tenant: Tenant, leads: List[Lead], prev_leads: List[Lead] ) -> DashboardMetrics: """Рассчитать основные метрики.""" total_leads = len(leads) # Подсчет по heat level hot_leads = sum(1 for lead in leads if lead.heat_level and lead.heat_level.value == "hot") warm_leads = sum(1 for lead in leads if lead.heat_level and lead.heat_level.value == "warm") cold_leads = sum(1 for lead in leads if lead.heat_level and lead.heat_level.value == "cold") # Active Leads (last 24 hours) from datetime import timezone now = datetime.now(timezone.utc) active_leads_24h = 0 for lead in leads: if lead.last_message_at: lead_time = lead.last_message_at if lead_time.tzinfo is None: lead_time = lead_time.replace(tzinfo=timezone.utc) if (now - lead_time).total_seconds() < 86400: active_leads_24h += 1 # Conversion rate (FIXED: only closed deals) closed_deals = sum(1 for lead in leads if lead.status == "closed") conversion_rate = (closed_deals / total_leads * 100) if total_leads > 0 else 0.0 # Pipeline value (из бюджетов) pipeline_value = self._calculate_pipeline_value(leads) # Total Bookings try: from app.models.booking import Appointment stmt = select(func.count(Appointment.id)).where( Appointment.tenant_id == tenant.id, Appointment.status == "SCHEDULED" ) total_bookings = await session.scalar(stmt) or 0 except Exception as e: logger.warning(f"Failed to count bookings: {e}") total_bookings = 0 # Avg Response Time avg_response_time = await self._calculate_avg_response_time(session, tenant.id) # Hours saved (20 минут на лид) hours_saved = (total_leads * 20) / 60 # Money saved (ROI based on messages) money_saved = await self._calculate_money_saved(session, tenant) # Calculate percentage changes vs previous period prev_total_leads = len(prev_leads) prev_closed_deals = sum(1 for lead in prev_leads if lead.status == "closed") prev_conversion_rate = (prev_closed_deals / prev_total_leads * 100) if prev_total_leads > 0 else 0.0 prev_pipeline_value = self._calculate_pipeline_value(prev_leads) # % Change calculations total_leads_change = ((total_leads - prev_total_leads) / prev_total_leads * 100) if prev_total_leads > 0 else 0.0 conversion_rate_change = conversion_rate - prev_conversion_rate # Absolute difference in percentage points pipeline_value_change = ((pipeline_value - prev_pipeline_value) / prev_pipeline_value * 100) if prev_pipeline_value > 0 else 0.0 return DashboardMetrics( total_leads=total_leads, hot_leads=hot_leads, warm_leads=warm_leads, cold_leads=cold_leads, active_leads_24h=active_leads_24h, conversion_rate=round(conversion_rate, 1), pipeline_value=round(pipeline_value, 2), weighted_pipeline_value=self._calculate_weighted_pipeline(leads), # NEW sales_velocity=self._calculate_sales_velocity(leads), # NEW avg_response_time_seconds=avg_response_time, total_bookings=total_bookings, hours_saved=round(hours_saved, 1), money_saved=round(money_saved, 2), revenue_influenced=self._calculate_revenue_influenced(leads), # NEW ai_autonomy_rate=self._calculate_ai_autonomy(leads), # NEW total_leads_change=round(total_leads_change, 1), conversion_rate_change=round(conversion_rate_change, 1), pipeline_value_change=round(pipeline_value_change, 1), token_usage_24h=await self._calculate_token_usage_24h(session, tenant.id), ai_cost_usd=await self._calculate_ai_cost_24h(session, tenant.id), spam_hits_24h=await self._calculate_spam_hits_24h(session, tenant.id) ) def _calculate_pipeline_value(self, leads: List[Lead]) -> float: """Извлечь и суммировать бюджеты из лидов.""" pipeline_value = 0.0 for lead in leads: # Из поля budget if lead.budget: budget_str = str(lead.budget) numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', budget_str.replace(',', '')) if numbers: try: pipeline_value += float(numbers[0]) except ValueError: pass # Из AI summary if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict): summary_budget = lead.ai_summary_json.get('budget', '') if summary_budget: numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(summary_budget).replace(',', '')) if numbers: try: pipeline_value += float(numbers[0]) except ValueError: pass return pipeline_value async def _calculate_money_saved(self, session: AsyncSession, tenant: Tenant) -> float: """Рассчитать сэкономленные деньги на основе сообщений.""" # Подсчитать общее количество сообщений msg_stmt = select(func.count(Message.id)).where(Message.tenant_id == tenant.id) msg_result = await session.execute(msg_stmt) total_messages = msg_result.scalar() or 0 # Рассчитать почасовую ставку менеджера hourly_rate = tenant.manager_monthly_salary / 160 # AI экономит 3 минуты (0.05 часа) на сообщение money_saved = total_messages * 0.05 * hourly_rate return money_saved async def _calculate_avg_response_time( self, session: AsyncSession, tenant_id: UUID ) -> float: """Рассчитать среднее время ответа AI в секундах (Optimized).""" try: # Fetch last 500 messages ordered by time (covers enough history for recent convs) stmt = select(Message).where( Message.tenant_id == tenant_id ).order_by(Message.created_at.desc()).limit(500) result = await session.execute(stmt) all_messages = list(result.scalars().all()) if not all_messages: return 0.0 # Sort chronologically for easier processing: Oldest -> Newest all_messages.sort(key=lambda m: m.created_at) total_time = 0.0 count = 0 # Group by lead_id/conversation to ensure we compare messages in same chat msgs_by_lead = {} for msg in all_messages: if msg.lead_id not in msgs_by_lead: msgs_by_lead[msg.lead_id] = [] msgs_by_lead[msg.lead_id].append(msg) for lead_id, msgs in msgs_by_lead.items(): last_user_msg_time = None for msg in msgs: if msg.sender_type == "user": last_user_msg_time = msg.created_at elif msg.sender_type in ["assistant", "ai"] and last_user_msg_time: # Found AI reply to a user message delta_seconds = (msg.created_at - last_user_msg_time).total_seconds() # Sanity check: 0-300 seconds (ignores replies to very old messages) if 0 < delta_seconds < 600: # Increased to 10 mins as 5 might be too tight total_time += delta_seconds count += 1 # Reset to avoid double counting or incorrect pairing last_user_msg_time = None return round(total_time / count, 2) if count > 0 else 0.0 except Exception as e: logger.warning(f"Failed to calculate avg response time: {e}") return 0.0 def _calculate_funnel(self, leads: List[Lead], stages: List[SalesStage] = None) -> List[FunnelStageData]: """ Рассчитать распределение по этапам воронки. Использует динамические этапы из Playbook (SalesStage), если переданы. Иначе фолбэк на старую логику. """ total_leads = len(leads) result = [] if stages: # Dynamic Stages Logic stage_counts = {} # Helper to access stages safely stage_ids = [str(s.id) for s in stages] first_stage_id = stage_ids[0] if stage_ids else None second_stage_id = stage_ids[1] if len(stage_ids) > 1 else first_stage_id # Count leads by stage_id for lead in leads: if lead.current_stage_id: sid = str(lead.current_stage_id) stage_counts[sid] = stage_counts.get(sid, 0) + 1 else: # HEURISTIC: Map legacy status to dynamic stages if current_stage_id is None # This prevents "0" stats for existing leads status = str(lead.status.value if hasattr(lead.status, 'value') else lead.status) if status == "new" and first_stage_id: stage_counts[first_stage_id] = stage_counts.get(first_stage_id, 0) + 1 elif status in ["qualified", "contacted"] and second_stage_id: stage_counts[second_stage_id] = stage_counts.get(second_stage_id, 0) + 1 elif status == "in_progress" and second_stage_id: # Map in_progress to 2nd stage or middle stage_counts[second_stage_id] = stage_counts.get(second_stage_id, 0) + 1 else: stage_counts["uncategorized"] = stage_counts.get("uncategorized", 0) + 1 # 1. Unassigned / New (Leads with no stage) uncat_count = stage_counts.get("uncategorized", 0) if uncat_count > 0: result.append(FunnelStageData( stage="Не распределено", # Localize later or keep generic count=uncat_count, percentage=(uncat_count / total_leads * 100) if total_leads > 0 else 0.0 )) # 2. Configured Stages for stage in stages: sid = str(stage.id) count = stage_counts.get(sid, 0) # Funnel usually shows structure, so showing 0 is good. result.append(FunnelStageData( stage=stage.name, count=count, percentage=(count / total_leads * 100) if total_leads > 0 else 0.0 )) else: # Fallback Legacy Logic (Status Enum) status_counts = {} for lead in leads: # Handle standard Enum status = lead.status.value if hasattr(lead.status, 'value') else str(lead.status) status_counts[status] = status_counts.get(status, 0) + 1 # Mapping LeadStatus -> Frontend Keys funnel_map = [ ("new", "new"), ("qualified", "qualified"), ("in_progress", "negotiation"), ("closed_won", "closed_won"), ("closed_lost", "closed_lost") ] for enum_val, key in funnel_map: count = status_counts.get(enum_val, 0) if count > 0 or key == "new": result.append(FunnelStageData( stage=key, count=count, percentage=(count / total_leads * 100) if total_leads > 0 else 0.0 )) return result def _calculate_disc_distribution(self, leads: List[Lead]) -> List[DISCDistributionData]: """Рассчитать распределение по DISC психотипам.""" total_leads = len(leads) disc_counts = {} for lead in leads: psychotype = lead.psychotype.value if lead.psychotype else "unknown" disc_counts[psychotype] = disc_counts.get(psychotype, 0) + 1 return [ DISCDistributionData( psychotype=psychotype.capitalize(), count=count, percentage=(count / total_leads * 100) if total_leads > 0 else 0.0 ) for psychotype, count in disc_counts.items() ] def _extract_top_objections(self, leads: List[Lead]) -> List[ObjectionData]: """Извлечь топ-5 возражений из AI summaries (Deduplicated).""" objection_counts: Dict[str, int] = {} original_cases: Dict[str, str] = {} # normalized -> display for lead in leads: if lead.ai_summary_json and isinstance(lead.ai_summary_json, dict): objections_list = lead.ai_summary_json.get('objections', []) # Поддержка legacy формата (строка вместо массива) if isinstance(objections_list, str): objections_list = [p.strip() for p in re.split(r'[;,.\n]', objections_list) if p.strip()] elif not isinstance(objections_list, list): objections_list = [] # Подсчитать каждое возражение for objection in objections_list[:5]: if isinstance(objection, str) and len(objection) > 5: # Normalize: lowercase, remove special chars at end obj_normalized = objection.strip().lower().rstrip('.,;!')[:100] # Store first occurrence as display version (usually has correct casing) if obj_normalized not in original_cases: original_cases[obj_normalized] = objection.strip() objection_counts[obj_normalized] = objection_counts.get(obj_normalized, 0) + 1 # Топ-5 самых частых top_objections_list = sorted(objection_counts.items(), key=lambda x: x[1], reverse=True)[:5] total_objections = sum(objection_counts.values()) return [ ObjectionData( objection=original_cases.get(norm_obj, norm_obj).capitalize(), count=count, percentage=(count / total_objections * 100) if total_objections > 0 else 0.0 ) for norm_obj, count in top_objections_list ] def _calculate_lead_value_over_time(self, leads: List[Lead]) -> List[LeadValueOverTimeData]: """Рассчитать стоимость лидов по дням (последние 30 дней).""" lead_value_over_time = [] today = datetime.utcnow().date() for i in range(29, -1, -1): # Last 30 days target_date = today - timedelta(days=i) leads_on_date = [ lead for lead in leads if lead.created_at and lead.created_at.date() == target_date ] # Рассчитать стоимость за день day_value = 0.0 for lead in leads_on_date: if lead.budget: numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(lead.budget).replace(',', '')) if numbers: try: day_value += float(numbers[0]) except ValueError: pass lead_value_over_time.append( LeadValueOverTimeData( date=target_date.strftime('%Y-%m-%d'), value=day_value, count=len(leads_on_date) ) ) return lead_value_over_time def _calculate_channel_stats(self, leads: List[Lead], db_counts: Dict[str, int] = None) -> List[ChannelStatsData]: """Рассчитать распределение лидов по каналам (source).""" total_leads = len(leads) final_counts = {} # 1. Use DB counts (from conversations) if db_counts: for channel, count in db_counts.items(): if channel: final_counts[channel.lower()] = count # 2. Fill remaining with 'manual' or custom logic if needed counted = sum(final_counts.values()) remaining = total_leads - counted if remaining > 0: final_counts['manual'] = final_counts.get('manual', 0) + remaining # Normalize names normalized_counts = {} for source, count in final_counts.items(): display_name = source.capitalize().replace('_', ' ') if "whatsapp" in source.lower(): display_name = "WhatsApp" elif "telegram" in source.lower(): display_name = "Telegram" elif "instagram" in source.lower(): display_name = "Instagram" normalized_counts[display_name] = normalized_counts.get(display_name, 0) + count return [ ChannelStatsData( channel=channel, count=count, percentage=(count / total_leads * 100) if total_leads > 0 else 0.0 ) for channel, count in normalized_counts.items() ] async def _calculate_token_usage_24h(self, session: AsyncSession, tenant_id: UUID) -> int: """Суммарное количество токенов за последние 24 часа.""" since = datetime.utcnow() - timedelta(hours=24) stmt = select(func.sum(Message.prompt_tokens + Message.completion_tokens)).where( Message.tenant_id == tenant_id, Message.created_at >= since, Message.sender_type == "ai" ) result = await session.execute(stmt) return result.scalar() or 0 async def _calculate_ai_cost_24h(self, session: AsyncSession, tenant_id: UUID) -> float: """Примерная стоимость ИИ за 24 часа (на базе $15/1M токенов).""" tokens = await self._calculate_token_usage_24h(session, tenant_id) # Gemini 1.5 Flash approx: $0.075 / 1M input, $0.3 / 1M output # Blended rate as fallback if not tracking detailed types: $0.15 / 1M return round((tokens / 1_000_000) * 15.0, 4) async def _calculate_spam_hits_24h(self, session: AsyncSession, tenant_id: UUID) -> int: """Количество срабатываний защиты от спама.""" # Пока считаем по количеству лидов, у которых needs_attention=True и reason содержит 'spam' или 'kill switch' # Либо просто активные Kill Switches. # Для простоты: количество лидов с needs_attention=True в этом тенанте. stmt = select(func.count(Lead.id)).where( Lead.tenant_id == tenant_id, Lead.needs_attention == True, Lead.last_message_at >= datetime.utcnow() - timedelta(hours=24) ) result = await session.execute(stmt) return result.scalar() or 0 def _calculate_weighted_pipeline(self, leads: List[Lead]) -> float: """ Рассчитать взвешенный пайплайн (Weighted Pipeline Forecast). Сумма (Budget * Probability). Probability зависит от heat_level и status. """ forecast = 0.0 # Probabilities probs = { # By Status "closed": 1.0, "negotiation": 0.8, "qualified": 0.5, "contacted": 0.2, "new": 0.1, # By Heat Level (overwrite if status is generic) "hot": 0.7, "warm": 0.4, "cold": 0.1 } for lead in leads: budget = 0.0 # Extract budget if lead.budget: numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(lead.budget).replace(',', '')) if numbers: budget = float(numbers[0]) elif lead.ai_summary_json and isinstance(lead.ai_summary_json, dict): s_budget = lead.ai_summary_json.get('budget', '') numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(s_budget).replace(',', '')) if numbers: budget = float(numbers[0]) if budget > 0: # Determine probability prob = 0.1 # Default # Check status first if lead.status and lead.status.lower() in probs: prob = probs[lead.status.lower()] # Check Heat Level (refine) if lead.heat_level and lead.heat_level.value in probs: heat_prob = probs[lead.heat_level.value] # If heat prob is higher than status prob (e.g. "new" but "hot"), user heat if heat_prob > prob: prob = heat_prob forecast += budget * prob return round(forecast, 2) def _calculate_sales_velocity(self, leads: List[Lead]) -> float: """ Рассчитать среднюю скорость закрытия сделок (в днях). Lead Created -> Lead Closed. """ closed_leads = [ l for l in leads if l.status == "closed" and l.created_at ] if not closed_leads: return 0.0 total_days = 0.0 # Use updated_at as proxy for close time if available, else now for lead in closed_leads: close_date = lead.updated_at or datetime.utcnow() close_date = close_date.replace(tzinfo=None) create_date = lead.created_at.replace(tzinfo=None) days = (close_date - create_date).days if days < 0: days = 0 total_days += days return round(total_days / len(closed_leads), 1) def _calculate_ai_autonomy(self, leads: List[Lead]) -> float: """ Рассчитать уровень автономии AI. % лидов, где не требовалось вмешательство человека (needs_attention=False). Только для лидов, где был диалог. """ active_leads = [ l for l in leads if l.last_message_at # Была активность ] if not active_leads: return 100.0 # No leads = perfect autonomy theoretically autonomous_leads = sum(1 for l in active_leads if not l.needs_attention) return round((autonomous_leads / len(active_leads)) * 100, 1) def _calculate_revenue_influenced(self, leads: List[Lead]) -> float: """ Рассчитать 'Revenue Influenced by AI'. Сумма бюджетов всех Qualified + Hot лидов (где AI помог квалифицировать). """ influenced_value = 0.0 target_leads = [ l for l in leads if (l.status in ['qualified', 'negotiation', 'closed']) or (l.heat_level and l.heat_level.value == 'hot') ] for lead in target_leads: # Extract budget logic (duplicated for brevity, ideally helper method) budget = 0.0 if lead.budget: numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(lead.budget).replace(',', '')) if numbers: budget = float(numbers[0]) elif lead.ai_summary_json and isinstance(lead.ai_summary_json, dict): s_budget = lead.ai_summary_json.get('budget', '') numbers = re.findall(r'\d+(?:,\d{3})*(?:\.\d+)?', str(s_budget).replace(',', '')) if numbers: budget = float(numbers[0]) influenced_value += budget return round(influenced_value, 2) # Глобальная аналитика для админа (AI Pulse) async def get_admin_ai_pulse(self, session: AsyncSession) -> Dict[str, Any]: """Глобальная статистика работы ИИ для суперпользователя.""" since_24h = datetime.utcnow() - timedelta(hours=24) since_1h = datetime.utcnow() - timedelta(hours=1) # 1. Токены за 24ч (всего) token_stmt = select(func.sum(Message.prompt_tokens + Message.completion_tokens)).where( Message.created_at >= since_24h, Message.sender_type == "ai" ) total_tokens = (await session.execute(token_stmt)).scalar() or 0 # 2. Активные диалоги за 1ч active_stmt = select(func.count(func.distinct(Message.conversation_id))).where( Message.created_at >= since_1h ) active_convs = (await session.execute(active_stmt)).scalar() or 0 # 3. Количество Kill Switch за 24ч spam_stmt = select(func.count(Lead.id)).where( Lead.needs_attention == True, Lead.last_message_at >= since_24h ) total_spam = (await session.execute(spam_stmt)).scalar() or 0 return { "total_tokens_24h": total_tokens, "total_cost_usd": round((total_tokens / 1_000_000) * 15.0, 2), "active_conversations_1h": active_convs, "spam_alerts_24h": total_spam, "system_health": "stable" if active_convs > 0 else "idle" } # ============================================================================ # Singleton Instance # ============================================================================ _analytics_service: AnalyticsService = None def get_analytics_service() -> AnalyticsService: """Получить singleton instance аналитического сервиса.""" global _analytics_service if _analytics_service is None: _analytics_service = AnalyticsService() return _analytics_service