Spaces:
Running
Running
axeronis
feat(analytics): overhaul dashboard with revenue forecast, velocity and AI autonomy metrics
2ad4e23 Download backend/app/api/analytics.py from axeronis/microfunnel-api: direct link, hf CLI and curl.
- Browser
- Download file 7.49 kB
-
https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/analytics.py
- Command line
-
hf download hf://spaces/axeronis/microfunnel-api/backend/app/api/analytics.py
-
curl -L -o analytics.py https://huggingface.co/spaces/axeronis/microfunnel-api/resolve/main/backend/app/api/analytics.py
7.49 kB
| from fastapi import APIRouter, Depends, HTTPException, status | |
| from sqlmodel.ext.asyncio.session import AsyncSession | |
| from pydantic import BaseModel | |
| from typing import List | |
| from app.core.database import get_async_session | |
| from app.api.deps import get_current_user | |
| from app.models import User | |
| from app.services.analytics_service import get_analytics_service | |
| router = APIRouter(prefix="/analytics", tags=["Analytics"]) | |
| # ============================================================================ | |
| # Schemas | |
| # ============================================================================ | |
| class DashboardMetrics(BaseModel): | |
| total_leads: int | |
| hot_leads: int | |
| warm_leads: int | |
| cold_leads: int | |
| active_leads_24h: int # NEW: Active in last 24h | |
| conversion_rate: float | |
| pipeline_value: float | |
| avg_response_time_seconds: float # NEW: Avg AI response time | |
| total_bookings: int # NEW: Total appointments | |
| hours_saved: float | |
| money_saved: float | |
| # Business Value Metrics | |
| weighted_pipeline_value: float = 0.0 # NEW | |
| sales_velocity: float = 0.0 # NEW | |
| revenue_influenced: float = 0.0 # NEW | |
| # AI Performance Metrics | |
| ai_autonomy_rate: float = 0.0 # NEW | |
| # Percentage changes (vs previous period) | |
| total_leads_change: float | |
| conversion_rate_change: float | |
| pipeline_value_change: float | |
| # Cost metrics (Hidden in UI but kept in API) | |
| token_usage_24h: int | |
| ai_cost_usd: float | |
| spam_hits_24h: int | |
| class FunnelStage(BaseModel): | |
| stage: str | |
| count: int | |
| percentage: float | |
| class DISCData(BaseModel): | |
| psychotype: str | |
| count: int | |
| percentage: float | |
| class ObjectionData(BaseModel): | |
| objection: str | |
| count: int | |
| percentage: float | |
| class LeadValueOverTime(BaseModel): | |
| date: str | |
| value: float | |
| count: int | |
| class ChannelStats(BaseModel): | |
| channel: str | |
| count: int | |
| percentage: float | |
| class DashboardResponse(BaseModel): | |
| metrics: DashboardMetrics | |
| funnel: List[FunnelStage] | |
| disc_distribution: List[DISCData] | |
| top_objections: List[ObjectionData] | |
| lead_value_over_time: List[LeadValueOverTime] | |
| channel_stats: List[ChannelStats] | |
| # ============================================================================ | |
| # Endpoints | |
| # ============================================================================ | |
| async def get_dashboard_analytics( | |
| date_from: str = None, # YYYY-MM-DD format | |
| date_to: str = None, # YYYY-MM-DD format | |
| session: AsyncSession = Depends(get_async_session), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """ | |
| Получить комплексную аналитику дашборда для тенанта. | |
| РЕФАКТОРИНГ: Вся бизнес-логика перенесена в AnalyticsService. | |
| Route теперь отвечает ТОЛЬКО за HTTP-обработку. | |
| """ | |
| tenant_id = current_user.tenant_id | |
| # Получить сервис аналитики | |
| analytics_service = get_analytics_service() | |
| try: | |
| # Вызвать бизнес-логику из сервиса | |
| dashboard_data = await analytics_service.calculate_dashboard_metrics( | |
| session=session, | |
| tenant_id=tenant_id, | |
| date_from=date_from, | |
| date_to=date_to | |
| ) | |
| # Преобразовать внутренние модели в Pydantic response models | |
| return DashboardResponse( | |
| metrics=DashboardMetrics( | |
| total_leads=dashboard_data.metrics.total_leads, | |
| hot_leads=dashboard_data.metrics.hot_leads, | |
| warm_leads=dashboard_data.metrics.warm_leads, | |
| cold_leads=dashboard_data.metrics.cold_leads, | |
| active_leads_24h=dashboard_data.metrics.active_leads_24h, | |
| conversion_rate=dashboard_data.metrics.conversion_rate, | |
| pipeline_value=dashboard_data.metrics.pipeline_value, | |
| avg_response_time_seconds=dashboard_data.metrics.avg_response_time_seconds, | |
| total_bookings=dashboard_data.metrics.total_bookings, | |
| hours_saved=dashboard_data.metrics.hours_saved, | |
| money_saved=dashboard_data.metrics.money_saved, | |
| weighted_pipeline_value=dashboard_data.metrics.weighted_pipeline_value, | |
| sales_velocity=dashboard_data.metrics.sales_velocity, | |
| revenue_influenced=dashboard_data.metrics.revenue_influenced, | |
| ai_autonomy_rate=dashboard_data.metrics.ai_autonomy_rate, | |
| total_leads_change=dashboard_data.metrics.total_leads_change, | |
| conversion_rate_change=dashboard_data.metrics.conversion_rate_change, | |
| pipeline_value_change=dashboard_data.metrics.pipeline_value_change, | |
| token_usage_24h=dashboard_data.metrics.token_usage_24h, | |
| ai_cost_usd=dashboard_data.metrics.ai_cost_usd, | |
| spam_hits_24h=dashboard_data.metrics.spam_hits_24h | |
| ), | |
| funnel=[ | |
| FunnelStage( | |
| stage=stage.stage, | |
| count=stage.count, | |
| percentage=stage.percentage | |
| ) | |
| for stage in dashboard_data.funnel | |
| ], | |
| disc_distribution=[ | |
| DISCData( | |
| psychotype=disc.psychotype, | |
| count=disc.count, | |
| percentage=disc.percentage | |
| ) | |
| for disc in dashboard_data.disc_distribution | |
| ], | |
| top_objections=[ | |
| ObjectionData( | |
| objection=obj.objection, | |
| count=obj.count, | |
| percentage=obj.percentage | |
| ) | |
| for obj in dashboard_data.top_objections | |
| ], | |
| lead_value_over_time=[ | |
| LeadValueOverTime( | |
| date=val.date, | |
| value=val.value, | |
| count=val.count | |
| ) | |
| for val in dashboard_data.lead_value_over_time | |
| ], | |
| channel_stats=[ | |
| ChannelStats( | |
| channel=ch.channel, | |
| count=ch.count, | |
| percentage=ch.percentage | |
| ) | |
| for ch in dashboard_data.channel_stats | |
| ] | |
| ) | |
| except ValueError as e: | |
| # Тенант не найден | |
| raise HTTPException( | |
| status_code=status.HTTP_404_NOT_FOUND, | |
| detail=str(e) | |
| ) | |
| except Exception as e: | |
| # Другие ошибки будут обработаны глобальным handler | |
| raise | |
| async def get_admin_ai_pulse( | |
| session: AsyncSession = Depends(get_async_session), | |
| current_user: User = Depends(get_current_user) | |
| ): | |
| """ | |
| Глобальная статистика работы ИИ для суперпользователя. | |
| """ | |
| if not current_user.is_superuser: | |
| raise HTTPException( | |
| status_code=status.HTTP_403_FORBIDDEN, | |
| detail="Доступ только для суперпользователей" | |
| ) | |
| analytics_service = get_analytics_service() | |
| return await analytics_service.get_admin_ai_pulse(session) | |