analytics_service.py
6.95 KB
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
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)