test_analytics_api.py
10.8 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
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
import pytest
from datetime import datetime, timezone, timedelta
from app.model.analytics import (
ConversationLog, AnalyticsEvent, AnalyticsStatistic,
PageView, ScanEvent, GroupJoinEvent,
)
from app.model.agent import Agent, AgentPosition, AgentSkill, AgentStatus
from app.model.position_tag import PositionTag, OfficialTab
from app.model.skill import Skill
from app.model.agent_group import QrcodeChannel
from tests.conftest import TestingSessionLocal
@pytest.fixture
def db():
session = TestingSessionLocal()
session.query(GroupJoinEvent).delete()
session.query(ScanEvent).delete()
session.query(PageView).delete()
session.query(AnalyticsStatistic).delete()
session.query(AnalyticsEvent).delete()
session.query(ConversationLog).delete()
session.query(AgentSkill).delete()
session.query(AgentPosition).delete()
session.query(Agent).delete()
session.commit()
yield session
session.close()
def _insert_log(db, **kwargs):
defaults = {
"session_id": "sess_test",
"user_id": "emp_001",
"agent_id": 101,
"agent_name": "复盘Agent",
"query": "查询销售额",
"response": "销售额为150万",
"intent": "query-metric",
"entities": {"merchant_id": "store_A"},
"processing_time_ms": 1250,
"has_error": False,
}
defaults.update(kwargs)
log = ConversationLog(**defaults)
db.add(log)
db.commit()
db.refresh(log)
return log
class TestConversationLogQuery:
def test_list_no_filters(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, user_id="emp_001")
_insert_log(db, user_id="emp_002")
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(page=1, page_size=20)
assert total == 2
def test_filter_by_user_id(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, user_id="emp_001")
_insert_log(db, user_id="emp_002")
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(user_id="emp_001")
assert total == 1
assert items[0].user_id == "emp_001"
def test_filter_by_agent_id(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, agent_id=101)
_insert_log(db, agent_id=102)
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(agent_id=102)
assert total == 1
assert items[0].agent_id == 102
def test_filter_by_intent(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, intent="query-metric")
_insert_log(db, intent="query-detail")
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(intent_type="query-metric")
assert total == 1
def test_filter_by_has_error(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, has_error=False)
_insert_log(db, has_error=True)
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(has_error=True)
assert total == 1
assert items[0].has_error is True
def test_filter_by_time_range(self, db):
from app.service.analytics_service import AnalyticsService
now = datetime.now(timezone.utc)
_insert_log(db, query="old")
db.query(ConversationLog).filter(ConversationLog.query == "old").update(
{"created_at": now - timedelta(days=10)}
)
db.commit()
_insert_log(db, query="recent")
time_start = now - timedelta(days=1)
time_end = now + timedelta(days=1)
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(
time_start=time_start, time_end=time_end
)
assert total == 1
assert items[0].query == "recent"
def test_combined_filters(self, db):
from app.service.analytics_service import AnalyticsService
_insert_log(db, user_id="emp_001", agent_id=101, intent="query-metric")
_insert_log(db, user_id="emp_001", agent_id=101, intent="query-detail")
_insert_log(db, user_id="emp_002", agent_id=101, intent="query-metric")
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs(
user_id="emp_001", intent_type="query-metric"
)
assert total == 1
def test_empty_result(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
total, items = svc.list_conversation_logs()
assert total == 0
assert items == []
class TestAnalyticsEventUpload:
def test_single_event(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.upload_events([
{"event_type": "agent_called", "event_data": {"agent_id": 101}, "timestamp": None}
])
assert result.success is True
assert result.received_count == 1
count = db.query(AnalyticsEvent).count()
assert count == 1
def test_batch_events(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.upload_events([
{"event_type": "agent_called", "event_data": {"agent_id": 101}, "timestamp": None},
{"event_type": "routing_decision", "event_data": {"reason": "mention"}, "timestamp": None},
{"event_type": "session_created", "event_data": {}, "timestamp": None},
])
assert result.received_count == 3
count = db.query(AnalyticsEvent).count()
assert count == 3
def test_event_data_stored_as_json(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
svc.upload_events([
{"event_type": "agent_called", "event_data": {"agent_id": 101, "intent": "query-metric"}, "timestamp": None}
])
event = db.query(AnalyticsEvent).first()
assert event.event_data["agent_id"] == 101
assert event.event_data["intent"] == "query-metric"
class TestAnalyticsStatistics:
def test_statistics_with_preaggregated_data(self, db):
from app.service.analytics_service import AnalyticsService
today = datetime.now(timezone.utc).date()
stat = AnalyticsStatistic(
stat_date=today,
dimension="date",
dimension_value=today.isoformat(),
total_agent_calls=100,
total_sessions=30,
avg_session_turns=4.5,
intent_distribution=[{"intent": "query-metric", "count": 55, "percentage": 55.0}],
agent_call_ranking=[{"agent_id": 101, "agent_name": "复盘Agent", "call_count": 60}],
daily_trend=[{"date": today.isoformat(), "calls": 100, "sessions": 30}],
)
db.add(stat)
db.commit()
svc = AnalyticsService(db)
result = svc.get_statistics(date_range="last_7_days")
assert result.total_agent_calls == 100
assert result.total_sessions == 30
assert len(result.intent_distribution) == 1
def test_statistics_empty(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.get_statistics(date_range="last_7_days")
assert result.total_agent_calls == 0
assert result.total_sessions == 0
assert result.intent_distribution == []
class TestPageViewTracking:
def test_record_page_view(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.record_page_view(
page_type="活码列表页",
user_id="emp_001",
session_id="sess_xyz",
device_type="PC",
)
assert result.success is True
assert db.query(PageView).count() == 1
def test_page_view_fields_persisted(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
svc.record_page_view(page_type="数据分析页", user_id="emp_002", device_type="Mobile")
pv = db.query(PageView).first()
assert pv.page_type == "数据分析页"
assert pv.user_id == "emp_002"
assert pv.device_type == "Mobile"
class TestScanEventTracking:
def test_record_scan_event(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.record_scan_event(
qrcode_id=1,
channel_code="zdxs_store_sales_emp_12345",
customer_user_id="wo_external_123",
position_code="store_sales",
employee_id="emp_12345",
)
assert result.success is True
assert db.query(ScanEvent).count() == 1
def test_scan_event_fields(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
svc.record_scan_event(qrcode_id=5, channel_code="ch_test")
se = db.query(ScanEvent).first()
assert se.qrcode_id == 5
assert se.channel_code == "ch_test"
class TestGroupJoinEventTracking:
def test_record_group_join(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
result = svc.record_group_join_event(
group_id="group_abc",
customer_user_id="wo_external_123",
employee_count=2,
agent_count=2,
channel_code="zdxs_store_sales_emp_12345",
)
assert result.success is True
assert db.query(GroupJoinEvent).count() == 1
def test_group_join_fields(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
svc.record_group_join_event(group_id="g1", employee_count=3, agent_count=1)
gje = db.query(GroupJoinEvent).first()
assert gje.group_id == "g1"
assert gje.employee_count == 3
assert gje.agent_count == 1
class TestIntegrationScanToGroupJoin:
def test_scan_then_join_conversion(self, db):
from app.service.analytics_service import AnalyticsService
svc = AnalyticsService(db)
svc.record_scan_event(
qrcode_id=1,
channel_code="ch_001",
customer_user_id="cust_1",
)
svc.record_group_join_event(
group_id="grp_1",
customer_user_id="cust_1",
channel_code="ch_001",
)
scans = db.query(ScanEvent).filter(ScanEvent.customer_user_id == "cust_1").all()
joins = db.query(GroupJoinEvent).filter(GroupJoinEvent.customer_user_id == "cust_1").all()
assert len(scans) == 1
assert len(joins) == 1
assert scans[0].channel_code == joins[0].channel_code