diff --git a/lib/blocs/group/group_bloc.dart b/lib/blocs/group/group_bloc.dart index b7e20ac..b0406d2 100644 --- a/lib/blocs/group/group_bloc.dart +++ b/lib/blocs/group/group_bloc.dart @@ -79,10 +79,11 @@ class GroupBloc extends Bloc { ) async { try { emit(GroupLoading()); - await _repository.createGroupWithMembers( + final groupId = await _repository.createGroupWithMembers( group: event.group, members: [], ); + emit(GroupCreated(groupId: groupId)); emit(const GroupOperationSuccess('Groupe créé avec succès')); } catch (e) { emit(GroupError('Erreur lors de la création: $e')); diff --git a/lib/blocs/group/group_state.dart b/lib/blocs/group/group_state.dart index 488cf07..e8f152b 100644 --- a/lib/blocs/group/group_state.dart +++ b/lib/blocs/group/group_state.dart @@ -30,6 +30,18 @@ class GroupLoaded extends GroupState { const GroupLoaded(this.groups); } +class GroupCreated extends GroupState { + final String groupId; + final String message; + + const GroupCreated({ + required this.groupId, + this.message = 'Groupe créé avec succès', + }); + @override + List get props => [groupId, message]; +} + // Succès d'une opération class GroupOperationSuccess extends GroupState { final String message; diff --git a/lib/blocs/trip/trip_state.dart b/lib/blocs/trip/trip_state.dart index 021bd79..d8da52e 100644 --- a/lib/blocs/trip/trip_state.dart +++ b/lib/blocs/trip/trip_state.dart @@ -21,7 +21,6 @@ class TripLoaded extends TripState { List get props => [trips]; } -// NOUVEAU : État pour indiquer qu'un voyage a été créé avec succès class TripCreated extends TripState { final String tripId; final String message; diff --git a/lib/components/home/create_trip_content.dart b/lib/components/home/create_trip_content.dart index cbd03c6..7604cd3 100644 --- a/lib/components/home/create_trip_content.dart +++ b/lib/components/home/create_trip_content.dart @@ -9,6 +9,10 @@ import '../../blocs/trip/trip_event.dart'; import '../../blocs/trip/trip_state.dart'; import '../../blocs/group/group_bloc.dart'; import '../../blocs/group/group_event.dart'; +import '../../blocs/group/group_state.dart'; +import '../../blocs/account/account_bloc.dart'; +import '../../blocs/account/account_event.dart'; +import '../../models/account.dart'; import '../../models/group.dart'; import '../../models/group_member.dart'; import '../../services/user_service.dart'; @@ -38,6 +42,7 @@ class _CreateTripContentState extends State { DateTime? _startDate; DateTime? _endDate; bool _isLoading = false; + String? _createdTripId; final List _participants = []; final _participantController = TextEditingController(); @@ -106,38 +111,66 @@ class _CreateTripContentState extends State { @override Widget build(BuildContext context) { - return BlocListener( - listener: (context, tripState) { - // Écouter l'état TripCreated pour récupérer l'ID du voyage - if (tripState is TripCreated) { - _createGroupForTrip(tripState.tripId); - } else if (tripState is TripOperationSuccess) { - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(tripState.message), - backgroundColor: Colors.green, - ), - ); - Navigator.pop(context); - if (isEditing) { - Navigator.pop(context); // Retour supplémentaire en mode édition + return MultiBlocListener( + listeners: [ + // Listener pour TripBloc + BlocListener( + listener: (context, tripState) { + if (tripState is TripCreated) { + // Stocker l'ID du trip et créer le groupe + _createdTripId = tripState.tripId; + _createGroupForTrip(tripState.tripId); + } else if (tripState is TripOperationSuccess) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(tripState.message), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context); + if (isEditing) { + Navigator.pop(context); + } + } + } else if (tripState is TripError) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(tripState.message), + backgroundColor: Colors.red, + ), + ); + setState(() { + _isLoading = false; + }); + } } - } - } else if (tripState is TripError) { - if (mounted) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(tripState.message), - backgroundColor: Colors.red, - ), - ); - setState(() { - _isLoading = false; - }); - } - } - }, + }, + ), + // Nouveau listener pour GroupBloc + BlocListener( + listener: (context, groupState) { + if (groupState is GroupCreated && _createdTripId != null) { + // Le groupe a été créé, maintenant créer le compte + print('++++++++++++++ Creating account for trip ${_createdTripId!} and group ${groupState.groupId} ++++++++++++++'); + _createAccountForTrip(_createdTripId!, groupState.groupId); + } else if (groupState is GroupError) { + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Erreur lors de la création du groupe: ${groupState.message}'), + backgroundColor: Colors.red, + ), + ); + setState(() { + _isLoading = false; + }); + } + } + }, + ), + ], child: BlocBuilder( builder: (context, userState) { if (userState is! user_state.UserLoaded) { @@ -506,6 +539,7 @@ class _CreateTripContentState extends State { user_state.UserModel currentUser, List> participantsData, ) async { + final groupBloc = context.read(); try { final group = await _groupRepository.getGroupByTripId(tripId); @@ -517,20 +551,7 @@ class _CreateTripContentState extends State { return; } - final newMembers = [ - GroupMember( - userId: currentUser.id, - firstName: currentUser.prenom, - pseudo: currentUser.prenom, - role: 'admin', - ), - ...participantsData.map((p) => GroupMember( - userId: p['id'] as String, - firstName: p['firstName'] as String, - pseudo: p['firstName'] as String, - role: 'member', - )), - ]; + final newMembers = await _createMembers(); final currentMembers = await _groupRepository.getGroupMembers(group.id); final currentMemberIds = currentMembers.map((m) => m.userId).toSet(); @@ -543,11 +564,15 @@ class _CreateTripContentState extends State { .toList(); for (final member in membersToAdd) { - context.read().add(AddMemberToGroup(group.id, member)); + if (mounted) { + groupBloc.add(AddMemberToGroup(group.id, member)); + } } for (final member in membersToRemove) { - context.read().add(RemoveMemberFromGroup(group.id, member.userId)); + if (mounted) { + groupBloc.add(RemoveMemberFromGroup(group.id, member.userId)); + } } } catch (e) { _errorService.logError( @@ -557,39 +582,53 @@ class _CreateTripContentState extends State { } } - // NOUVELLE MÉTHODE : Créer le groupe après la création du voyage + Future> _createMembers() async { + final userState = context.read().state; + if (userState is! user_state.UserLoaded) return []; + + final currentUser = userState.user; + final participantsData = await _getParticipantsData(_participants); + + final groupMembers = [ + GroupMember( + userId: currentUser.id, + firstName: currentUser.prenom, + pseudo: currentUser.prenom, + role: 'admin', + ), + ...participantsData.map((p) => GroupMember( + userId: p['id'] as String, + firstName: p['firstName'] as String, + pseudo: p['firstName'] as String, + role: 'member', + )), + ]; + return groupMembers; + } + Future _createGroupForTrip(String tripId) async { + final groupBloc = context.read(); try { final userState = context.read().state; if (userState is! user_state.UserLoaded) return; final currentUser = userState.user; - final participantsData = await _getParticipantsData(_participants); // Créer le groupe avec le tripId récupéré final group = Group( id: '', // Sera généré par Firestore name: _titleController.text.trim(), - tripId: tripId, // ✅ ID du voyage récupéré + tripId: tripId, createdBy: currentUser.id, ); - final groupMembers = [ - GroupMember( - userId: currentUser.id, - firstName: currentUser.prenom, - pseudo: currentUser.prenom, - role: 'admin', - ), - ...participantsData.map((p) => GroupMember( - userId: p['id'] as String, - firstName: p['firstName'] as String, - pseudo: p['firstName'] as String, - role: 'member', - )), - ]; + final groupMembers = await _createMembers(); - context.read().add(CreateGroupWithMembers( + if (groupMembers.isEmpty) { + throw Exception('Erreur lors de la création des membres du groupe'); + } + + groupBloc.add(CreateGroupWithMembers( group: group, members: groupMembers, )); @@ -622,6 +661,60 @@ class _CreateTripContentState extends State { } } + Future _createAccountForTrip(String tripId, String groupId) async { + final accountBloc = context.read(); + try { + final userState = context.read().state; + if (userState is! user_state.UserLoaded) return; + + print('Creating account for trip $tripId and group $groupId'); + + final account = Account( + id: '', + tripId: tripId, + groupId: groupId, + name: _titleController.text.trim(), + ); + + final accountsMembers = await _createMembers(); + + accountBloc.add(CreateAccountWithMembers( + account: account, + members: accountsMembers, + )); + + print('++++++++++++++ Created account for trip $tripId and group $groupId ++++++++++++++'); + + if (mounted) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Compte créé avec succès !'), + backgroundColor: Colors.green, + ), + ); + + setState(() { + _isLoading = false; + }); + + Navigator.pop(context); + } + + + } catch (e) { + _errorService.logError( + 'create_trip_content.dart', + 'Erreur lors de la création du compte: $e', + ); + + if (mounted) { + setState(() { + _isLoading = false; + }); + } + } + } + Future _saveTrip(user_state.UserModel currentUser) async { if (!_formKey.currentState!.validate()) { return; @@ -640,6 +733,8 @@ class _CreateTripContentState extends State { _isLoading = true; }); + final tripBloc = context.read(); + try { final participantsData = await _getParticipantsData(_participants); List participantIds = participantsData.map((p) => p['id'] as String).toList(); @@ -664,16 +759,17 @@ class _CreateTripContentState extends State { if (isEditing) { // Mode mise à jour - context.read().add(TripUpdateRequested(trip: trip)); + tripBloc.add(TripUpdateRequested(trip: trip)); await _updateGroupMembers( widget.tripToEdit!.id!, currentUser, participantsData, - ); + ); + } else { // Mode création - Le groupe sera créé dans le listener TripCreated - context.read().add(TripCreateRequested(trip: trip)); + tripBloc.add(TripCreateRequested(trip: trip)); } } catch (e) { if (mounted) {