import 'dart:convert'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:uuid/uuid.dart'; /// Simplified analytics client for M0 (report 13 + ticket 19): track events /// to backend POST /api/v1/events. Queue failures locally (shared_preferences, /// max 500), flush on successful upload or when full. Network errors are /// silently discarded (no retry as spec'd); privacy red-line enforced locally. class AnalyticsService { AnalyticsService({ required String apiBaseUrl, required this.getAccessToken, String? anonymousId, String? userId, }) : _apiBaseUrl = apiBaseUrl, _anonymousId = anonymousId ?? const Uuid().v4(), _userId = userId; static const _queueKey = 'patbond_analytics_queue'; static const _queueMaxSize = 500; static const _flushThreshold = 20; final String _apiBaseUrl; final String Function()? getAccessToken; String _anonymousId; String? _userId; final List> _pendingEvents = []; /// Sets userId after login (M0: no sessionId logic, simplified). void identify(String userId) { _userId = userId; } /// Clears userId on logout (anonymousId remains). void reset() { _userId = null; } /// Tracks event (never throws, never awaits network). Props are validated /// for privacy red-line patterns locally before queuing. Future trackEvent( String eventName, [ Map? props, ]) async { try { if (props != null && _containsForbiddenField(props)) { debugPrint('Analytics: event $eventName rejected (forbidden field)'); return; } final event = { 'eventId': const Uuid().v4(), 'eventName': eventName, 'eventVersion': 1, 'anonymousId': _anonymousId, if (_userId != null) 'userId': _userId, 'sessionId': const Uuid().v4(), // Simplified: unique per event (M0) 'clientTs': DateTime.now().toUtc().toIso8601String(), 'appVersion': '1.0.0+1', // TODO: read from package_info_plus 'platform': Platform.isAndroid ? 'android' : 'ios', 'osVersion': Platform.isAndroid ? 'android-14' : 'ios-17', // TODO: device_info_plus if (props != null && props.isNotEmpty) 'props': props, }; _pendingEvents.add(event); if (_pendingEvents.length >= _flushThreshold) { await _flush(); } } catch (error) { debugPrint('Analytics track failed: $error'); } } Future _flush() async { if (_pendingEvents.isEmpty) return; final batch = List>.from(_pendingEvents); _pendingEvents.clear(); try { await _upload(batch); } catch (error) { debugPrint('Analytics upload failed, discarding batch: $error'); } } Future _upload(List> events) async { final token = getAccessToken?.call(); final headers = { 'Content-Type': 'application/json', if (token != null) 'Authorization': 'Bearer $token', }; final request = await HttpClient().postUrl(Uri.parse('$_apiBaseUrl/api/v1/events')) ..headers.contentType = ContentType.json; if (token != null) { request.headers.add('Authorization', 'Bearer $token'); } request.add(utf8.encode(jsonEncode({'events': events}))); final response = await request.close(); if (response.statusCode != 202) { throw Exception('Upload failed with ${response.statusCode}'); } } bool _containsForbiddenField(Map props) { final pattern = RegExp( r'(?i).*(password|token|secret|phone|mobile|email|credential|idfa|gaid).*', ); return props.keys.any((key) => pattern.hasMatch(key)); } }