Skip to content

Commit 46e4ff1

Browse files
committed
fix(analytics): correct total calculation for Mixpanel segmentations
- Remove unnecessary fallback to first value in segmentation data - Implement correct logic to fetch total value without 'unit' parameter - Update API call to use segmentation endpoint for total calculation - Add error handling for empty response values
1 parent 97ab01e commit 46e4ff1

File tree

1 file changed

+27
-8
lines changed

1 file changed

+27
-8
lines changed

lib/src/services/analytics/mixpanel_data_client.dart

Lines changed: 27 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,7 @@ class MixpanelDataClient implements AnalyticsReportingClient {
109109

110110
final dataPoints = <DataPoint>[];
111111
final series = segmentationData.series;
112-
final values =
113-
segmentationData.values[metricName] ??
114-
segmentationData.values.values.firstOrNull ??
115-
[];
112+
final values = segmentationData.values[metricName] ?? [];
116113

117114
for (var i = 0; i < series.length; i++) {
118115
dataPoints.add(
@@ -140,15 +137,37 @@ class MixpanelDataClient implements AnalyticsReportingClient {
140137
);
141138
}
142139
if (metricName == 'activeUsers') {
143-
// Mixpanel uses a special name for active users.
144140
metricName = r'$active';
145141
}
146142

147143
_log.info('Fetching total for metric "$metricName" from Mixpanel.');
148-
final timeSeries = await getTimeSeries(query, startDate, endDate);
149-
if (timeSeries.isEmpty) return 0;
150144

151-
return timeSeries.map((dp) => dp.value).reduce((a, b) => a + b);
145+
// To get a single total, we call the segmentation endpoint *without* the 'unit' parameter.
146+
final queryParameters = {
147+
'project_id': _projectId,
148+
'event': metricName,
149+
'from_date': DateFormat('yyyy-MM-dd').format(startDate),
150+
'to_date': DateFormat('yyyy-MM-dd').format(endDate),
151+
};
152+
153+
final response = await _httpClient.get<Map<String, dynamic>>(
154+
'/segmentation',
155+
queryParameters: queryParameters,
156+
);
157+
158+
final segmentationData =
159+
MixpanelResponse<MixpanelSegmentationData>.fromJson(
160+
response,
161+
(json) =>
162+
MixpanelSegmentationData.fromJson(json as Map<String, dynamic>),
163+
).data;
164+
165+
// The response for a total value has a single entry in the 'values' map.
166+
if (segmentationData.values.values.isEmpty ||
167+
segmentationData.values.values.first.isEmpty) {
168+
return 0;
169+
}
170+
return segmentationData.values.values.first.first;
152171
}
153172

154173
@override

0 commit comments

Comments
 (0)