feat: Enhance trip management features and improve UI responsiveness

- Implemented AutomaticKeepAliveClientMixin in HomeContent to maintain state during navigation.
- Modified trip loading logic to trigger after the first frame for better performance.
- Updated trip loading events to use LoadTripsByUserId for consistency.
- Added temporary success messages for trip creation and operations.
- Improved UI elements for better user experience, including updated text styles and spacing.
- Refactored trip model to support Firestore timestamps and improved error handling during parsing.
- Streamlined trip repository methods for better clarity and performance.
- Enhanced trip service methods to ensure correct mapping from Firestore documents.
- Removed unnecessary trip reset logic on logout.
This commit is contained in:
Dayron
2025-10-20 14:31:41 +02:00
parent af93ac54ff
commit d0a76b5043
12 changed files with 863 additions and 756 deletions

View File

@@ -13,7 +13,7 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
GroupBloc(this._repository) : super(GroupInitial()) { GroupBloc(this._repository) : super(GroupInitial()) {
on<LoadGroupsByUserId>(_onLoadGroupsByUserId); on<LoadGroupsByUserId>(_onLoadGroupsByUserId);
on<_GroupsUpdated>(_onGroupsUpdated); // NOUVEAU événement interne on<_GroupsUpdated>(_onGroupsUpdated);
on<LoadGroupsByTrip>(_onLoadGroupsByTrip); on<LoadGroupsByTrip>(_onLoadGroupsByTrip);
on<CreateGroup>(_onCreateGroup); on<CreateGroup>(_onCreateGroup);
on<CreateGroupWithMembers>(_onCreateGroupWithMembers); on<CreateGroupWithMembers>(_onCreateGroupWithMembers);
@@ -44,7 +44,6 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
} }
} }
// NOUVEAU: Handler pour les mises à jour du stream
Future<void> _onGroupsUpdated( Future<void> _onGroupsUpdated(
_GroupsUpdated event, _GroupsUpdated event,
Emitter<GroupState> emit, Emitter<GroupState> emit,
@@ -111,6 +110,7 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
Emitter<GroupState> emit, Emitter<GroupState> emit,
) async { ) async {
try { try {
// CORRECTION : Utiliser addMemberToGroup au lieu de addMember
await _repository.addMember(event.groupId, event.member); await _repository.addMember(event.groupId, event.member);
emit(const GroupOperationSuccess('Membre ajouté')); emit(const GroupOperationSuccess('Membre ajouté'));
} catch (e) { } catch (e) {
@@ -123,6 +123,7 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
Emitter<GroupState> emit, Emitter<GroupState> emit,
) async { ) async {
try { try {
// CORRECTION : Utiliser removeMemberFromGroup au lieu de removeMember
await _repository.removeMember(event.groupId, event.userId); await _repository.removeMember(event.groupId, event.userId);
emit(const GroupOperationSuccess('Membre supprimé')); emit(const GroupOperationSuccess('Membre supprimé'));
} catch (e) { } catch (e) {
@@ -161,7 +162,6 @@ class GroupBloc extends Bloc<GroupEvent, GroupState> {
} }
} }
// NOUVEAU: Événement interne pour les mises à jour du stream
class _GroupsUpdated extends GroupEvent { class _GroupsUpdated extends GroupEvent {
final List<Group> groups; final List<Group> groups;
final String? error; final String? error;

View File

@@ -1,124 +1,133 @@
import 'dart:async'; import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_bloc/flutter_bloc.dart';
import '../../repositories/trip_repository.dart'; import 'package:travel_mate/data/models/trip.dart';
import 'trip_event.dart'; import 'trip_event.dart';
import 'trip_state.dart'; import 'trip_state.dart';
import '../../data/models/trip.dart'; import '../../repositories/trip_repository.dart';
class TripBloc extends Bloc<TripEvent, TripState> { class TripBloc extends Bloc<TripEvent, TripState> {
final TripRepository _tripRepository; final TripRepository _repository;
StreamSubscription? _tripsSubscription; StreamSubscription? _tripsSubscription;
String? _currentUserId;
TripBloc({required TripRepository tripRepository}) TripBloc(this._repository) : super(TripInitial()) {
: _tripRepository = tripRepository, on<LoadTripsByUserId>(_onLoadTripsByUserId);
super(TripInitial()) { on<TripCreateRequested>(_onTripCreateRequested);
on<TripLoadRequested>(_onLoadRequested); on<TripUpdateRequested>(_onTripUpdateRequested);
on<_TripUpdated>(_onTripUpdated); on<TripDeleteRequested>(_onTripDeleteRequested);
on<TripCreateRequested>(_onCreateRequested); on<_TripsUpdated>(_onTripsUpdated);
on<TripUpdateRequested>(_onUpdateRequested);
on<TripDeleteRequested>(_onDeleteRequested);
on<TripParticipantAddRequested>(_onParticipantAddRequested);
on<TripParticipantRemoveRequested>(_onParticipantRemoveRequested);
on<ResetTrips>(_onResetTrips);
} }
Future<void> _onLoadRequested( Future<void> _onLoadTripsByUserId(
TripLoadRequested event, LoadTripsByUserId event,
Emitter<TripState> emit, Emitter<TripState> emit,
) async { ) async {
emit(TripLoading()); print('🔍 Chargement des trips pour userId: ${event.userId}');
await _tripsSubscription?.cancel();
_tripsSubscription = _tripRepository.getUserTrips(event.userId).listen( // MODIFIÉ : Toujours émettre Loading pour forcer le rechargement
(trips) => add(_TripUpdated(trips: trips)), emit(TripLoading());
onError: (error) => emit(TripError(message: error.toString())),
_currentUserId = event.userId;
await _tripsSubscription?.cancel();
_tripsSubscription = _repository.getTripsByUserId(event.userId).listen(
(trips) {
print('📦 Stream reçu: ${trips.length} trips');
add(_TripsUpdated(trips));
},
onError: (error) {
print('❌ Erreur stream: $error');
emit(TripError(error.toString()));
},
); );
} }
Future<void> _onTripUpdated( void _onTripsUpdated(
_TripUpdated event, _TripsUpdated event,
Emitter<TripState> emit, Emitter<TripState> emit,
) async { ) {
emit(TripLoaded(trips: event.trips)); print('✅ Émission de TripLoaded avec ${event.trips.length} trips');
emit(TripLoaded(event.trips));
} }
Future<void> _onCreateRequested( Future<void> _onTripCreateRequested(
TripCreateRequested event, TripCreateRequested event,
Emitter<TripState> emit, Emitter<TripState> emit,
) async { ) async {
try { try {
await _tripRepository.createTrip(event.trip); print('📝 Création du voyage: ${event.trip.title}');
emit(const TripOperationSuccess(message: 'Voyage créé avec succès')); emit(TripLoading());
final tripId = await _repository.createTrip(event.trip);
print('✅ Voyage créé avec ID: $tripId');
// Émettre TripCreated pour que create_trip_content puisse créer le groupe
emit(TripCreated(tripId: tripId));
// AJOUTÉ : Attendre un peu puis recharger manuellement
await Future.delayed(const Duration(milliseconds: 800));
if (_currentUserId != null) {
print('🔄 Rechargement forcé après création');
add(LoadTripsByUserId(userId: _currentUserId!));
}
} catch (e) { } catch (e) {
emit(TripError(message: e.toString())); print('❌ Erreur création: $e');
emit(TripError('Erreur lors de la création: $e'));
} }
} }
Future<void> _onUpdateRequested( Future<void> _onTripUpdateRequested(
TripUpdateRequested event, TripUpdateRequested event,
Emitter<TripState> emit, Emitter<TripState> emit,
) async { ) async {
try { try {
await _tripRepository.updateTrip(event.trip); print('📝 Mise à jour du voyage: ${event.trip.title}');
emit(const TripOperationSuccess(message: 'Voyage mis à jour'));
await _repository.updateTrip(event.trip.id!, event.trip);
print('✅ Voyage mis à jour');
emit(const TripOperationSuccess('Voyage mis à jour avec succès'));
// AJOUTÉ : Recharger après mise à jour
await Future.delayed(const Duration(milliseconds: 500));
if (_currentUserId != null) {
print('🔄 Rechargement forcé après mise à jour');
add(LoadTripsByUserId(userId: _currentUserId!));
}
} catch (e) { } catch (e) {
emit(TripError(message: e.toString())); print('❌ Erreur mise à jour: $e');
emit(TripError('Erreur lors de la mise à jour: $e'));
} }
} }
Future<void> _onDeleteRequested( Future<void> _onTripDeleteRequested(
TripDeleteRequested event, TripDeleteRequested event,
Emitter<TripState> emit, Emitter<TripState> emit,
) async { ) async {
try { try {
await _tripRepository.deleteTrip(event.tripId); print('🗑️ Suppression du voyage: ${event.tripId}');
emit(const TripOperationSuccess(message: 'Voyage supprimé'));
await _repository.deleteTrip(event.tripId);
print('✅ Voyage supprimé');
emit(const TripOperationSuccess('Voyage supprimé avec succès'));
// AJOUTÉ : Recharger après suppression
await Future.delayed(const Duration(milliseconds: 500));
if (_currentUserId != null) {
print('🔄 Rechargement forcé après suppression');
add(LoadTripsByUserId(userId: _currentUserId!));
}
} catch (e) { } catch (e) {
emit(TripError(message: e.toString())); print('❌ Erreur suppression: $e');
emit(TripError('Erreur lors de la suppression: $e'));
} }
} }
Future<void> _onParticipantAddRequested(
TripParticipantAddRequested event,
Emitter<TripState> emit,
) async {
try {
await _tripRepository.addParticipant(
event.tripId,
event.participantEmail,
);
emit(const TripOperationSuccess(message: 'Participant ajouté'));
} catch (e) {
emit(TripError(message: e.toString()));
}
}
Future<void> _onParticipantRemoveRequested(
TripParticipantRemoveRequested event,
Emitter<TripState> emit,
) async {
try {
await _tripRepository.removeParticipant(
event.tripId,
event.participantEmail,
);
emit(const TripOperationSuccess(message: 'Participant retiré'));
} catch (e) {
emit(TripError(message: e.toString()));
}
}
Future<void> _onResetTrips(
ResetTrips event,
Emitter<TripState> emit,
) async {
await _tripsSubscription?.cancel();
_tripsSubscription = null;
emit(TripInitial());
}
@override @override
Future<void> close() { Future<void> close() {
_tripsSubscription?.cancel(); _tripsSubscription?.cancel();
@@ -126,10 +135,10 @@ class TripBloc extends Bloc<TripEvent, TripState> {
} }
} }
class _TripUpdated extends TripEvent { class _TripsUpdated extends TripEvent {
final List<Trip> trips; final List<Trip> trips;
const _TripUpdated({required this.trips}); const _TripsUpdated(this.trips);
@override @override
List<Object?> get props => [trips]; List<Object?> get props => [trips];

View File

@@ -8,10 +8,10 @@ abstract class TripEvent extends Equatable {
List<Object?> get props => []; List<Object?> get props => [];
} }
class TripLoadRequested extends TripEvent { class LoadTripsByUserId extends TripEvent {
final String userId; final String userId;
const TripLoadRequested({required this.userId}); const LoadTripsByUserId({required this.userId});
@override @override
List<Object?> get props => [userId]; List<Object?> get props => [userId];
@@ -42,38 +42,4 @@ class TripDeleteRequested extends TripEvent {
@override @override
List<Object?> get props => [tripId]; List<Object?> get props => [tripId];
}
class TripParticipantAddRequested extends TripEvent {
final String tripId;
final String participantEmail;
const TripParticipantAddRequested({
required this.tripId,
required this.participantEmail,
});
@override
List<Object?> get props => [tripId, participantEmail];
}
class TripParticipantRemoveRequested extends TripEvent {
final String tripId;
final String participantEmail;
const TripParticipantRemoveRequested({
required this.tripId,
required this.participantEmail,
});
@override
List<Object?> get props => [tripId, participantEmail];
}
// NOUVEAU : Événement pour réinitialiser les trips
class ResetTrips extends TripEvent {
const ResetTrips();
@override
List<Object?> get props => [];
} }

View File

@@ -15,16 +15,30 @@ class TripLoading extends TripState {}
class TripLoaded extends TripState { class TripLoaded extends TripState {
final List<Trip> trips; final List<Trip> trips;
const TripLoaded({required this.trips}); const TripLoaded(this.trips);
@override @override
List<Object?> get props => [trips]; List<Object?> 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;
const TripCreated({
required this.tripId,
this.message = 'Voyage créé avec succès',
});
@override
List<Object?> get props => [tripId, message];
}
class TripOperationSuccess extends TripState { class TripOperationSuccess extends TripState {
final String message; final String message;
const TripOperationSuccess({required this.message}); const TripOperationSuccess(this.message);
@override @override
List<Object?> get props => [message]; List<Object?> get props => [message];
@@ -33,7 +47,7 @@ class TripOperationSuccess extends TripState {
class TripError extends TripState { class TripError extends TripState {
final String message; final String message;
const TripError({required this.message}); const TripError(this.message);
@override @override
List<Object?> get props => [message]; List<Object?> get props => [message];

View File

@@ -6,14 +6,20 @@ import '../../blocs/user/user_bloc.dart';
import '../../blocs/user/user_state.dart' as user_state; import '../../blocs/user/user_state.dart' as user_state;
import '../../blocs/trip/trip_bloc.dart'; import '../../blocs/trip/trip_bloc.dart';
import '../../blocs/trip/trip_event.dart'; import '../../blocs/trip/trip_event.dart';
import '../../blocs/trip/trip_state.dart';
import '../../blocs/group/group_bloc.dart'; import '../../blocs/group/group_bloc.dart';
import '../../blocs/group/group_event.dart'; import '../../blocs/group/group_event.dart';
import '../../data/models/group.dart'; import '../../data/models/group.dart';
import '../../data/models/group_member.dart'; import '../../data/models/group_member.dart';
import '../../services/user_service.dart'; import '../../services/user_service.dart';
import '../../repositories/group_repository.dart';
class CreateTripContent extends StatefulWidget { class CreateTripContent extends StatefulWidget {
const CreateTripContent({super.key}); final Trip? tripToEdit;
const CreateTripContent({
super.key,
this.tripToEdit,
});
@override @override
State<CreateTripContent> createState() => _CreateTripContentState(); State<CreateTripContent> createState() => _CreateTripContentState();
@@ -27,6 +33,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
final _locationController = TextEditingController(); final _locationController = TextEditingController();
final _budgetController = TextEditingController(); final _budgetController = TextEditingController();
final _userService = UserService(); final _userService = UserService();
final _groupRepository = GroupRepository();
DateTime? _startDate; DateTime? _startDate;
DateTime? _endDate; DateTime? _endDate;
@@ -35,6 +42,58 @@ class _CreateTripContentState extends State<CreateTripContent> {
final List<String> _participants = []; final List<String> _participants = [];
final _participantController = TextEditingController(); final _participantController = TextEditingController();
bool get isEditing => widget.tripToEdit != null;
@override
void initState() {
super.initState();
_initializeFormWithTrip();
}
Future<void> _initializeFormWithTrip() async {
if (widget.tripToEdit != null) {
final trip = widget.tripToEdit!;
setState(() {
_titleController.text = trip.title;
_descriptionController.text = trip.description;
_locationController.text = trip.location;
_budgetController.text = trip.budget?.toString() ?? '';
_startDate = trip.startDate;
_endDate = trip.endDate;
});
await _loadParticipantEmails(trip.participants);
}
}
Future<void> _loadParticipantEmails(List<String> participantIds) async {
final userState = context.read<UserBloc>().state;
String? currentUserId;
if (userState is user_state.UserLoaded) {
currentUserId = userState.user.id;
}
for (String userId in participantIds) {
if (userId == currentUserId) continue;
try {
final userDoc = await _userService.getUserById(userId);
if (userDoc != null && userDoc.email.isNotEmpty) {
setState(() {
_participants.add(userDoc.email);
});
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur chargement participant $userId: $e',
);
}
}
}
@override @override
void dispose() { void dispose() {
_titleController.dispose(); _titleController.dispose();
@@ -47,235 +106,271 @@ class _CreateTripContentState extends State<CreateTripContent> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocBuilder<UserBloc, user_state.UserState>( return BlocListener<TripBloc, TripState>(
builder: (context, userState) { listener: (context, tripState) {
if (userState is! user_state.UserLoaded) { // Écouter l'état TripCreated pour récupérer l'ID du voyage
return Scaffold( if (tripState is TripCreated) {
appBar: AppBar(title: Text('Créer un voyage')), _createGroupForTrip(tripState.tripId);
body: Center(child: Text('Veuillez vous connecter')), } 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
}
}
} else if (tripState is TripError) {
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(tripState.message),
backgroundColor: Colors.red,
),
);
setState(() {
_isLoading = false;
});
}
} }
},
child: BlocBuilder<UserBloc, user_state.UserState>(
builder: (context, userState) {
if (userState is! user_state.UserLoaded) {
return Scaffold(
appBar: AppBar(
title: Text(isEditing ? 'Modifier le voyage' : 'Créer un voyage'),
),
body: Center(child: Text('Veuillez vous connecter')),
);
}
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text('Créer un voyage'), title: Text(isEditing ? 'Modifier le voyage' : 'Créer un voyage'),
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white, foregroundColor: Colors.white,
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: EdgeInsets.all(16), padding: EdgeInsets.all(16),
child: Form( child: Form(
key: _formKey, key: _formKey,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
_buildSectionTitle('Informations générales'), _buildSectionTitle('Informations générales'),
SizedBox(height: 16), SizedBox(height: 16),
TextFormField( TextFormField(
controller: _titleController, controller: _titleController,
validator: (value) { validator: (value) {
if (value == null || value.trim().isEmpty) { if (value == null || value.trim().isEmpty) {
return 'Titre requis'; return 'Titre requis';
} }
return null; return null;
}, },
decoration: InputDecoration( decoration: InputDecoration(
labelText: 'Titre du voyage *', labelText: 'Titre du voyage *',
hintText: 'ex: Voyage à Paris', hintText: 'ex: Voyage à Paris',
border: OutlineInputBorder( border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.travel_explore),
),
),
SizedBox(height: 16),
TextFormField(
controller: _descriptionController,
maxLines: 3,
decoration: InputDecoration(
labelText: 'Description',
hintText: 'Décrivez votre voyage...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.description),
),
),
SizedBox(height: 16),
TextFormField(
controller: _locationController,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Destination requise';
}
return null;
},
decoration: InputDecoration(
labelText: 'Destination *',
hintText: 'ex: Paris, France',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.location_on),
),
),
SizedBox(height: 24),
_buildSectionTitle('Dates du voyage'),
SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDateField(
label: 'Date de début *',
date: _startDate,
onTap: () => _selectStartDate(context),
), ),
prefixIcon: Icon(Icons.travel_explore),
), ),
SizedBox(width: 16), ),
Expanded(
child: _buildDateField( SizedBox(height: 16),
label: 'Date de fin *',
date: _endDate, TextFormField(
onTap: () => _selectEndDate(context), controller: _descriptionController,
maxLines: 3,
decoration: InputDecoration(
labelText: 'Description',
hintText: 'Décrivez votre voyage...',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.description),
),
),
SizedBox(height: 16),
TextFormField(
controller: _locationController,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return 'Destination requise';
}
return null;
},
decoration: InputDecoration(
labelText: 'Destination *',
hintText: 'ex: Paris, France',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.location_on),
),
),
SizedBox(height: 24),
_buildSectionTitle('Dates du voyage'),
SizedBox(height: 16),
Row(
children: [
Expanded(
child: _buildDateField(
label: 'Date de début *',
date: _startDate,
onTap: () => _selectStartDate(context),
),
),
SizedBox(width: 16),
Expanded(
child: _buildDateField(
label: 'Date de fin *',
date: _endDate,
onTap: () => _selectEndDate(context),
),
),
],
),
SizedBox(height: 24),
_buildSectionTitle('Budget'),
SizedBox(height: 16),
TextFormField(
controller: _budgetController,
keyboardType: TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
labelText: 'Budget estimé',
hintText: 'ex: 1200.50',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.euro),
suffixText: '',
),
),
SizedBox(height: 24),
_buildSectionTitle('Participants'),
SizedBox(height: 8),
Text(
'Ajoutez les emails des personnes que vous souhaitez inviter',
style: TextStyle(color: Colors.grey[600], fontSize: 14),
),
SizedBox(height: 16),
Row(
children: [
Expanded(
child: TextFormField(
controller: _participantController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email du participant',
hintText: 'ex: ami@email.com',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.person_add),
),
),
),
SizedBox(width: 8),
ElevatedButton(
onPressed: _addParticipant,
style: ElevatedButton.styleFrom(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
padding: EdgeInsets.all(16),
),
child: Icon(Icons.add),
),
],
),
SizedBox(height: 16),
if (_participants.isNotEmpty) ...[
Text(
'Participants ajoutés (${_participants.length})',
style: TextStyle(fontWeight: FontWeight.w500),
),
SizedBox(height: 8),
Container(
width: double.infinity,
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(12),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: _participants
.map(
(email) => Chip(
label: Text(email, style: TextStyle(fontSize: 12)),
deleteIcon: Icon(Icons.close, size: 18),
onDeleted: () => _removeParticipant(email),
backgroundColor: Theme.of(context)
.colorScheme
.primary
.withValues(alpha: 0.1),
),
)
.toList(),
), ),
), ),
], ],
),
SizedBox(height: 24), SizedBox(height: 32),
_buildSectionTitle('Budget'), SizedBox(
SizedBox(height: 16), width: double.infinity,
height: 50,
TextFormField( child: ElevatedButton(
controller: _budgetController, onPressed: _isLoading ? null : () => _saveTrip(userState.user),
keyboardType: TextInputType.numberWithOptions(decimal: true),
decoration: InputDecoration(
labelText: 'Budget estimé',
hintText: 'ex: 1200.50',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.euro),
suffixText: '',
),
),
SizedBox(height: 24),
_buildSectionTitle('Participants'),
SizedBox(height: 8),
Text(
'Ajoutez les emails des personnes que vous souhaitez inviter',
style: TextStyle(color: Colors.grey[600], fontSize: 14),
),
SizedBox(height: 16),
Row(
children: [
Expanded(
child: TextFormField(
controller: _participantController,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
labelText: 'Email du participant',
hintText: 'ex: ami@email.com',
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
prefixIcon: Icon(Icons.person_add),
),
),
),
SizedBox(width: 8),
ElevatedButton(
onPressed: _addParticipant,
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder( shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
), ),
padding: EdgeInsets.all(16),
), ),
child: Icon(Icons.add), child: _isLoading
), ? CircularProgressIndicator(color: Colors.white)
], : Text(
), isEditing ? 'Mettre à jour le voyage' : 'Créer le voyage',
style: TextStyle(
SizedBox(height: 16), fontSize: 16,
fontWeight: FontWeight.bold,
if (_participants.isNotEmpty) ...[ ),
Text(
'Participants ajoutés (${_participants.length})',
style: TextStyle(fontWeight: FontWeight.w500),
),
SizedBox(height: 8),
Container(
width: double.infinity,
padding: EdgeInsets.all(12),
decoration: BoxDecoration(
border: Border.all(color: Colors.grey[300]!),
borderRadius: BorderRadius.circular(12),
),
child: Wrap(
spacing: 8,
runSpacing: 8,
children: _participants
.map(
(email) => Chip(
label: Text(email, style: TextStyle(fontSize: 12)),
deleteIcon: Icon(Icons.close, size: 18),
onDeleted: () => _removeParticipant(email),
backgroundColor: Theme.of(
context,
).colorScheme.primary.withAlpha(25),
), ),
)
.toList(),
), ),
), ),
SizedBox(height: 20),
], ],
),
SizedBox(height: 32),
SizedBox(
width: double.infinity,
height: 50,
child: ElevatedButton(
onPressed: _isLoading ? null : () => _saveTrip(userState.user),
style: ElevatedButton.styleFrom(
backgroundColor: Theme.of(context).colorScheme.primary,
foregroundColor: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
),
child: _isLoading
? CircularProgressIndicator(color: Colors.white)
: Text(
'Créer le voyage',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
),
SizedBox(height: 20),
],
), ),
), ),
), );
); },
}, ),
); );
} }
@@ -300,7 +395,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
final labelColor = isDarkMode ? Colors.white70 : Colors.grey[600]; final labelColor = isDarkMode ? Colors.white70 : Colors.grey[600];
final iconColor = isDarkMode ? Colors.white70 : Colors.grey[600]; final iconColor = isDarkMode ? Colors.white70 : Colors.grey[600];
final placeholderColor = isDarkMode ? Colors.white38 : Colors.grey[500]; final placeholderColor = isDarkMode ? Colors.white38 : Colors.grey[500];
return InkWell( return InkWell(
onTap: onTap, onTap: onTap,
child: Container( child: Container(
@@ -319,9 +414,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
Icon(Icons.calendar_today, size: 16, color: iconColor), Icon(Icons.calendar_today, size: 16, color: iconColor),
SizedBox(width: 8), SizedBox(width: 8),
Text( Text(
date != null date != null ? '${date.day}/${date.month}/${date.year}' : 'Sélectionner',
? '${date.day}/${date.month}/${date.year}'
: 'Sélectionner',
style: TextStyle( style: TextStyle(
fontSize: 16, fontSize: 16,
color: date != null ? textColor : placeholderColor, color: date != null ? textColor : placeholderColor,
@@ -382,18 +475,15 @@ class _CreateTripContentState extends State<CreateTripContent> {
final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$'); final emailRegex = RegExp(r'^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$');
if (!emailRegex.hasMatch(email)) { if (!emailRegex.hasMatch(email)) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('Email invalide')));
SnackBar(content: Text('Email invalide'))
);
} }
return; return;
} }
if (_participants.contains(email)) { if (_participants.contains(email)) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context)
SnackBar(content: Text('Ce participant est déjà ajouté')) .showSnackBar(SnackBar(content: Text('Ce participant est déjà ajouté')));
);
} }
return; return;
} }
@@ -410,6 +500,128 @@ class _CreateTripContentState extends State<CreateTripContent> {
}); });
} }
// Mettre à jour le groupe avec les nouveaux membres
Future<void> _updateGroupMembers(
String tripId,
user_state.UserModel currentUser,
List<Map<String, String>> participantsData,
) async {
try {
final group = await _groupRepository.getGroupByTripId(tripId);
if (group == null) {
_errorService.logError(
'create_trip_content.dart',
'Groupe non trouvé pour le voyage $tripId',
);
return;
}
final newMembers = <GroupMember>[
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 currentMembers = await _groupRepository.getGroupMembers(group.id);
final currentMemberIds = currentMembers.map((m) => m.userId).toSet();
final newMemberIds = newMembers.map((m) => m.userId).toSet();
final membersToAdd = newMembers.where((m) => !currentMemberIds.contains(m.userId)).toList();
final membersToRemove = currentMembers
.where((m) => !newMemberIds.contains(m.userId) && m.role != 'admin')
.toList();
for (final member in membersToAdd) {
context.read<GroupBloc>().add(AddMemberToGroup(group.id, member));
}
for (final member in membersToRemove) {
context.read<GroupBloc>().add(RemoveMemberFromGroup(group.id, member.userId));
}
} catch (e) {
_errorService.logError(
'create_trip_content.dart',
'Erreur lors de la mise à jour du groupe: $e',
);
}
}
// NOUVELLE MÉTHODE : Créer le groupe après la création du voyage
Future<void> _createGroupForTrip(String tripId) async {
try {
final userState = context.read<UserBloc>().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é
createdBy: currentUser.id,
);
final groupMembers = <GroupMember>[
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',
)),
];
context.read<GroupBloc>().add(CreateGroupWithMembers(
group: group,
members: groupMembers,
));
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Voyage et groupe créés 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 groupe: $e',
);
if (mounted) {
setState(() {
_isLoading = false;
});
}
}
}
Future<void> _saveTrip(user_state.UserModel currentUser) async { Future<void> _saveTrip(user_state.UserModel currentUser) async {
if (!_formKey.currentState!.validate()) { if (!_formKey.currentState!.validate()) {
return; return;
@@ -431,14 +643,13 @@ class _CreateTripContentState extends State<CreateTripContent> {
try { try {
final participantsData = await _getParticipantsData(_participants); final participantsData = await _getParticipantsData(_participants);
List<String> participantIds = participantsData.map((p) => p['id'] as String).toList(); List<String> participantIds = participantsData.map((p) => p['id'] as String).toList();
if (!participantIds.contains(currentUser.id)) { if (!participantIds.contains(currentUser.id)) {
participantIds.insert(0, currentUser.id); participantIds.insert(0, currentUser.id);
} }
// Créer le voyage
final trip = Trip( final trip = Trip(
id: '', id: isEditing ? widget.tripToEdit!.id : '',
title: _titleController.text.trim(), title: _titleController.text.trim(),
description: _descriptionController.text.trim(), description: _descriptionController.text.trim(),
location: _locationController.text.trim(), location: _locationController.text.trim(),
@@ -447,42 +658,23 @@ class _CreateTripContentState extends State<CreateTripContent> {
budget: double.tryParse(_budgetController.text) ?? 0.0, budget: double.tryParse(_budgetController.text) ?? 0.0,
createdBy: currentUser.id, createdBy: currentUser.id,
participants: participantIds, participants: participantIds,
createdAt: DateTime.now(), createdAt: isEditing ? widget.tripToEdit!.createdAt : DateTime.now(),
updatedAt: DateTime.now(), updatedAt: DateTime.now(),
); );
context.read<TripBloc>().add(TripCreateRequested(trip: trip)); if (isEditing) {
// Mode mise à jour
context.read<TripBloc>().add(TripUpdateRequested(trip: trip));
// Attendre que le trip soit créé (simplifié) await _updateGroupMembers(
await Future.delayed(Duration(milliseconds: 500)); widget.tripToEdit!.id!,
currentUser,
final group = Group( participantsData,
id: '', );
name: _titleController.text.trim(), } else {
tripId: '', // Mode création - Le groupe sera créé dans le listener TripCreated
createdBy: currentUser.id, context.read<TripBloc>().add(TripCreateRequested(trip: trip));
); }
final groupMembers = <GroupMember>[
GroupMember(
userId: currentUser.id,
firstName: currentUser.prenom,
pseudo: currentUser.prenom, // Par défaut = prénom
role: 'admin',
),
...participantsData.map((p) => GroupMember(
userId: p['id'] as String,
firstName: p['firstName'] as String,
pseudo: p['firstName'] as String, // Par défaut = prénom
role: 'member',
)),
];
context.read<GroupBloc>().add(CreateGroupWithMembers(
group: group,
members: groupMembers,
));
} catch (e) { } catch (e) {
if (mounted) { if (mounted) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -491,9 +683,7 @@ class _CreateTripContentState extends State<CreateTripContent> {
backgroundColor: Colors.red, backgroundColor: Colors.red,
), ),
); );
}
} finally {
if (mounted) {
setState(() { setState(() {
_isLoading = false; _isLoading = false;
}); });
@@ -501,9 +691,6 @@ class _CreateTripContentState extends State<CreateTripContent> {
} }
} }
// ...existing code...
// Récupérer les IDs et prénoms des participants
Future<List<Map<String, String>>> _getParticipantsData(List<String> emails) async { Future<List<Map<String, String>>> _getParticipantsData(List<String> emails) async {
List<Map<String, String>> participantsData = []; List<Map<String, String>> participantsData = [];
@@ -511,10 +698,9 @@ class _CreateTripContentState extends State<CreateTripContent> {
try { try {
final userId = await _userService.getUserIdByEmail(email); final userId = await _userService.getUserIdByEmail(email);
if (userId != null) { if (userId != null) {
// Récupérer le prénom de l'utilisateur
final userDoc = await _userService.getUserById(userId); final userDoc = await _userService.getUserById(userId);
final firstName = userDoc?.prenom ?? 'Utilisateur'; final firstName = userDoc?.prenom ?? 'Utilisateur';
participantsData.add({ participantsData.add({
'id': userId, 'id': userId,
'firstName': firstName, 'firstName': firstName,
@@ -530,7 +716,10 @@ class _CreateTripContentState extends State<CreateTripContent> {
} }
} }
} catch (e) { } catch (e) {
_errorService.logError('Erreur lors de la récupération de l\'utilisateur $email: $e', StackTrace.current); _errorService.logError(
'create_trip_content.dart',
'Erreur lors de la récupération de l\'utilisateur $email: $e',
);
} }
} }

View File

@@ -16,23 +16,31 @@ class HomeContent extends StatefulWidget {
State<HomeContent> createState() => _HomeContentState(); State<HomeContent> createState() => _HomeContentState();
} }
class _HomeContentState extends State<HomeContent> { class _HomeContentState extends State<HomeContent> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Charger les trips quand le widget est initialisé // MODIFIÉ : Attendre un frame avant de charger
_loadTripsIfUserLoaded(); WidgetsBinding.instance.addPostFrameCallback((_) {
_loadTripsIfUserLoaded();
});
} }
void _loadTripsIfUserLoaded() { void _loadTripsIfUserLoaded() {
final userState = context.read<UserBloc>().state; final userState = context.read<UserBloc>().state;
if (userState is UserLoaded) { if (userState is UserLoaded) {
context.read<TripBloc>().add(TripLoadRequested(userId: userState.user.id)); print('🚀 Chargement initial des trips pour ${userState.user.id}');
context.read<TripBloc>().add(LoadTripsByUserId(userId: userState.user.id));
} }
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
super.build(context); // Important pour AutomaticKeepAliveClientMixin
return BlocBuilder<UserBloc, UserState>( return BlocBuilder<UserBloc, UserState>(
builder: (context, userState) { builder: (context, userState) {
if (userState is UserLoading) { if (userState is UserLoading) {
@@ -42,7 +50,7 @@ class _HomeContentState extends State<HomeContent> {
), ),
); );
} }
if (userState is UserError) { if (userState is UserError) {
return Scaffold( return Scaffold(
body: Center( body: Center(
@@ -57,7 +65,7 @@ class _HomeContentState extends State<HomeContent> {
), ),
); );
} }
if (userState is! UserLoaded) { if (userState is! UserLoaded) {
return Scaffold( return Scaffold(
body: Center( body: Center(
@@ -65,14 +73,9 @@ class _HomeContentState extends State<HomeContent> {
), ),
); );
} }
final user = userState.user; final user = userState.user;
// Charger les trips si ce n'est pas déjà fait
if (context.read<TripBloc>().state is TripInitial) {
context.read<TripBloc>().add(TripLoadRequested(userId: user.id));
}
return BlocConsumer<TripBloc, TripState>( return BlocConsumer<TripBloc, TripState>(
listener: (context, tripState) { listener: (context, tripState) {
if (tripState is TripOperationSuccess) { if (tripState is TripOperationSuccess) {
@@ -82,8 +85,6 @@ class _HomeContentState extends State<HomeContent> {
backgroundColor: Colors.green, backgroundColor: Colors.green,
), ),
); );
// Recharger les trips après une opération réussie
context.read<TripBloc>().add(TripLoadRequested(userId: user.id));
} else if (tripState is TripError) { } else if (tripState is TripError) {
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
SnackBar( SnackBar(
@@ -91,62 +92,70 @@ class _HomeContentState extends State<HomeContent> {
backgroundColor: Colors.red, backgroundColor: Colors.red,
), ),
); );
} else if (tripState is TripCreated) {
// Afficher un message de succès temporaire
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text('Voyage en cours de création...'),
backgroundColor: Colors.blue,
duration: Duration(seconds: 1),
),
);
} }
}, },
builder: (context, tripState) { builder: (context, tripState) {
return Scaffold( return Scaffold(
body: RefreshIndicator( body: RefreshIndicator(
onRefresh: () async { onRefresh: () async {
context.read<TripBloc>().add(TripLoadRequested(userId: user.id)); print('🔄 Pull to refresh');
context.read<TripBloc>().add(LoadTripsByUserId(userId: user.id));
// Attendre que le chargement soit terminé
await Future.delayed(Duration(milliseconds: 500));
}, },
child: SingleChildScrollView( child: SingleChildScrollView(
physics: AlwaysScrollableScrollPhysics(), physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
// Header de bienvenue
Text( Text(
'Bonjour ${user.prenom} !', 'Bonjour ${user.prenom} !',
style: TextStyle(fontSize: 28, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 28, fontWeight: FontWeight.bold),
), ),
SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
'Vos voyages', 'Vos voyages',
style: TextStyle(fontSize: 16, color: Colors.grey[600]), style: TextStyle(fontSize: 16, color: Colors.grey[600]),
), ),
SizedBox(height: 20), const SizedBox(height: 20),
// Contenu principal basé sur l'état du TripBloc if (tripState is TripLoading || tripState is TripCreated)
if (tripState is TripLoading)
_buildLoadingState() _buildLoadingState()
else if (tripState is TripError) else if (tripState is TripError)
_buildErrorState(tripState.message, user.id) _buildErrorState(tripState.message, user.id)
else if (tripState is TripLoaded) else if (tripState is TripLoaded)
tripState.trips.isEmpty tripState.trips.isEmpty
? _buildEmptyState() ? _buildEmptyState()
: _buildTripsList(tripState.trips) : _buildTripsList(tripState.trips)
else else
_buildEmptyState(), _buildEmptyState(),
// Espacement en bas pour éviter que le FAB cache le contenu
const SizedBox(height: 80), const SizedBox(height: 80),
], ],
), ),
), ),
), ),
// FloatingActionButton
floatingActionButton: FloatingActionButton( floatingActionButton: FloatingActionButton(
onPressed: () async { onPressed: () async {
final result = await Navigator.push( final result = await Navigator.push(
context, context,
MaterialPageRoute(builder: (context) => CreateTripContent()), MaterialPageRoute(builder: (context) => const CreateTripContent()),
); );
if (result == true) { // AJOUTÉ : Recharger manuellement après retour
// Recharger les trips if (result == true && mounted) {
context.read<TripBloc>().add(TripLoadRequested(userId: user.id)); print('🔄 Retour de création, rechargement...');
context.read<TripBloc>().add(LoadTripsByUserId(userId: user.id));
} }
}, },
backgroundColor: Theme.of(context).colorScheme.primary, backgroundColor: Theme.of(context).colorScheme.primary,
@@ -189,7 +198,7 @@ class _HomeContentState extends State<HomeContent> {
SizedBox(height: 16), SizedBox(height: 16),
ElevatedButton( ElevatedButton(
onPressed: () { onPressed: () {
context.read<TripBloc>().add(TripLoadRequested(userId: userId)); context.read<TripBloc>().add(LoadTripsByUserId(userId: userId));
}, },
child: Text('Réessayer'), child: Text('Réessayer'),
), ),
@@ -205,28 +214,17 @@ class _HomeContentState extends State<HomeContent> {
padding: EdgeInsets.all(32), padding: EdgeInsets.all(32),
child: Column( child: Column(
children: [ children: [
Icon( Icon(Icons.travel_explore, size: 80, color: Colors.grey[400]),
Icons.travel_explore,
size: 64,
color: Colors.grey[400],
),
SizedBox(height: 16), SizedBox(height: 16),
Text( Text(
'Aucun voyage pour le moment', 'Aucun voyage',
style: TextStyle( style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
fontSize: 18,
fontWeight: FontWeight.w500,
color: Colors.grey[600],
),
), ),
SizedBox(height: 8), SizedBox(height: 8),
Text( Text(
'Créez votre premier voyage en appuyant sur le bouton +', 'Créez votre premier voyage en appuyant sur le bouton +',
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(fontSize: 14, color: Colors.grey[600]),
fontSize: 14,
color: Colors.grey[500],
),
), ),
], ],
), ),
@@ -236,205 +234,127 @@ class _HomeContentState extends State<HomeContent> {
Widget _buildTripsList(List<Trip> trips) { Widget _buildTripsList(List<Trip> trips) {
return Column( return Column(
children: trips.map((trip) => _buildTravelCard(trip)).toList(), children: trips.map((trip) => _buildTripCard(trip)).toList(),
); );
} }
Widget _buildTravelCard(Trip trip) { Widget _buildTripCard(Trip trip) {
final colors = [Colors.blue, Colors.orange, Colors.green, Colors.purple, Colors.red];
final color = colors[trip.title.hashCode.abs() % colors.length];
final isDarkMode = Theme.of(context).brightness == Brightness.dark; final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final secondaryTextColor = isDarkMode ? Colors.white70 : Colors.grey[700]; final textColor = isDarkMode ? Colors.white : Colors.black;
final iconColor = isDarkMode ? Colors.white70 : Colors.grey[600]; final subtextColor = isDarkMode ? Colors.white70 : Colors.grey[600];
return Card( return Card(
elevation: 4, margin: EdgeInsets.only(bottom: 12),
margin: const EdgeInsets.only(bottom: 16), elevation: 2,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)), shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: InkWell( child: InkWell(
onTap: () { onTap: () async {
Navigator.push( // AJOUTÉ : Recharger après retour des détails
final result = await Navigator.push(
context, context,
MaterialPageRoute(builder: (context) => ShowTripDetailsContent(trip: trip)), MaterialPageRoute(
builder: (context) => ShowTripDetailsContent(trip: trip),
),
); );
if (result == true && mounted) {
final userState = context.read<UserBloc>().state;
if (userState is UserLoaded) {
print('🔄 Retour des détails, rechargement...');
context.read<TripBloc>().add(LoadTripsByUserId(userId: userState.user.id));
}
}
}, },
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
child: Column( child: Padding(
crossAxisAlignment: CrossAxisAlignment.start, padding: EdgeInsets.all(16),
children: [ child: Column(
// Image d'en-tête avec titre overlay crossAxisAlignment: CrossAxisAlignment.start,
Container( children: [
height: 150, Row(
decoration: BoxDecoration(
borderRadius: const BorderRadius.vertical(top: Radius.circular(12)),
gradient: LinearGradient(
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
colors: [
color.withValues(alpha: 0.7),
color.withValues(alpha: 0.9),
],
),
),
child: Stack(
children: [ children: [
Container( Expanded(
width: double.infinity,
decoration: BoxDecoration(
borderRadius: const BorderRadius.vertical(
top: Radius.circular(12),
),
color: color.withValues(alpha: 0.3),
),
),
Positioned(
bottom: 16,
left: 16,
right: 16,
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
Text( Text(
trip.title, trip.title,
style: const TextStyle( style: TextStyle(
fontSize: 20, fontSize: 18,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,
color: Colors.white, color: textColor,
), ),
), ),
const SizedBox(height: 4), SizedBox(height: 4),
Row( Row(
children: [ children: [
const Icon( Icon(Icons.location_on, size: 16, color: subtextColor),
Icons.location_on, SizedBox(width: 4),
color: Colors.white, Text(
size: 16, trip.location,
), style: TextStyle(color: subtextColor),
const SizedBox(width: 4),
Expanded(
child: Text(
trip.location,
style: const TextStyle(
fontSize: 14,
color: Colors.white,
),
overflow: TextOverflow.ellipsis,
),
), ),
], ],
), ),
], ],
), ),
), ),
], Container(
), padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
), decoration: BoxDecoration(
color: _getStatusColor(trip).withOpacity(0.2),
// Contenu de la carte borderRadius: BorderRadius.circular(12),
Padding(
padding: EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Description
if (trip.description.isNotEmpty) ...[
Text(
trip.description,
style: TextStyle(
fontSize: 14,
color: secondaryTextColor,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
), ),
SizedBox(height: 12), child: Text(
], _getStatusText(trip),
style: TextStyle(
// Dates color: _getStatusColor(trip),
Row( fontWeight: FontWeight.bold,
children: [ fontSize: 12,
Icon(
Icons.calendar_today,
size: 16,
color: iconColor,
), ),
SizedBox(width: 8), ),
Text(
'${trip.startDate.day}/${trip.startDate.month}/${trip.startDate.year} - ${trip.endDate.day}/${trip.endDate.month}/${trip.endDate.year}',
style: TextStyle(
fontSize: 14,
color: iconColor,
fontWeight: FontWeight.w500,
),
),
],
),
SizedBox(height: 12),
// Participants
Row(
children: [
Icon(Icons.group, size: 16, color: iconColor),
SizedBox(width: 8),
Text(
'${trip.participants.length} participant${trip.participants.length > 1 ? 's' : ''}',
style: TextStyle(
fontSize: 14,
color: iconColor,
fontWeight: FontWeight.w500,
),
),
],
),
SizedBox(height: 12),
// Budget et statut
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
if (trip.budget! > 0)
Row(
children: [
Icon(Icons.euro, size: 16, color: iconColor),
SizedBox(width: 8),
Text(
'Budget: ${trip.budget!.toStringAsFixed(2)}',
style: TextStyle(
fontSize: 14,
color: iconColor,
fontWeight: FontWeight.w500,
),
),
],
),
Container(
padding: EdgeInsets.symmetric(
horizontal: 8,
vertical: 4,
),
decoration: BoxDecoration(
color: _getStatusColor(trip).withValues(alpha: 0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
_getStatusText(trip),
style: TextStyle(
fontSize: 12,
color: _getStatusColor(trip),
fontWeight: FontWeight.w500,
),
),
),
],
), ),
], ],
), ),
), SizedBox(height: 12),
], Row(
children: [
Icon(Icons.calendar_today, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${_formatDate(trip.startDate)} - ${_formatDate(trip.endDate)}',
style: TextStyle(fontSize: 14, color: subtextColor),
),
],
),
if (trip.budget != null) ...[
SizedBox(height: 8),
Row(
children: [
Icon(Icons.euro, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${trip.budget!.toStringAsFixed(2)}',
style: TextStyle(fontSize: 14, color: subtextColor),
),
],
),
],
SizedBox(height: 8),
Row(
children: [
Icon(Icons.people, size: 16, color: subtextColor),
SizedBox(width: 4),
Text(
'${trip.participants.length} participant${trip.participants.length > 1 ? 's' : ''}',
style: TextStyle(fontSize: 14, color: subtextColor),
),
],
),
],
),
), ),
), ),
); );
@@ -442,23 +362,27 @@ class _HomeContentState extends State<HomeContent> {
Color _getStatusColor(Trip trip) { Color _getStatusColor(Trip trip) {
final now = DateTime.now(); final now = DateTime.now();
if (trip.endDate.isBefore(now)) { if (now.isBefore(trip.startDate)) {
return Colors.grey;
} else if (trip.startDate.isBefore(now) && trip.endDate.isAfter(now)) {
return Colors.green;
} else {
return Colors.blue; return Colors.blue;
} else if (now.isAfter(trip.endDate)) {
return Colors.grey;
} else {
return Colors.green;
} }
} }
String _getStatusText(Trip trip) { String _getStatusText(Trip trip) {
final now = DateTime.now(); final now = DateTime.now();
if (trip.endDate.isBefore(now)) { if (now.isBefore(trip.startDate)) {
return 'Terminé';
} else if (trip.startDate.isBefore(now) && trip.endDate.isAfter(now)) {
return 'En cours';
} else {
return 'À venir'; return 'À venir';
} else if (now.isAfter(trip.endDate)) {
return 'Terminé';
} else {
return 'En cours';
} }
} }
}
String _formatDate(DateTime date) {
return '${date.day}/${date.month}/${date.year}';
}
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:travel_mate/components/home/create_trip_content.dart';
import 'package:travel_mate/data/models/trip.dart'; import 'package:travel_mate/data/models/trip.dart';
class ShowTripDetailsContent extends StatefulWidget { class ShowTripDetailsContent extends StatefulWidget {
@@ -12,7 +13,7 @@ class ShowTripDetailsContent extends StatefulWidget {
class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> { class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// Détecter le thème actuel
final isDarkMode = Theme.of(context).brightness == Brightness.dark; final isDarkMode = Theme.of(context).brightness == Brightness.dark;
final textColor = isDarkMode ? Colors.white : Colors.black; final textColor = isDarkMode ? Colors.white : Colors.black;
final secondaryTextColor = isDarkMode ? Colors.white70 : Colors.grey[600]; final secondaryTextColor = isDarkMode ? Colors.white70 : Colors.grey[600];
@@ -85,8 +86,20 @@ class _ShowTripDetailsContentState extends State<ShowTripDetailsContent> {
width: double.infinity, width: double.infinity,
height: 50, height: 50,
child: ElevatedButton( child: ElevatedButton(
onPressed: () { onPressed: () async {
// Handle button press final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => CreateTripContent(
tripToEdit: widget.trip,
),
),
);
if (result == true && mounted) {
Navigator.pop(context, true); // Retour avec flag
}
}, },
style: ElevatedButton.styleFrom( style: ElevatedButton.styleFrom(
backgroundColor: Color.fromARGB(255, 0, 123, 255), backgroundColor: Color.fromARGB(255, 0, 123, 255),

View File

@@ -1,4 +1,5 @@
import 'dart:convert'; import 'dart:convert';
import 'package:cloud_firestore/cloud_firestore.dart';
class Trip { class Trip {
final String? id; final String? id;
@@ -9,10 +10,10 @@ class Trip {
final DateTime endDate; final DateTime endDate;
final double? budget; final double? budget;
final List<String> participants; final List<String> participants;
final String createdBy; // ID de l'utilisateur créateur final String createdBy;
final DateTime createdAt; final DateTime createdAt;
final DateTime updatedAt; final DateTime updatedAt;
final String status; // 'draft', 'active', 'completed', 'cancelled' final String status;
Trip({ Trip({
this.id, this.id,
@@ -29,74 +30,71 @@ class Trip {
this.status = 'draft', this.status = 'draft',
}); });
// Constructeur pour créer un Trip depuis un Map (utile pour Firebase) // NOUVELLE MÉTHODE HELPER pour convertir n'importe quel format de date
factory Trip.fromMap(Map<String, dynamic> map) { static DateTime _parseDateTime(dynamic value) {
return Trip( if (value == null) return DateTime.now();
id: map['id'],
title: map['title'] ?? '', // Si c'est déjà un Timestamp Firebase
description: map['description'] ?? '', if (value is Timestamp) {
location: map['location'] ?? '', return value.toDate();
startDate: _parseDateTime(map['startDate']),
endDate: _parseDateTime(map['endDate']),
budget: map['budget']?.toDouble(),
participants: List<String>.from(map['participants'] ?? []),
createdBy: map['createdBy'] ?? '',
createdAt: _parseDateTime(map['createdAt']),
updatedAt: _parseDateTime(map['updatedAt']),
status: map['status'] ?? 'draft',
);
}
// Méthode helper pour parser les dates depuis différents formats
static DateTime _parseDateTime(dynamic dateValue) {
if (dateValue == null) {
return DateTime.now();
} }
if (dateValue is DateTime) { // Si c'est un int (millisecondes depuis epoch)
return dateValue; if (value is int) {
return DateTime.fromMillisecondsSinceEpoch(value);
} }
if (dateValue is String) { // Si c'est un String (ISO 8601)
try { if (value is String) {
// Essayer de parser comme ISO 8601 return DateTime.parse(value);
return DateTime.parse(dateValue);
} catch (e) {
return DateTime.now();
}
} }
if (dateValue is int) { // Si c'est déjà un DateTime
try { if (value is DateTime) {
// Traiter comme millisecondes return value;
return DateTime.fromMillisecondsSinceEpoch(dateValue);
} catch (e) {
return DateTime.now();
}
} }
// Par défaut
return DateTime.now(); return DateTime.now();
} }
// Constructeur pour créer un Trip depuis JSON // Constructeur pour créer un Trip depuis un Map (utile pour Firebase)
factory Trip.fromJson(String jsonStr) { factory Trip.fromMap(Map<String, dynamic> map, String id) {
Map<String, dynamic> map = json.decode(jsonStr); try {
return Trip.fromMap(map); return Trip(
id: id,
title: map['title'] as String? ?? '',
description: map['description'] as String? ?? '',
location: map['location'] as String? ?? '',
startDate: _parseDateTime(map['startDate']),
endDate: _parseDateTime(map['endDate']),
budget: (map['budget'] as num?)?.toDouble(),
createdBy: map['createdBy'] as String? ?? '',
participants: List<String>.from(map['participants'] as List? ?? []),
createdAt: _parseDateTime(map['createdAt']),
updatedAt: _parseDateTime(map['updatedAt']),
status: map['status'] as String? ?? 'draft',
);
} catch (e) {
print('❌ Erreur parsing Trip: $e');
print('Map reçue: $map');
rethrow;
}
} }
// Méthode pour convertir un Trip en Map (utile pour Firebase) // MODIFIÉ : Convertir en Map avec Timestamp pour Firestore
Map<String, dynamic> toMap() { Map<String, dynamic> toMap() {
return { return {
'id': id,
'title': title, 'title': title,
'description': description, 'description': description,
'location': location, 'location': location,
'startDate': startDate.millisecondsSinceEpoch, 'startDate': Timestamp.fromDate(startDate),
'endDate': endDate.millisecondsSinceEpoch, 'endDate': Timestamp.fromDate(endDate),
'budget': budget, 'budget': budget,
'participants': participants, 'participants': participants,
'createdBy': createdBy, 'createdBy': createdBy,
'createdAt': createdAt.millisecondsSinceEpoch, 'createdAt': Timestamp.fromDate(createdAt),
'updatedAt': updatedAt.millisecondsSinceEpoch, 'updatedAt': Timestamp.fromDate(updatedAt),
'status': status, 'status': status,
}; };
} }
@@ -166,12 +164,12 @@ class Trip {
// Méthode pour obtenir le budget par participant // Méthode pour obtenir le budget par participant
double? get budgetPerParticipant { double? get budgetPerParticipant {
if (budget == null || participants.isEmpty) return null; if (budget == null || participants.isEmpty) return null;
return budget! / (participants.length + 1); // +1 pour le créateur return budget! / (participants.length + 1);
} }
// Méthode pour obtenir le nombre total de participants (incluant le créateur) // Méthode pour obtenir le nombre total de participants (incluant le créateur)
int get totalParticipants { int get totalParticipants {
return participants.length + 1; // +1 pour le créateur return participants.length + 1;
} }
// Méthode pour formater les dates // Méthode pour formater les dates
@@ -197,7 +195,7 @@ class Trip {
@override @override
String toString() { String toString() {
return 'Trip(id: $id, title: $title, location: $location, dates: $formattedDates, participants: ${participants.length})'; return 'Trip(id: $id, title: $title, location: $location, status: $status)';
} }
@override @override
@@ -208,4 +206,4 @@ class Trip {
@override @override
int get hashCode => id.hashCode; int get hashCode => id.hashCode;
} }

View File

@@ -63,7 +63,7 @@ class MyApp extends StatelessWidget {
), ),
BlocProvider( BlocProvider(
create: (context) => create: (context) =>
TripBloc(tripRepository: context.read<TripRepository>()), TripBloc(context.read<TripRepository>()),
), ),
BlocProvider(create: (context) => UserBloc()), BlocProvider(create: (context) => UserBloc()),
], ],

View File

@@ -108,7 +108,6 @@ class _HomePageState extends State<HomePage> {
if (shouldLogout != true || !mounted) return; if (shouldLogout != true || !mounted) return;
try { try {
context.read<TripBloc>().add(ResetTrips());
context.read<UserBloc>().add(UserLoggedOut()); context.read<UserBloc>().add(UserLoggedOut());
_pageCache.clear(); _pageCache.clear();
context.read<AuthBloc>().add(AuthSignOutRequested()); context.read<AuthBloc>().add(AuthSignOutRequested());

View File

@@ -2,112 +2,107 @@ import 'package:cloud_firestore/cloud_firestore.dart';
import '../data/models/trip.dart'; import '../data/models/trip.dart';
class TripRepository { class TripRepository {
final FirebaseFirestore _firestore; final FirebaseFirestore _firestore = FirebaseFirestore.instance;
TripRepository({FirebaseFirestore? firestore}) CollectionReference get _tripsCollection => _firestore.collection('trips');
: _firestore = firestore ?? FirebaseFirestore.instance;
// Créer un voyage // Récupérer tous les voyages d'un utilisateur
Future<Trip> createTrip(Trip trip) async { Stream<List<Trip>> getTripsByUserId(String userId) {
print('🔍 Chargement des trips pour userId: $userId');
try { try {
final docRef = await _firestore.collection('trips').add(trip.toMap()); return _tripsCollection
final createdTrip = trip.copyWith(id: docRef.id); .where('participants', arrayContains: userId)
.snapshots()
// Mettre à jour avec l'ID généré .map((snapshot) {
await docRef.update({'id': docRef.id}); print('📦 Snapshot reçu: ${snapshot.docs.length} documents');
return createdTrip; final trips = snapshot.docs
.map((doc) {
try {
final data = doc.data() as Map<String, dynamic>;
print('📄 Document ${doc.id}: ${data.keys.toList()}');
return Trip.fromMap(data, doc.id);
} catch (e) {
print('❌ Erreur parsing trip ${doc.id}: $e');
return null;
}
})
.whereType<Trip>()
.toList();
print('${trips.length} trips parsés avec succès');
return trips;
});
} catch (e) { } catch (e) {
print('❌ Erreur getTripsByUserId: $e');
throw Exception('Erreur lors de la récupération des voyages: $e');
}
}
// Créer un voyage et retourner son ID
Future<String> createTrip(Trip trip) async {
try {
print('📝 Création du voyage: ${trip.title}');
final tripData = trip.toMap();
// Ne pas modifier les timestamps ici, ils sont déjà au bon format
final docRef = await _tripsCollection.add(tripData);
print('✅ Voyage créé avec ID: ${docRef.id}');
return docRef.id;
} catch (e) {
print('❌ Erreur création voyage: $e');
throw Exception('Erreur lors de la création du voyage: $e'); throw Exception('Erreur lors de la création du voyage: $e');
} }
} }
// Récupérer les voyages d'un utilisateur // Récupérer un voyage par son ID
Stream<List<Trip>> getUserTrips(String userId) {
return _firestore
.collection('trips')
.where('createdBy', isEqualTo: userId)
.snapshots()
.map((snapshot) {
return snapshot.docs.map((doc) {
final data = doc.data();
return Trip.fromMap({...data, 'id': doc.id});
}).toList();
});
}
// Récupérer les voyages où l'utilisateur est participant
Stream<List<Trip>> getSharedTrips(String userId) {
return _firestore
.collection('trips')
.where('participants', arrayContains: userId)
.snapshots()
.map((snapshot) {
return snapshot.docs.map((doc) {
final data = doc.data();
return Trip.fromMap({...data, 'id': doc.id});
}).toList();
});
}
// Récupérer un voyage par ID
Future<Trip?> getTripById(String tripId) async { Future<Trip?> getTripById(String tripId) async {
try { try {
final doc = await _firestore.collection('trips').doc(tripId).get(); final doc = await _tripsCollection.doc(tripId).get();
if (doc.exists) {
final data = doc.data() as Map<String, dynamic>; if (!doc.exists) {
return Trip.fromMap({...data, 'id': doc.id}); print('⚠️ Voyage $tripId non trouvé');
return null;
} }
return null;
return Trip.fromMap(doc.data() as Map<String, dynamic>, doc.id);
} catch (e) { } catch (e) {
print('❌ Erreur getTripById: $e');
throw Exception('Erreur lors de la récupération du voyage: $e'); throw Exception('Erreur lors de la récupération du voyage: $e');
} }
} }
// Mettre à jour un voyage // Mettre à jour un voyage
Future<bool> updateTrip(Trip trip) async { Future<void> updateTrip(String tripId, Trip trip) async {
try { try {
await _firestore print('📝 Mise à jour du voyage: $tripId');
.collection('trips')
.doc(trip.id) final tripData = trip.toMap();
.update(trip.toMap()); // Mettre à jour le timestamp de modification
return true; tripData['updatedAt'] = Timestamp.now();
await _tripsCollection.doc(tripId).update(tripData);
print('✅ Voyage $tripId mis à jour');
} catch (e) { } catch (e) {
print('❌ Erreur mise à jour voyage: $e');
throw Exception('Erreur lors de la mise à jour du voyage: $e'); throw Exception('Erreur lors de la mise à jour du voyage: $e');
} }
} }
// Supprimer un voyage // Supprimer un voyage
Future<bool> deleteTrip(String tripId) async { Future<void> deleteTrip(String tripId) async {
try { try {
await _firestore.collection('trips').doc(tripId).delete(); print('🗑️ Suppression du voyage: $tripId');
return true;
await _tripsCollection.doc(tripId).delete();
print('✅ Voyage $tripId supprimé');
} catch (e) { } catch (e) {
print('❌ Erreur suppression voyage: $e');
throw Exception('Erreur lors de la suppression du voyage: $e'); throw Exception('Erreur lors de la suppression du voyage: $e');
} }
} }
// Ajouter un participant
Future<bool> addParticipant(String tripId, String participantEmail) async {
try {
await _firestore.collection('trips').doc(tripId).update({
'participants': FieldValue.arrayUnion([participantEmail])
});
return true;
} catch (e) {
throw Exception('Erreur lors de l\'ajout du participant: $e');
}
}
// Retirer un participant
Future<bool> removeParticipant(String tripId, String participantEmail) async {
try {
await _firestore.collection('trips').doc(tripId).update({
'participants': FieldValue.arrayRemove([participantEmail])
});
return true;
} catch (e) {
throw Exception('Erreur lors du retrait du participant: $e');
}
}
} }

View File

@@ -17,7 +17,7 @@ class TripService {
return querySnapshot.docs.map((doc) { return querySnapshot.docs.map((doc) {
final data = doc.data() as Map<String, dynamic>; final data = doc.data() as Map<String, dynamic>;
return Trip.fromMap({...data, 'id': doc.id}); return Trip.fromMap({...data, 'id': doc.id}, doc.id);
}).toList(); }).toList();
} catch (e) { } catch (e) {
_errorService.logError('Erreur lors du chargement des voyages: $e', StackTrace.current); _errorService.logError('Erreur lors du chargement des voyages: $e', StackTrace.current);
@@ -176,7 +176,7 @@ class TripService {
processedData['description'] = processedData['description'] ?? ''; processedData['description'] = processedData['description'] ?? '';
processedData['status'] = processedData['status'] ?? 'draft'; processedData['status'] = processedData['status'] ?? 'draft';
final trip = Trip.fromMap(processedData); final trip = Trip.fromMap(processedData, docId);
return trip; return trip;
} catch (e, stackTrace) { } catch (e, stackTrace) {
@@ -224,7 +224,7 @@ class TripService {
if (doc.exists) { if (doc.exists) {
final data = doc.data() as Map<String, dynamic>; final data = doc.data() as Map<String, dynamic>;
return Trip.fromMap({...data, 'id': doc.id}); return Trip.fromMap({...data, 'id': doc.id}, doc.id);
} }
return null; return null;
} catch (e) { } catch (e) {