From 7f4fd610c5a4cebb5da137a3e1a27e364df365ea Mon Sep 17 00:00:00 2001 From: Dayron Date: Fri, 10 Oct 2025 11:49:54 +0200 Subject: [PATCH] feat: Add group creation functionality and refactor trip service for improved data handling --- lib/components/home/create_trip_content.dart | 96 ++++++++++++-------- lib/models/group.dart | 8 +- lib/services/group_service.dart | 30 ++++-- lib/services/trip_service.dart | 3 - 4 files changed, 84 insertions(+), 53 deletions(-) diff --git a/lib/components/home/create_trip_content.dart b/lib/components/home/create_trip_content.dart index 205f936..4cd51b1 100644 --- a/lib/components/home/create_trip_content.dart +++ b/lib/components/home/create_trip_content.dart @@ -3,6 +3,8 @@ import 'package:provider/provider.dart'; import 'package:travel_mate/models/trip.dart'; import 'package:travel_mate/providers/user_provider.dart'; import 'package:travel_mate/services/trip_service.dart'; +import 'package:travel_mate/services/group_service.dart'; +import 'package:travel_mate/models/group.dart'; class CreateTripContent extends StatefulWidget { @@ -44,18 +46,6 @@ class _CreateTripContentState extends State { title: Text('Créer un voyage'), backgroundColor: Theme.of(context).colorScheme.primary, foregroundColor: Colors.white, - actions: [ - TextButton( - onPressed: _isLoading ? null : _saveTrip, - child: Text( - 'Sauvegarder', - style: TextStyle( - color: Colors.white, - fontWeight: FontWeight.bold, - ), - ), - ), - ], ), body: SingleChildScrollView( padding: EdgeInsets.all(16), @@ -413,6 +403,55 @@ class _CreateTripContentState extends State { }); } + Future _saveGroup() async { + if (!_formKey.currentState!.validate()) { + return false; + } + + setState(() { + _isLoading = true; + }); + + final members = await _changeUserEmailById(_participants); + + final group = Group( + id: '', + name: _titleController.text.trim(), + members: members, + ); + + final groupService = GroupService(); + bool success = await groupService.createGroup(group); + return success; + } + + Future> _changeUserEmailById(List participants) async { + final userProvider = Provider.of(context, listen: false); + List ids = []; + + for (String email in participants) { + try { + final id = await userProvider.getUserIdByEmail(email); + if (id != null) { + ids.add(id); + } else { + print('Utilisateur non trouvé pour l\'ID: $email'); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Utilisateur non trouvé pour l\'email: $email'), + backgroundColor: Colors.orange, + duration: Duration(seconds: 2), + ), + ); + } + } catch (e) { + print('Erreur lors de la récupération de l\'utilisateur $email: $e'); + } + } + + return ids; + } + Future _saveTrip() async { if (!_formKey.currentState!.validate()) { return; @@ -443,34 +482,11 @@ class _CreateTripContentState extends State { // Convertir les emails en IDs utilisateur List participantIds = []; - - // Ajouter automatiquement le créateur if (currentUser.id != null) { participantIds.add(currentUser.id!); } - // Convertir chaque email en ID utilisateur - for (String email in _participants) { - try { - final userId = await userProvider.getUserIdByEmail(email); - if (userId != null && !participantIds.contains(userId)) { - participantIds.add(userId); - print('Email $email converti en ID: $userId'); - } else if (userId == null) { - print('Utilisateur non trouvé pour l\'email: $email'); - // Optionnel: afficher un warning à l'utilisateur - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Utilisateur non trouvé pour l\'email: $email'), - backgroundColor: Colors.orange, - duration: Duration(seconds: 2), - ), - ); - } - } catch (e) { - print('Erreur lors de la recherche de l\'utilisateur $email: $e'); - } - } + participantIds = await _changeUserEmailById(_participants); // Créer l'objet Trip avec les IDs des participants final trip = Trip( @@ -487,14 +503,16 @@ class _CreateTripContentState extends State { updatedAt: DateTime.now(), ); - print('Participants IDs: $participantIds'); print('Données du voyage: ${trip.toMap()}'); // Sauvegarder le voyage final tripService = TripService(); final success = await tripService.addTrip(trip); - if (success && mounted) { + //Créer le groupe associé au voyage + final successGroup = await _saveGroup(); + + if (success && successGroup && mounted) { print('Voyage créé avec succès !'); ScaffoldMessenger.of(context).showSnackBar( SnackBar( @@ -525,4 +543,4 @@ class _CreateTripContentState extends State { } } } -} +} \ No newline at end of file diff --git a/lib/models/group.dart b/lib/models/group.dart index 2c46dea..9137d6d 100644 --- a/lib/models/group.dart +++ b/lib/models/group.dart @@ -1,9 +1,7 @@ -import 'package:travel_mate/models/user.dart'; - class Group { final String? id; final String name; - final List members; + final List members; Group({ this.id, @@ -15,14 +13,14 @@ class Group { return Group( id: documentId, name: data['name'] ?? '', - members: List.from(data['members']?.map((member) => User.fromMap(member)) ?? []), + members: List.from(data['members'] ?? []), ); } Map toMap() { return { 'name': name, - 'members': members.map((member) => member.toMap()).toList(), + 'members': members, }; } } \ No newline at end of file diff --git a/lib/services/group_service.dart b/lib/services/group_service.dart index 337bb04..2b5e196 100644 --- a/lib/services/group_service.dart +++ b/lib/services/group_service.dart @@ -12,15 +12,33 @@ class GroupService { }); } - Future createGroup(Group group) async { - await _firestore.collection('groups').add(group.toMap()); + Future createGroup(Group group) async { + try { + await _firestore.collection('groups').add(group.toMap()); + return true; + } catch (e) { + print('Erreur lors de la création du groupe: $e'); + return false; + } } - Future updateGroup(Group group) async { - await _firestore.collection('groups').doc(group.id).update(group.toMap()); + Future updateGroup(Group group) async { + try { + await _firestore.collection('groups').doc(group.id).update(group.toMap()); + return true; + } catch (e) { + print('Erreur lors de la mise à jour du groupe: $e'); + return false; + } } - Future deleteGroup(String groupId) async { - await _firestore.collection('groups').doc(groupId).delete(); + Future deleteGroup(String groupId) async { + try { + await _firestore.collection('groups').doc(groupId).delete(); + return true; + } catch (e) { + print('Erreur lors de la suppression du groupe: $e'); + return false; + } } } \ No newline at end of file diff --git a/lib/services/trip_service.dart b/lib/services/trip_service.dart index 5a31096..ad4b89b 100644 --- a/lib/services/trip_service.dart +++ b/lib/services/trip_service.dart @@ -30,9 +30,6 @@ class TripService { // Retirer l'ID vide du map tripData.remove('id'); - // Les participants contiennent déjà uniquement des IDs - // Pas besoin d'ajouter le créateur car il est déjà inclus - // Convertir les dates en Timestamp pour Firestore tripData['startDate'] = Timestamp.fromDate(trip.startDate); tripData['endDate'] = Timestamp.fromDate(trip.endDate);