part of 'data_service.dart'; extension DataServiceTrips on DataService { Future fetchTripDetails() async { _isTripDetailsLoading = true; try { final json = await api.get('/trips/legs-and-stats'); if (json is List) { final tripMap = json.map((e) => TripDetail.fromJson(e)).toList(); _tripDetails = [...tripMap]..sort((a, b) => b.id.compareTo(a.id)); } else { _tripDetails = []; } } catch (e) { debugPrint('Failed to fetch trip_map: $e'); _tripDetails = []; } finally { _isTripDetailsLoading = false; _notifyAsync(); } } Future> fetchTripLocoStats(int tripId) async { try { final json = await api.get('/trips/stats/$tripId'); return _parseTripLocoStats(json); } catch (e) { debugPrint('Failed to fetch trip loco stats: $e'); return []; } } List _parseTripLocoStats(dynamic json) { List? list; if (json is List) { list = json.expand((e) => e is List ? e : [e]).toList(); } else if (json is Map) { for (final key in ['locos', 'stats', 'data', 'trip_locos']) { final candidate = json[key]; if (candidate is List) { list = candidate.expand((e) => e is List ? e : [e]).toList(); break; } } } if (list == null) return []; return list .whereType>() .map((e) => TripLocoStat.fromJson(e)) .toList(); } Future fetchTrips() async { try { final json = await api.get('/trips/mileage'); Iterable? raw; if (json is List) { raw = json; } else if (json is Map) { for (final key in ['trips', 'trip_data', 'data']) { final value = json[key]; if (value is List) { raw = value; break; } } } if (raw != null) { final tripMap = raw .whereType>() .map((e) => TripSummary.fromJson(e)) .toList(); _tripList = [...tripMap]..sort((a, b) => b.tripId.compareTo(a.tripId)); } else { debugPrint('Unexpected trip list response: $json'); _tripList = []; } } catch (e) { debugPrint('Failed to fetch trip list: $e'); _tripList = []; } finally { _notifyAsync(); } } Future fetchTripOptions() async { try { final json = await api.get('/trips'); Iterable? raw; if (json is List) { raw = json; } else if (json is Map) { for (final key in ['trips', 'trip_data', 'data']) { final value = json[key]; if (value is List) { raw = value; break; } } } if (raw != null) { final tripMap = raw .whereType>() .map((e) => TripSummary.fromJson(e)) .toList(); _tripList = [...tripMap]..sort((a, b) => b.tripId.compareTo(a.tripId)); } else { debugPrint('Unexpected trip list response: $json'); _tripList = []; } } catch (e) { debugPrint('Failed to fetch trip list: $e'); _tripList = []; } finally { _notifyAsync(); } } void upsertTripSummary(TripSummary trip) { final existingIndex = _tripList.indexWhere((element) => element.tripId == trip.tripId); if (existingIndex >= 0) { _tripList[existingIndex] = trip; } else { _tripList = [trip, ..._tripList]; } _tripList.sort((a, b) => b.tripId.compareTo(a.tripId)); _notifyAsync(); } }