analytics_service.py 6.95 KB
from __future__ import annotations

from datetime import datetime, timezone, timedelta
from typing import Any, Optional

from sqlalchemy import and_
from sqlalchemy.orm import Session as OrmSession

from app.model.analytics import (
    ConversationLog,
    AnalyticsEvent,
    AnalyticsStatistic,
    PageView,
    ScanEvent,
    GroupJoinEvent,
)
from app.schema.analytics import (
    AnalyticsEventResponse,
    AnalyticsStatisticsResponse,
    IntentDistributionItem,
    AgentCallRankingItem,
    DailyTrendItem,
    PageViewResponse,
    ScanEventResponse,
    GroupJoinEventResponse,
)


class AnalyticsService:
    def __init__(self, db: OrmSession) -> None:
        self.db = db

    def list_conversation_logs(
        self,
        page: int = 1,
        page_size: int = 20,
        user_id: Optional[str] = None,
        agent_id: Optional[int] = None,
        intent_type: Optional[str] = None,
        time_start: Optional[datetime] = None,
        time_end: Optional[datetime] = None,
        has_error: Optional[bool] = None,
    ) -> tuple[int, list[ConversationLog]]:
        query = self.db.query(ConversationLog)

        if user_id is not None:
            query = query.filter(ConversationLog.user_id == user_id)
        if agent_id is not None:
            query = query.filter(ConversationLog.agent_id == agent_id)
        if intent_type is not None:
            query = query.filter(ConversationLog.intent == intent_type)
        if time_start is not None:
            query = query.filter(ConversationLog.created_at >= time_start)
        if time_end is not None:
            query = query.filter(ConversationLog.created_at <= time_end)
        if has_error is not None:
            query = query.filter(ConversationLog.has_error == has_error)

        total = query.count()
        items = query.order_by(ConversationLog.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
        return total, items

    def upload_events(self, events: list[dict[str, Any]]) -> AnalyticsEventResponse:
        for ev in events:
            row = AnalyticsEvent(
                event_type=ev["event_type"],
                event_data=ev.get("event_data"),
            )
            self.db.add(row)
        self.db.commit()
        return AnalyticsEventResponse(success=True, received_count=len(events))

    def get_statistics(
        self,
        date_range: str = "last_7_days",
        group_by: Optional[str] = None,
    ) -> AnalyticsStatisticsResponse:
        if date_range == "last_7_days":
            start = datetime.now(timezone.utc).date() - timedelta(days=7)
        elif date_range == "last_30_days":
            start = datetime.now(timezone.utc).date() - timedelta(days=30)
        else:
            start = datetime.now(timezone.utc).date() - timedelta(days=7)

        stats = self.db.query(AnalyticsStatistic).filter(
            AnalyticsStatistic.stat_date >= start
        ).all()

        if not stats:
            return AnalyticsStatisticsResponse(
                total_agent_calls=0,
                total_sessions=0,
                avg_session_turns=0.0,
                intent_distribution=[],
                agent_call_ranking=[],
                daily_trend=[],
            )

        total_calls = sum(s.total_agent_calls for s in stats)
        total_sessions = sum(s.total_sessions for s in stats)
        avg_turns = sum(float(s.avg_session_turns) for s in stats) / len(stats) if stats else 0.0

        intent_map: dict[str, int] = {}
        for s in stats:
            if s.intent_distribution:
                for item in s.intent_distribution:
                    intent_map[item["intent"]] = intent_map.get(item["intent"], 0) + item["count"]

        total_intent = sum(intent_map.values()) or 1
        intent_dist = [
            IntentDistributionItem(intent=k, count=v, percentage=round(v / total_intent * 100, 1))
            for k, v in sorted(intent_map.items(), key=lambda x: -x[1])
        ]

        agent_map: dict[int, dict] = {}
        for s in stats:
            if s.agent_call_ranking:
                for item in s.agent_call_ranking:
                    aid = item["agent_id"]
                    if aid not in agent_map:
                        agent_map[aid] = {"agent_id": aid, "agent_name": item["agent_name"], "call_count": 0}
                    agent_map[aid]["call_count"] += item["call_count"]

        agent_ranking = sorted(agent_map.values(), key=lambda x: -x["call_count"])
        agent_ranking = [AgentCallRankingItem(**a) for a in agent_ranking]

        trend_map: dict[str, dict] = {}
        for s in stats:
            if s.daily_trend:
                for item in s.daily_trend:
                    d = item["date"]
                    if d not in trend_map:
                        trend_map[d] = {"date": d, "calls": 0, "sessions": 0}
                    trend_map[d]["calls"] += item["calls"]
                    trend_map[d]["sessions"] += item["sessions"]

        daily_trend = [DailyTrendItem(**t) for t in sorted(trend_map.values(), key=lambda x: x["date"])]

        return AnalyticsStatisticsResponse(
            total_agent_calls=total_calls,
            total_sessions=total_sessions,
            avg_session_turns=round(avg_turns, 2),
            intent_distribution=intent_dist,
            agent_call_ranking=agent_ranking,
            daily_trend=daily_trend,
        )

    def record_page_view(
        self,
        page_type: str,
        user_id: Optional[str] = None,
        session_id: Optional[str] = None,
        device_type: Optional[str] = None,
    ) -> PageViewResponse:
        pv = PageView(
            page_type=page_type,
            user_id=user_id,
            session_id=session_id,
            device_type=device_type,
        )
        self.db.add(pv)
        self.db.commit()
        return PageViewResponse(success=True)

    def record_scan_event(
        self,
        qrcode_id: Optional[int] = None,
        channel_code: Optional[str] = None,
        customer_user_id: Optional[str] = None,
        position_code: Optional[str] = None,
        employee_id: Optional[str] = None,
    ) -> ScanEventResponse:
        se = ScanEvent(
            qrcode_id=qrcode_id,
            channel_code=channel_code,
            customer_user_id=customer_user_id,
            position_code=position_code,
            employee_id=employee_id,
        )
        self.db.add(se)
        self.db.commit()
        return ScanEventResponse(success=True)

    def record_group_join_event(
        self,
        group_id: Optional[str] = None,
        customer_user_id: Optional[str] = None,
        employee_count: int = 0,
        agent_count: int = 0,
        channel_code: Optional[str] = None,
    ) -> GroupJoinEventResponse:
        gje = GroupJoinEvent(
            group_id=group_id,
            customer_user_id=customer_user_id,
            employee_count=employee_count,
            agent_count=agent_count,
            channel_code=channel_code,
        )
        self.db.add(gje)
        self.db.commit()
        return GroupJoinEventResponse(success=True)