feat(wip): Update entities and adopt a proper repository workflow for trip "obtention"
This commit is contained in:
@@ -1,5 +0,0 @@
|
||||
import 'package:anyway/domain/entities/landmark.dart';
|
||||
|
||||
abstract class TripRemoteDataSource {
|
||||
Future<List<Landmark>> fetchLandmarks();
|
||||
}
|
||||
142
frontend/lib/data/datasources/trip_remote_datasource.dart
Normal file
142
frontend/lib/data/datasources/trip_remote_datasource.dart
Normal file
@@ -0,0 +1,142 @@
|
||||
import 'dart:convert';
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
|
||||
abstract class TripRemoteDataSource {
|
||||
/// Fetch available landmarks for the provided preferences/start payload.
|
||||
Future<List<Map<String, dynamic>>> fetchLandmarks(Map<String, dynamic> body);
|
||||
|
||||
/// Create a new trip using the optimizer payload (that includes landmarks).
|
||||
Future<Map<String, dynamic>> createTrip(Map<String, dynamic> body);
|
||||
|
||||
/// Fetch an existing trip by UUID
|
||||
Future<Map<String, dynamic>> fetchTrip(String uuid);
|
||||
}
|
||||
|
||||
class TripRemoteDataSourceImpl implements TripRemoteDataSource {
|
||||
final Dio dio;
|
||||
|
||||
TripRemoteDataSourceImpl({required this.dio});
|
||||
|
||||
@override
|
||||
Future<List<Map<String, dynamic>>> fetchLandmarks(Map<String, dynamic> body) async {
|
||||
final response = await dio.post('/get/landmarks', data: body);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Server error fetching landmarks: ${response.statusCode}');
|
||||
}
|
||||
|
||||
if (response.data is! List) {
|
||||
throw Exception('Unexpected landmarks response format');
|
||||
}
|
||||
|
||||
return _normalizeLandmarks(List<dynamic>.from(response.data as List));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> createTrip(Map<String, dynamic> body) async {
|
||||
log('Creating trip with body: $body');
|
||||
// convert body to actual json
|
||||
String bodyJson = jsonEncode(body);
|
||||
log('Trip request JSON: $bodyJson');
|
||||
final response = await dio.post('/optimize/trip', data: body);
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Server error: ${response.statusCode}');
|
||||
}
|
||||
|
||||
if (response.data is! Map<String, dynamic>) {
|
||||
throw Exception('Unexpected response format');
|
||||
}
|
||||
|
||||
final Map<String, dynamic> json = Map<String, dynamic>.from(response.data as Map);
|
||||
|
||||
_ensureLandmarks(json);
|
||||
if (json.containsKey('landmarks') && json['landmarks'] is List) {
|
||||
return json;
|
||||
}
|
||||
|
||||
final String? firstUuid = json['first_landmark_uuid'] as String?;
|
||||
if (firstUuid == null) {
|
||||
return json;
|
||||
}
|
||||
|
||||
final List<Map<String, dynamic>> landmarks = [];
|
||||
String? next = firstUuid;
|
||||
while (next != null) {
|
||||
final lm = await _fetchLandmarkByUuid(next);
|
||||
landmarks.add(lm);
|
||||
final dynamic nxt = lm['next_uuid'];
|
||||
next = (nxt is String) ? nxt : null;
|
||||
}
|
||||
|
||||
json['landmarks'] = landmarks;
|
||||
return json;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> fetchTrip(String uuid) async {
|
||||
final response = await dio.get('/trip/$uuid');
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Server error: ${response.statusCode}');
|
||||
}
|
||||
if (response.data is! Map<String, dynamic>) {
|
||||
throw Exception('Unexpected response format');
|
||||
}
|
||||
|
||||
final Map<String, dynamic> json = Map<String, dynamic>.from(response.data as Map);
|
||||
// Normalize same as createTrip: if trip contains first_landmark_uuid, expand chain
|
||||
if (json.containsKey('landmarks') && json['landmarks'] is List) {
|
||||
_ensureLandmarks(json);
|
||||
return json;
|
||||
}
|
||||
|
||||
final String? firstUuid = json['first_landmark_uuid'] as String?;
|
||||
if (firstUuid == null) return json;
|
||||
|
||||
final List<Map<String, dynamic>> landmarks = [];
|
||||
String? next = firstUuid;
|
||||
while (next != null) {
|
||||
final lm = await _fetchLandmarkByUuid(next);
|
||||
landmarks.add(lm);
|
||||
final dynamic nxt = lm['next_uuid'];
|
||||
next = (nxt is String) ? nxt : null;
|
||||
}
|
||||
|
||||
json['landmarks'] = landmarks;
|
||||
return json;
|
||||
}
|
||||
|
||||
// Fetch a single landmark by uuid via the /landmark/{landmark_uuid} endpoint
|
||||
Future<Map<String, dynamic>> _fetchLandmarkByUuid(String uuid) async {
|
||||
final response = await dio.get('/landmark/$uuid');
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Failed to fetch landmark $uuid: ${response.statusCode}');
|
||||
}
|
||||
if (response.data is! Map<String, dynamic>) {
|
||||
throw Exception('Unexpected landmark response format');
|
||||
}
|
||||
return _normalizeLandmark(Map<String, dynamic>.from(response.data as Map));
|
||||
}
|
||||
|
||||
static void _ensureLandmarks(Map<String, dynamic> json) {
|
||||
final raw = json['landmarks'];
|
||||
if (raw is List) {
|
||||
json['landmarks'] = _normalizeLandmarks(raw);
|
||||
}
|
||||
}
|
||||
|
||||
static List<Map<String, dynamic>> _normalizeLandmarks(List<dynamic> rawList) {
|
||||
return rawList
|
||||
.map((item) => _normalizeLandmark(Map<String, dynamic>.from(item as Map)))
|
||||
.toList();
|
||||
}
|
||||
|
||||
static Map<String, dynamic> _normalizeLandmark(Map<String, dynamic> source) {
|
||||
final normalized = Map<String, dynamic>.from(source);
|
||||
final typeValue = normalized['type'];
|
||||
if (typeValue is String) {
|
||||
normalized['type'] = {'type': typeValue};
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
// TODO - I have the feeling this file is outdated and not used anymore
|
||||
import 'package:anyway/domain/entities/landmark.dart';
|
||||
import 'package:anyway/domain/entities/landmark_description.dart';
|
||||
import 'package:anyway/domain/entities/landmark_type.dart';
|
||||
@@ -16,6 +17,8 @@ abstract class LandmarkModel with _$LandmarkModel {
|
||||
required String description,
|
||||
}) = _LandmarkModel;
|
||||
|
||||
const LandmarkModel._();
|
||||
|
||||
factory LandmarkModel.fromJson(Map<String, dynamic> json) => _$LandmarkModelFromJson(json);
|
||||
|
||||
Landmark toEntity() => Landmark(
|
||||
@@ -24,7 +27,6 @@ abstract class LandmarkModel with _$LandmarkModel {
|
||||
location: location,
|
||||
type: LandmarkType(type: LandmarkTypeEnum.values.firstWhere((e) => e.value == type)),
|
||||
isSecondary: isSecondary,
|
||||
// TODO - try to set tags
|
||||
description: LandmarkDescription(description: description, tags: [])
|
||||
description: LandmarkDescription(description: description, tags: []),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,71 +14,47 @@ T _$identity<T>(T value) => value;
|
||||
|
||||
/// @nodoc
|
||||
mixin _$LandmarkModel {
|
||||
String get uuid;
|
||||
String get name;
|
||||
List<double> get location;
|
||||
String get type;
|
||||
bool get isSecondary;
|
||||
String get description;
|
||||
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$LandmarkModelCopyWith<LandmarkModel> get copyWith =>
|
||||
_$LandmarkModelCopyWithImpl<LandmarkModel>(
|
||||
this as LandmarkModel, _$identity);
|
||||
String get uuid; String get name; List<double> get location; String get type; bool get isSecondary; String get description;
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
$LandmarkModelCopyWith<LandmarkModel> get copyWith => _$LandmarkModelCopyWithImpl<LandmarkModel>(this as LandmarkModel, _$identity);
|
||||
|
||||
/// Serializes this LandmarkModel to a JSON map.
|
||||
Map<String, dynamic> toJson();
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is LandmarkModel &&
|
||||
(identical(other.uuid, uuid) || other.uuid == uuid) &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
const DeepCollectionEquality().equals(other.location, location) &&
|
||||
(identical(other.type, type) || other.type == type) &&
|
||||
(identical(other.isSecondary, isSecondary) ||
|
||||
other.isSecondary == isSecondary) &&
|
||||
(identical(other.description, description) ||
|
||||
other.description == description));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType,
|
||||
uuid,
|
||||
name,
|
||||
const DeepCollectionEquality().hash(location),
|
||||
type,
|
||||
isSecondary,
|
||||
description);
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is LandmarkModel&&(identical(other.uuid, uuid) || other.uuid == uuid)&&(identical(other.name, name) || other.name == name)&&const DeepCollectionEquality().equals(other.location, location)&&(identical(other.type, type) || other.type == type)&&(identical(other.isSecondary, isSecondary) || other.isSecondary == isSecondary)&&(identical(other.description, description) || other.description == description));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,uuid,name,const DeepCollectionEquality().hash(location),type,isSecondary,description);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'LandmarkModel(uuid: $uuid, name: $name, location: $location, type: $type, isSecondary: $isSecondary, description: $description)';
|
||||
}
|
||||
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'LandmarkModel(uuid: $uuid, name: $name, location: $location, type: $type, isSecondary: $isSecondary, description: $description)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class $LandmarkModelCopyWith<$Res> {
|
||||
factory $LandmarkModelCopyWith(
|
||||
LandmarkModel value, $Res Function(LandmarkModel) _then) =
|
||||
_$LandmarkModelCopyWithImpl;
|
||||
@useResult
|
||||
$Res call(
|
||||
{String uuid,
|
||||
String name,
|
||||
List<double> location,
|
||||
String type,
|
||||
bool isSecondary,
|
||||
String description});
|
||||
}
|
||||
abstract mixin class $LandmarkModelCopyWith<$Res> {
|
||||
factory $LandmarkModelCopyWith(LandmarkModel value, $Res Function(LandmarkModel) _then) = _$LandmarkModelCopyWithImpl;
|
||||
@useResult
|
||||
$Res call({
|
||||
String uuid, String name, List<double> location, String type, bool isSecondary, String description
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class _$LandmarkModelCopyWithImpl<$Res>
|
||||
implements $LandmarkModelCopyWith<$Res> {
|
||||
@@ -87,310 +63,213 @@ class _$LandmarkModelCopyWithImpl<$Res>
|
||||
final LandmarkModel _self;
|
||||
final $Res Function(LandmarkModel) _then;
|
||||
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline')
|
||||
@override
|
||||
$Res call({
|
||||
Object? uuid = null,
|
||||
Object? name = null,
|
||||
Object? location = null,
|
||||
Object? type = null,
|
||||
Object? isSecondary = null,
|
||||
Object? description = null,
|
||||
}) {
|
||||
return _then(_self.copyWith(
|
||||
uuid: null == uuid
|
||||
? _self.uuid
|
||||
: uuid // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
location: null == location
|
||||
? _self.location
|
||||
: location // ignore: cast_nullable_to_non_nullable
|
||||
as List<double>,
|
||||
type: null == type
|
||||
? _self.type
|
||||
: type // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isSecondary: null == isSecondary
|
||||
? _self.isSecondary
|
||||
: isSecondary // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
description: null == description
|
||||
? _self.description
|
||||
: description // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@pragma('vm:prefer-inline') @override $Res call({Object? uuid = null,Object? name = null,Object? location = null,Object? type = null,Object? isSecondary = null,Object? description = null,}) {
|
||||
return _then(_self.copyWith(
|
||||
uuid: null == uuid ? _self.uuid : uuid // ignore: cast_nullable_to_non_nullable
|
||||
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
|
||||
as String,location: null == location ? _self.location : location // ignore: cast_nullable_to_non_nullable
|
||||
as List<double>,type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
|
||||
as String,isSecondary: null == isSecondary ? _self.isSecondary : isSecondary // ignore: cast_nullable_to_non_nullable
|
||||
as bool,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// Adds pattern-matching-related methods to [LandmarkModel].
|
||||
extension LandmarkModelPatterns on LandmarkModel {
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
/// A variant of `map` that fallback to returning `orElse`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeMap<TResult extends Object?>(
|
||||
TResult Function(_LandmarkModel value)? $default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _LandmarkModel value)? $default,{required TResult orElse(),}){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return orElse();
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// Callbacks receives the raw object, upcasted.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case final Subclass2 value:
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult map<TResult extends Object?>(
|
||||
TResult Function(_LandmarkModel value) $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel():
|
||||
return $default(_that);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _LandmarkModel value) $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel():
|
||||
return $default(_that);case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
}
|
||||
}
|
||||
/// A variant of `map` that fallback to returning `null`.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case final Subclass value:
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? mapOrNull<TResult extends Object?>(
|
||||
TResult? Function(_LandmarkModel value)? $default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _LandmarkModel value)? $default,){
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that);case _:
|
||||
return null;
|
||||
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to an `orElse` callback.
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return orElse();
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult maybeWhen<TResult extends Object?>(
|
||||
TResult Function(String uuid, String name, List<double> location,
|
||||
String type, bool isSecondary, String description)?
|
||||
$default, {
|
||||
required TResult orElse(),
|
||||
}) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that.uuid, _that.name, _that.location, _that.type,
|
||||
_that.isSecondary, _that.description);
|
||||
case _:
|
||||
return orElse();
|
||||
}
|
||||
}
|
||||
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String uuid, String name, List<double> location, String type, bool isSecondary, String description)? $default,{required TResult orElse(),}) {final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that.uuid,_that.name,_that.location,_that.type,_that.isSecondary,_that.description);case _:
|
||||
return orElse();
|
||||
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
}
|
||||
}
|
||||
/// A `switch`-like method, using callbacks.
|
||||
///
|
||||
/// As opposed to `map`, this offers destructuring.
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case Subclass2(:final field2):
|
||||
/// return ...;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult when<TResult extends Object?>(
|
||||
TResult Function(String uuid, String name, List<double> location,
|
||||
String type, bool isSecondary, String description)
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel():
|
||||
return $default(_that.uuid, _that.name, _that.location, _that.type,
|
||||
_that.isSecondary, _that.description);
|
||||
case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
}
|
||||
}
|
||||
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String uuid, String name, List<double> location, String type, bool isSecondary, String description) $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel():
|
||||
return $default(_that.uuid,_that.name,_that.location,_that.type,_that.isSecondary,_that.description);case _:
|
||||
throw StateError('Unexpected subclass');
|
||||
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
}
|
||||
}
|
||||
/// A variant of `when` that fallback to returning `null`
|
||||
///
|
||||
/// It is equivalent to doing:
|
||||
/// ```dart
|
||||
/// switch (sealedClass) {
|
||||
/// case Subclass(:final field):
|
||||
/// return ...;
|
||||
/// case _:
|
||||
/// return null;
|
||||
/// }
|
||||
/// ```
|
||||
|
||||
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String uuid, String name, List<double> location, String type, bool isSecondary, String description)? $default,) {final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that.uuid,_that.name,_that.location,_that.type,_that.isSecondary,_that.description);case _:
|
||||
return null;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@optionalTypeArgs
|
||||
TResult? whenOrNull<TResult extends Object?>(
|
||||
TResult? Function(String uuid, String name, List<double> location,
|
||||
String type, bool isSecondary, String description)?
|
||||
$default,
|
||||
) {
|
||||
final _that = this;
|
||||
switch (_that) {
|
||||
case _LandmarkModel() when $default != null:
|
||||
return $default(_that.uuid, _that.name, _that.location, _that.type,
|
||||
_that.isSecondary, _that.description);
|
||||
case _:
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
@JsonSerializable()
|
||||
class _LandmarkModel implements LandmarkModel {
|
||||
const _LandmarkModel(
|
||||
{required this.uuid,
|
||||
required this.name,
|
||||
required final List<double> location,
|
||||
required this.type,
|
||||
required this.isSecondary,
|
||||
required this.description})
|
||||
: _location = location;
|
||||
factory _LandmarkModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$LandmarkModelFromJson(json);
|
||||
|
||||
@override
|
||||
final String uuid;
|
||||
@override
|
||||
final String name;
|
||||
final List<double> _location;
|
||||
@override
|
||||
List<double> get location {
|
||||
if (_location is EqualUnmodifiableListView) return _location;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_location);
|
||||
}
|
||||
class _LandmarkModel extends LandmarkModel {
|
||||
const _LandmarkModel({required this.uuid, required this.name, required final List<double> location, required this.type, required this.isSecondary, required this.description}): _location = location,super._();
|
||||
factory _LandmarkModel.fromJson(Map<String, dynamic> json) => _$LandmarkModelFromJson(json);
|
||||
|
||||
@override
|
||||
final String type;
|
||||
@override
|
||||
final bool isSecondary;
|
||||
@override
|
||||
final String description;
|
||||
@override final String uuid;
|
||||
@override final String name;
|
||||
final List<double> _location;
|
||||
@override List<double> get location {
|
||||
if (_location is EqualUnmodifiableListView) return _location;
|
||||
// ignore: implicit_dynamic_type
|
||||
return EqualUnmodifiableListView(_location);
|
||||
}
|
||||
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$LandmarkModelCopyWith<_LandmarkModel> get copyWith =>
|
||||
__$LandmarkModelCopyWithImpl<_LandmarkModel>(this, _$identity);
|
||||
@override final String type;
|
||||
@override final bool isSecondary;
|
||||
@override final String description;
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$LandmarkModelToJson(
|
||||
this,
|
||||
);
|
||||
}
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@pragma('vm:prefer-inline')
|
||||
_$LandmarkModelCopyWith<_LandmarkModel> get copyWith => __$LandmarkModelCopyWithImpl<_LandmarkModel>(this, _$identity);
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) ||
|
||||
(other.runtimeType == runtimeType &&
|
||||
other is _LandmarkModel &&
|
||||
(identical(other.uuid, uuid) || other.uuid == uuid) &&
|
||||
(identical(other.name, name) || other.name == name) &&
|
||||
const DeepCollectionEquality().equals(other._location, _location) &&
|
||||
(identical(other.type, type) || other.type == type) &&
|
||||
(identical(other.isSecondary, isSecondary) ||
|
||||
other.isSecondary == isSecondary) &&
|
||||
(identical(other.description, description) ||
|
||||
other.description == description));
|
||||
}
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return _$LandmarkModelToJson(this, );
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return identical(this, other) || (other.runtimeType == runtimeType&&other is _LandmarkModel&&(identical(other.uuid, uuid) || other.uuid == uuid)&&(identical(other.name, name) || other.name == name)&&const DeepCollectionEquality().equals(other._location, _location)&&(identical(other.type, type) || other.type == type)&&(identical(other.isSecondary, isSecondary) || other.isSecondary == isSecondary)&&(identical(other.description, description) || other.description == description));
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode => Object.hash(runtimeType,uuid,name,const DeepCollectionEquality().hash(_location),type,isSecondary,description);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'LandmarkModel(uuid: $uuid, name: $name, location: $location, type: $type, isSecondary: $isSecondary, description: $description)';
|
||||
}
|
||||
|
||||
@JsonKey(includeFromJson: false, includeToJson: false)
|
||||
@override
|
||||
int get hashCode => Object.hash(
|
||||
runtimeType,
|
||||
uuid,
|
||||
name,
|
||||
const DeepCollectionEquality().hash(_location),
|
||||
type,
|
||||
isSecondary,
|
||||
description);
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'LandmarkModel(uuid: $uuid, name: $name, location: $location, type: $type, isSecondary: $isSecondary, description: $description)';
|
||||
}
|
||||
}
|
||||
|
||||
/// @nodoc
|
||||
abstract mixin class _$LandmarkModelCopyWith<$Res>
|
||||
implements $LandmarkModelCopyWith<$Res> {
|
||||
factory _$LandmarkModelCopyWith(
|
||||
_LandmarkModel value, $Res Function(_LandmarkModel) _then) =
|
||||
__$LandmarkModelCopyWithImpl;
|
||||
@override
|
||||
@useResult
|
||||
$Res call(
|
||||
{String uuid,
|
||||
String name,
|
||||
List<double> location,
|
||||
String type,
|
||||
bool isSecondary,
|
||||
String description});
|
||||
}
|
||||
abstract mixin class _$LandmarkModelCopyWith<$Res> implements $LandmarkModelCopyWith<$Res> {
|
||||
factory _$LandmarkModelCopyWith(_LandmarkModel value, $Res Function(_LandmarkModel) _then) = __$LandmarkModelCopyWithImpl;
|
||||
@override @useResult
|
||||
$Res call({
|
||||
String uuid, String name, List<double> location, String type, bool isSecondary, String description
|
||||
});
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
/// @nodoc
|
||||
class __$LandmarkModelCopyWithImpl<$Res>
|
||||
implements _$LandmarkModelCopyWith<$Res> {
|
||||
@@ -399,45 +278,21 @@ class __$LandmarkModelCopyWithImpl<$Res>
|
||||
final _LandmarkModel _self;
|
||||
final $Res Function(_LandmarkModel) _then;
|
||||
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override
|
||||
@pragma('vm:prefer-inline')
|
||||
$Res call({
|
||||
Object? uuid = null,
|
||||
Object? name = null,
|
||||
Object? location = null,
|
||||
Object? type = null,
|
||||
Object? isSecondary = null,
|
||||
Object? description = null,
|
||||
}) {
|
||||
return _then(_LandmarkModel(
|
||||
uuid: null == uuid
|
||||
? _self.uuid
|
||||
: uuid // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
name: null == name
|
||||
? _self.name
|
||||
: name // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
location: null == location
|
||||
? _self._location
|
||||
: location // ignore: cast_nullable_to_non_nullable
|
||||
as List<double>,
|
||||
type: null == type
|
||||
? _self.type
|
||||
: type // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
isSecondary: null == isSecondary
|
||||
? _self.isSecondary
|
||||
: isSecondary // ignore: cast_nullable_to_non_nullable
|
||||
as bool,
|
||||
description: null == description
|
||||
? _self.description
|
||||
: description // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
/// Create a copy of LandmarkModel
|
||||
/// with the given fields replaced by the non-null parameter values.
|
||||
@override @pragma('vm:prefer-inline') $Res call({Object? uuid = null,Object? name = null,Object? location = null,Object? type = null,Object? isSecondary = null,Object? description = null,}) {
|
||||
return _then(_LandmarkModel(
|
||||
uuid: null == uuid ? _self.uuid : uuid // ignore: cast_nullable_to_non_nullable
|
||||
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
|
||||
as String,location: null == location ? _self._location : location // ignore: cast_nullable_to_non_nullable
|
||||
as List<double>,type: null == type ? _self.type : type // ignore: cast_nullable_to_non_nullable
|
||||
as String,isSecondary: null == isSecondary ? _self.isSecondary : isSecondary // ignore: cast_nullable_to_non_nullable
|
||||
as bool,description: null == description ? _self.description : description // ignore: cast_nullable_to_non_nullable
|
||||
as String,
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
// dart format on
|
||||
|
||||
@@ -1,119 +1,89 @@
|
||||
import 'dart:developer';
|
||||
|
||||
import 'package:anyway/domain/entities/landmark.dart';
|
||||
import 'package:anyway/domain/entities/preferences.dart';
|
||||
import 'package:anyway/domain/entities/trip.dart';
|
||||
import 'package:anyway/domain/repositories/trip_repository.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:anyway/data/datasources/trip_remote_datasource.dart';
|
||||
|
||||
// We can request a new trip from our backend API by passing it user preferences (which contain all the necessary data)
|
||||
class BackendTripRepository implements TripRepository {
|
||||
final Dio dio;
|
||||
|
||||
BackendTripRepository({required this.dio});
|
||||
final TripRemoteDataSource remote;
|
||||
|
||||
BackendTripRepository({required this.remote});
|
||||
|
||||
@override
|
||||
Future<Trip> getTrip({Preferences? preferences, String? tripUUID}) async {
|
||||
Map<String, dynamic> data = {
|
||||
"preferences": preferences!.toJson(),
|
||||
// "start": preferences!.startPoint.location,
|
||||
Future<Trip> getTrip({Preferences? preferences, String? tripUUID, List<Landmark>? landmarks}) async {
|
||||
try {
|
||||
Map<String, dynamic> json;
|
||||
|
||||
if (tripUUID != null) {
|
||||
json = await remote.fetchTrip(tripUUID);
|
||||
} else {
|
||||
if (preferences == null) {
|
||||
throw ArgumentError('Either preferences or tripUUID must be provided');
|
||||
}
|
||||
|
||||
final Map<String, dynamic> prefsPayload = _buildPreferencesPayload(preferences);
|
||||
List<Map<String, dynamic>> landmarkBodies = landmarks != null
|
||||
? landmarks.map((lm) => lm.toJson()).toList()
|
||||
: await _fetchLandmarkPayloads(prefsPayload, preferences.startLocation);
|
||||
|
||||
// TODO: remove
|
||||
// restrict the landmark list to 30 to iterate quickly
|
||||
landmarkBodies = landmarkBodies.take(30).toList();
|
||||
// change the json key because of backend inconsistency
|
||||
for (var lm in landmarkBodies) {
|
||||
if (lm.containsKey('type')) {
|
||||
lm['type'] = "sightseeing";
|
||||
}
|
||||
lm['osm_type'] = 'node';
|
||||
lm['osm_id'] = 1;
|
||||
}
|
||||
|
||||
final Map<String, dynamic> body = {
|
||||
'preferences': prefsPayload,
|
||||
'landmarks': landmarkBodies,
|
||||
'start': preferences.startLocation,
|
||||
};
|
||||
if (preferences.endLocation != null) {
|
||||
body['end'] = preferences.endLocation;
|
||||
}
|
||||
if (preferences.detourToleranceMinutes != null) {
|
||||
body['detour_tolerance_minute'] = preferences.detourToleranceMinutes;
|
||||
}
|
||||
|
||||
json = await remote.createTrip(body);
|
||||
}
|
||||
|
||||
return Trip.fromJson(json);
|
||||
} catch (e) {
|
||||
throw Exception('Failed to fetch trip: ${e.toString()}');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// TODO - maybe shorten this
|
||||
@override
|
||||
Future<List<Landmark>> searchLandmarks(Preferences preferences) async {
|
||||
final Map<String, dynamic> prefsPayload = _buildPreferencesPayload(preferences);
|
||||
final List<Map<String, dynamic>> rawLandmarks = await _fetchLandmarkPayloads(prefsPayload, preferences.startLocation);
|
||||
return rawLandmarks.map((lmJson) => Landmark.fromJson(lmJson)).toList();
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> _fetchLandmarkPayloads(
|
||||
Map<String, dynamic> prefsPayload, List<double> startLocation) async {
|
||||
final Map<String, dynamic> landmarkRequest = {
|
||||
'preferences': prefsPayload,
|
||||
'start': startLocation,
|
||||
};
|
||||
|
||||
return await remote.fetchLandmarks(landmarkRequest);
|
||||
}
|
||||
|
||||
late Response response;
|
||||
try {
|
||||
response = await dio.post(
|
||||
"/trip/new",
|
||||
data: data
|
||||
);
|
||||
} catch (e) {
|
||||
trip.updateUUID("error");
|
||||
|
||||
// Format the error message to be more user friendly
|
||||
String errorDescription;
|
||||
if (e is DioException) {
|
||||
errorDescription = e.message ?? "Unknown error";
|
||||
} else if (e is SocketException) {
|
||||
errorDescription = "No internet connection";
|
||||
} else if (e is TimeoutException) {
|
||||
errorDescription = "Request timed out";
|
||||
} else {
|
||||
errorDescription = "Unknown error";
|
||||
}
|
||||
|
||||
String errorMessage = """
|
||||
We're sorry, the following error was generated:
|
||||
|
||||
${errorDescription.trim()}
|
||||
""".trim();
|
||||
|
||||
trip.updateError(errorMessage);
|
||||
log(e.toString());
|
||||
log(errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
// handle more specific errors
|
||||
if (response.statusCode != 200) {
|
||||
trip.updateUUID("error");
|
||||
String errorDescription;
|
||||
if (response.data.runtimeType == String) {
|
||||
errorDescription = response.data;
|
||||
} else if (response.data.runtimeType == Map<String, dynamic>) {
|
||||
errorDescription = response.data["detail"] ?? "Unknown error";
|
||||
} else {
|
||||
errorDescription = "Unknown error";
|
||||
}
|
||||
|
||||
String errorMessage = """
|
||||
We're sorry, our servers generated the following error:
|
||||
|
||||
${errorDescription.trim()}
|
||||
Please try again.
|
||||
""".trim();
|
||||
trip.updateError(errorMessage);
|
||||
log(errorMessage);
|
||||
// Actualy no need to throw an exception, we can just log the error and let the user retry
|
||||
// throw Exception(errorDetail);
|
||||
} else {
|
||||
|
||||
// if the response data is not json, throw an error
|
||||
if (response.data is! Map<String, dynamic>) {
|
||||
log("${response.data.runtimeType}");
|
||||
trip.updateUUID("error");
|
||||
String errorMessage = """
|
||||
We're sorry, our servers generated the following error:
|
||||
|
||||
${response.data.trim()}
|
||||
Please try again.
|
||||
""".trim();
|
||||
trip.updateError(errorMessage);
|
||||
log(errorMessage);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, dynamic> json = response.data;
|
||||
|
||||
// only fill in the trip "meta" data for now
|
||||
trip.loadFromJson(json);
|
||||
|
||||
// now fill the trip with landmarks
|
||||
// we are going to recreate ALL the landmarks from the information given by the api
|
||||
trip.landmarks.remove(trip.landmarks.first);
|
||||
String? nextUUID = json["first_landmark_uuid"];
|
||||
while (nextUUID != null) {
|
||||
var (landmark, newUUID) = await fetchLandmark(nextUUID);
|
||||
trip.addLandmark(landmark);
|
||||
nextUUID = newUUID;
|
||||
}
|
||||
|
||||
log(response.data.toString());
|
||||
// // Also save the trip for the user's convenience
|
||||
// savedTrips.addTrip(trip);
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
Map<String, dynamic> _buildPreferencesPayload(Preferences preferences) {
|
||||
final Map<String, dynamic> prefsPayload = {};
|
||||
preferences.scores.forEach((type, score) {
|
||||
prefsPayload[type] = {'type': type, 'score': score};
|
||||
});
|
||||
prefsPayload['max_time_minute'] = preferences.maxTimeMinutes;
|
||||
return prefsPayload;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:anyway/domain/repositories/onboarding_repository.dart';
|
||||
|
||||
class LocalOnboardingRepository implements OnboardingRepository {
|
||||
static const _key = 'onboardingCompleted';
|
||||
|
||||
@override
|
||||
Future<bool> isOnboarded() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getBool(_key) ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> setOnboarded(bool value) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setBool(_key, value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:anyway/domain/entities/preferences.dart';
|
||||
import 'package:anyway/domain/repositories/preferences_repository.dart';
|
||||
|
||||
class PreferencesRepositoryImpl implements PreferencesRepository {
|
||||
static const _key = 'userPreferences';
|
||||
|
||||
@override
|
||||
Future<Preferences> getPreferences() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = prefs.getString(_key);
|
||||
if (raw == null) {
|
||||
// TODO - rethink this
|
||||
// return a sensible default
|
||||
return Preferences(
|
||||
scores: {
|
||||
'sightseeing': 0,
|
||||
'shopping': 0,
|
||||
'nature': 0,
|
||||
},
|
||||
maxTimeMinutes: 120,
|
||||
startLocation: const [48.8575, 2.3514],
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final map = json.decode(raw) as Map<String, dynamic>;
|
||||
return Preferences.fromJson(map);
|
||||
} catch (_) {
|
||||
return Preferences(
|
||||
scores: {
|
||||
'sightseeing': 0,
|
||||
'shopping': 0,
|
||||
'nature': 0,
|
||||
},
|
||||
maxTimeMinutes: 120,
|
||||
startLocation: const [48.8575, 2.3514],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> savePreferences(Preferences preferences) async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final raw = json.encode(preferences.toJson());
|
||||
await prefs.setString(_key, raw);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user