Clean project: remove test files, debug logs, and add documentation

This commit is contained in:
dahoud
2025-10-05 13:41:33 +00:00
parent 96a17eadbd
commit 291847924c
438 changed files with 65754 additions and 32713 deletions

View File

@@ -0,0 +1,406 @@
/// Page de détails d'un événement
library event_detail_page;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/evenements_bloc.dart';
import '../../bloc/evenements_state.dart';
import '../../data/models/evenement_model.dart';
import '../widgets/inscription_event_dialog.dart';
import '../widgets/edit_event_dialog.dart';
class EventDetailPage extends StatelessWidget {
final EvenementModel evenement;
const EventDetailPage({
super.key,
required this.evenement,
});
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Détails de l\'événement'),
backgroundColor: const Color(0xFF3B82F6),
foregroundColor: Colors.white,
actions: [
IconButton(
icon: const Icon(Icons.edit),
onPressed: () => _showEditDialog(context),
),
],
),
body: BlocBuilder<EvenementsBloc, EvenementsState>(
builder: (context, state) {
return SingleChildScrollView(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildHeader(),
_buildInfoSection(),
_buildDescriptionSection(),
if (evenement.lieu != null) _buildLocationSection(),
_buildParticipantsSection(),
const SizedBox(height: 80), // Espace pour le bouton flottant
],
),
);
},
),
floatingActionButton: _buildInscriptionButton(context),
);
}
Widget _buildHeader() {
return Container(
width: double.infinity,
padding: const EdgeInsets.all(24),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
const Color(0xFF3B82F6),
const Color(0xFF3B82F6).withOpacity(0.8),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.2),
borderRadius: BorderRadius.circular(20),
),
child: Text(
_getTypeLabel(evenement.type),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
const SizedBox(height: 12),
Text(
evenement.titre,
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Row(
children: [
Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: _getStatutColor(evenement.statut),
borderRadius: BorderRadius.circular(4),
),
child: Text(
_getStatutLabel(evenement.statut),
style: const TextStyle(
color: Colors.white,
fontSize: 12,
fontWeight: FontWeight.bold,
),
),
),
],
),
],
),
);
}
Widget _buildInfoSection() {
return Container(
padding: const EdgeInsets.all(16),
child: Column(
children: [
_buildInfoRow(
Icons.calendar_today,
'Date de début',
_formatDate(evenement.dateDebut),
),
const Divider(),
_buildInfoRow(
Icons.event,
'Date de fin',
_formatDate(evenement.dateFin),
),
if (evenement.maxParticipants != null) ...[
const Divider(),
_buildInfoRow(
Icons.people,
'Places',
'${evenement.participantsActuels} / ${evenement.maxParticipants}',
),
],
if (evenement.organisateurNom != null) ...[
const Divider(),
_buildInfoRow(
Icons.person,
'Organisateur',
evenement.organisateurNom!,
),
],
],
),
);
}
Widget _buildInfoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
child: Row(
children: [
Icon(icon, color: const Color(0xFF3B82F6), size: 20),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 12,
color: Colors.grey[600],
),
),
const SizedBox(height: 2),
Text(
value,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w500,
),
),
],
),
),
],
),
);
}
Widget _buildDescriptionSection() {
if (evenement.description == null) return const SizedBox.shrink();
return Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Description',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Text(
evenement.description!,
style: const TextStyle(fontSize: 14, height: 1.5),
),
],
),
);
}
Widget _buildLocationSection() {
return Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Lieu',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 8),
Row(
children: [
const Icon(Icons.location_on, color: Color(0xFF3B82F6)),
const SizedBox(width: 8),
Expanded(
child: Text(
evenement.lieu!,
style: const TextStyle(fontSize: 14),
),
),
],
),
],
),
);
}
Widget _buildParticipantsSection() {
return Container(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
const Text(
'Participants',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
Text(
'${evenement.participantsActuels} inscrits',
style: TextStyle(
fontSize: 14,
color: Colors.grey[600],
),
),
],
),
const SizedBox(height: 12),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey[100],
borderRadius: BorderRadius.circular(8),
),
child: const Row(
children: [
Icon(Icons.info_outline, size: 20),
SizedBox(width: 8),
Expanded(
child: Text(
'La liste des participants est visible uniquement pour les organisateurs',
style: TextStyle(fontSize: 12),
),
),
],
),
),
],
),
);
}
Widget _buildInscriptionButton(BuildContext context) {
const isInscrit = false; // TODO: Vérifier si l'utilisateur est inscrit
final placesRestantes = (evenement.maxParticipants ?? 0) -
evenement.participantsActuels;
final isComplet = placesRestantes <= 0 && evenement.maxParticipants != null;
return FloatingActionButton.extended(
onPressed: (isInscrit || !isComplet)
? () => _showInscriptionDialog(context, isInscrit)
: null,
backgroundColor: isInscrit ? Colors.red : const Color(0xFF3B82F6),
icon: Icon(isInscrit ? Icons.cancel : Icons.check),
label: Text(
isInscrit ? 'Se désinscrire' : (isComplet ? 'Complet' : 'S\'inscrire'),
),
);
}
void _showInscriptionDialog(BuildContext context, bool isInscrit) {
showDialog(
context: context,
builder: (context) => BlocProvider.value(
value: context.read<EvenementsBloc>(),
child: InscriptionEventDialog(
evenement: evenement,
isInscrit: isInscrit,
),
),
);
}
void _showEditDialog(BuildContext context) {
showDialog(
context: context,
builder: (context) => BlocProvider.value(
value: context.read<EvenementsBloc>(),
child: EditEventDialog(evenement: evenement),
),
);
}
String _formatDate(DateTime date) {
final months = [
'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'
];
return '${date.day} ${months[date.month - 1]} ${date.year} à ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
}
String _getTypeLabel(TypeEvenement type) {
switch (type) {
case TypeEvenement.assembleeGenerale:
return 'Assemblée Générale';
case TypeEvenement.reunion:
return 'Réunion';
case TypeEvenement.formation:
return 'Formation';
case TypeEvenement.conference:
return 'Conférence';
case TypeEvenement.atelier:
return 'Atelier';
case TypeEvenement.seminaire:
return 'Séminaire';
case TypeEvenement.evenementSocial:
return 'Événement Social';
case TypeEvenement.manifestation:
return 'Manifestation';
case TypeEvenement.celebration:
return 'Célébration';
case TypeEvenement.autre:
return 'Autre';
}
}
String _getStatutLabel(StatutEvenement statut) {
switch (statut) {
case StatutEvenement.planifie:
return 'Planifié';
case StatutEvenement.confirme:
return 'Confirmé';
case StatutEvenement.enCours:
return 'En cours';
case StatutEvenement.termine:
return 'Terminé';
case StatutEvenement.annule:
return 'Annulé';
case StatutEvenement.reporte:
return 'Reporté';
}
}
Color _getStatutColor(StatutEvenement statut) {
switch (statut) {
case StatutEvenement.planifie:
return Colors.blue;
case StatutEvenement.confirme:
return Colors.green;
case StatutEvenement.enCours:
return Colors.orange;
case StatutEvenement.termine:
return Colors.grey;
case StatutEvenement.annule:
return Colors.red;
case StatutEvenement.reporte:
return Colors.purple;
}
}
}

View File

@@ -3,7 +3,6 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/auth/bloc/auth_bloc.dart';
import '../../../../core/auth/models/user_role.dart';
import '../../../../core/design_system/tokens/tokens.dart';
/// Page de gestion des événements - Interface sophistiquée et exhaustive
///
@@ -763,10 +762,10 @@ class _EventsPageState extends State<EventsPage> with TickerProviderStateMixin {
// Informations principales
Row(
children: [
Icon(
const Icon(
Icons.calendar_today,
size: 14,
color: const Color(0xFF6B7280),
color: Color(0xFF6B7280),
),
const SizedBox(width: 4),
Text(
@@ -777,10 +776,10 @@ class _EventsPageState extends State<EventsPage> with TickerProviderStateMixin {
),
),
const SizedBox(width: 12),
Icon(
const Icon(
Icons.location_on,
size: 14,
color: const Color(0xFF6B7280),
color: Color(0xFF6B7280),
),
const SizedBox(width: 4),
Expanded(
@@ -818,10 +817,10 @@ class _EventsPageState extends State<EventsPage> with TickerProviderStateMixin {
),
),
const Spacer(),
Icon(
const Icon(
Icons.people,
size: 14,
color: const Color(0xFF6B7280),
color: Color(0xFF6B7280),
),
const SizedBox(width: 4),
Text(
@@ -869,7 +868,7 @@ class _EventsPageState extends State<EventsPage> with TickerProviderStateMixin {
icon = Icons.event_note;
}
return Container(
return SizedBox(
height: 400,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,

View File

@@ -0,0 +1,601 @@
/// Page des événements avec données injectées depuis le BLoC
///
/// Cette version de EventsPage accepte les données en paramètre
/// au lieu d'utiliser des données mock hardcodées.
library events_page_connected;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../../../core/auth/bloc/auth_bloc.dart';
import '../../../../core/auth/models/user_role.dart';
import '../../../../core/utils/logger.dart';
/// Page de gestion des événements avec données injectées
class EventsPageWithData extends StatefulWidget {
/// Liste des événements à afficher
final List<Map<String, dynamic>> events;
/// Nombre total d'événements
final int totalCount;
/// Page actuelle
final int currentPage;
/// Nombre total de pages
final int totalPages;
const EventsPageWithData({
super.key,
required this.events,
required this.totalCount,
required this.currentPage,
required this.totalPages,
});
@override
State<EventsPageWithData> createState() => _EventsPageWithDataState();
}
class _EventsPageWithDataState extends State<EventsPageWithData>
with TickerProviderStateMixin {
// Controllers
final TextEditingController _searchController = TextEditingController();
late TabController _tabController;
// État
String _searchQuery = '';
String _selectedFilter = 'Tous';
@override
void initState() {
super.initState();
_tabController = TabController(length: 5, vsync: this);
AppLogger.info('EventsPageWithData initialisée avec ${widget.events.length} événements');
}
@override
void dispose() {
_searchController.dispose();
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return BlocBuilder<AuthBloc, AuthState>(
builder: (context, state) {
if (state is! AuthAuthenticated) {
return Container(
color: const Color(0xFFF8F9FA),
child: const Center(child: CircularProgressIndicator()),
);
}
final canManageEvents = _canManageEvents(state.effectiveRole);
return Container(
color: const Color(0xFFF8F9FA),
child: Column(
children: [
// Métriques
_buildEventMetrics(),
// Recherche et filtres
_buildSearchAndFilters(canManageEvents),
// Onglets
_buildTabBar(),
// Contenu
Expanded(
child: TabBarView(
controller: _tabController,
children: [
_buildAllEventsView(),
_buildUpcomingEventsView(),
_buildOngoingEventsView(),
_buildPastEventsView(),
_buildCalendarView(),
],
),
),
// Pagination
if (widget.totalPages > 1) _buildPagination(),
],
),
);
},
);
}
/// Métriques des événements
Widget _buildEventMetrics() {
final upcoming = widget.events.where((e) => e['estAVenir'] == true).length;
final ongoing = widget.events.where((e) => e['estEnCours'] == true).length;
final past = widget.events.where((e) => e['estPasse'] == true).length;
return Container(
padding: const EdgeInsets.all(12),
child: Row(
children: [
Expanded(
child: _buildMetricCard(
'À venir',
upcoming.toString(),
Icons.event_available,
const Color(0xFF00B894),
),
),
const SizedBox(width: 8),
Expanded(
child: _buildMetricCard(
'En cours',
ongoing.toString(),
Icons.event,
const Color(0xFF74B9FF),
),
),
const SizedBox(width: 8),
Expanded(
child: _buildMetricCard(
'Passés',
past.toString(),
Icons.event_busy,
const Color(0xFF636E72),
),
),
],
),
);
}
Widget _buildMetricCard(String label, String value, IconData icon, Color color) {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 4,
offset: const Offset(0, 2),
),
],
),
child: Column(
children: [
Icon(icon, color: color, size: 24),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold,
color: color,
),
),
Text(
label,
style: const TextStyle(fontSize: 10, color: Color(0xFF636E72)),
),
],
),
);
}
/// Recherche et filtres
Widget _buildSearchAndFilters(bool canManageEvents) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
child: Row(
children: [
Expanded(
child: TextField(
controller: _searchController,
decoration: InputDecoration(
hintText: 'Rechercher un événement...',
prefixIcon: const Icon(Icons.search, size: 20),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(8),
borderSide: BorderSide.none,
),
filled: true,
fillColor: Colors.white,
contentPadding: const EdgeInsets.symmetric(vertical: 8),
),
onChanged: (value) {
setState(() {
_searchQuery = value;
});
AppLogger.userAction('Search events', data: {'query': value});
},
),
),
if (canManageEvents) ...[
const SizedBox(width: 8),
IconButton(
icon: const Icon(Icons.add_circle, color: Color(0xFF6C5CE7)),
onPressed: () {
AppLogger.userAction('Add new event button clicked');
_showAddEventDialog();
},
tooltip: 'Ajouter un événement',
),
],
],
),
);
}
/// Barre d'onglets
Widget _buildTabBar() {
return Container(
margin: const EdgeInsets.symmetric(horizontal: 12),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(8),
),
child: TabBar(
controller: _tabController,
labelColor: const Color(0xFF6C5CE7),
unselectedLabelColor: const Color(0xFF636E72),
indicatorColor: const Color(0xFF6C5CE7),
labelStyle: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600),
tabs: const [
Tab(text: 'Tous'),
Tab(text: 'À venir'),
Tab(text: 'En cours'),
Tab(text: 'Passés'),
Tab(text: 'Calendrier'),
],
),
);
}
/// Vue tous les événements
Widget _buildAllEventsView() {
final filtered = _getFilteredEvents();
return _buildEventsList(filtered);
}
/// Vue événements à venir
Widget _buildUpcomingEventsView() {
final filtered = _getFilteredEvents()
.where((e) => e['estAVenir'] == true)
.toList();
return _buildEventsList(filtered);
}
/// Vue événements en cours
Widget _buildOngoingEventsView() {
final filtered = _getFilteredEvents()
.where((e) => e['estEnCours'] == true)
.toList();
return _buildEventsList(filtered);
}
/// Vue événements passés
Widget _buildPastEventsView() {
final filtered = _getFilteredEvents()
.where((e) => e['estPasse'] == true)
.toList();
return _buildEventsList(filtered);
}
/// Vue calendrier (placeholder)
Widget _buildCalendarView() {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.calendar_month, size: 64, color: Color(0xFF636E72)),
SizedBox(height: 16),
Text(
'Vue calendrier',
style: TextStyle(fontSize: 18, color: Color(0xFF636E72)),
),
SizedBox(height: 8),
Text(
'À implémenter',
style: TextStyle(fontSize: 14, color: Color(0xFF636E72)),
),
],
),
);
}
/// Liste des événements
Widget _buildEventsList(List<Map<String, dynamic>> events) {
if (events.isEmpty) {
return const Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.event_busy, size: 64, color: Color(0xFF636E72)),
SizedBox(height: 16),
Text(
'Aucun événement trouvé',
style: TextStyle(fontSize: 18, color: Color(0xFF636E72)),
),
],
),
);
}
return RefreshIndicator(
onRefresh: () async {
// Recharger les événements
// Note: Cette page utilise des données passées en paramètre
// Le rafraîchissement devrait être géré par le parent
await Future.delayed(const Duration(milliseconds: 500));
},
child: ListView.builder(
padding: const EdgeInsets.all(12),
itemCount: events.length,
itemBuilder: (context, index) {
final event = events[index];
return _buildEventCard(event);
},
),
);
}
/// Carte d'événement
Widget _buildEventCard(Map<String, dynamic> event) {
final startDate = event['startDate'] as DateTime;
final dateFormatter = DateFormat('dd/MM/yyyy HH:mm');
return Card(
margin: const EdgeInsets.only(bottom: 12),
elevation: 2,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
child: InkWell(
onTap: () {
AppLogger.userAction('View event details', data: {'eventId': event['id']});
_showEventDetails(event);
},
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Expanded(
child: Text(
event['title'],
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
_buildStatusChip(event['status']),
],
),
const SizedBox(height: 8),
Row(
children: [
const Icon(Icons.calendar_today, size: 14, color: Color(0xFF636E72)),
const SizedBox(width: 4),
Text(
dateFormatter.format(startDate),
style: const TextStyle(fontSize: 12, color: Color(0xFF636E72)),
),
const SizedBox(width: 12),
const Icon(Icons.location_on, size: 14, color: Color(0xFF636E72)),
const SizedBox(width: 4),
Expanded(
child: Text(
event['location'],
style: const TextStyle(fontSize: 12, color: Color(0xFF636E72)),
overflow: TextOverflow.ellipsis,
),
),
],
),
if (event['description'] != null && event['description'].toString().isNotEmpty) ...[
const SizedBox(height: 8),
Text(
event['description'],
style: const TextStyle(fontSize: 12, color: Color(0xFF636E72)),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
const SizedBox(height: 8),
Row(
children: [
_buildTypeChip(event['type']),
const SizedBox(width: 8),
if (event['cost'] != null && event['cost'] > 0)
_buildCostChip(event['cost']),
const Spacer(),
Text(
'${event['currentParticipants']}/${event['maxParticipants']}',
style: const TextStyle(fontSize: 12, color: Color(0xFF636E72)),
),
const SizedBox(width: 4),
const Icon(Icons.people, size: 14, color: Color(0xFF636E72)),
],
),
],
),
),
),
);
}
Widget _buildStatusChip(String status) {
Color color;
switch (status) {
case 'Confirmé':
color = const Color(0xFF00B894);
break;
case 'Annulé':
color = const Color(0xFFFF7675);
break;
case 'Reporté':
color = const Color(0xFFFFBE76);
break;
case 'Brouillon':
color = const Color(0xFF636E72);
break;
default:
color = const Color(0xFF74B9FF);
}
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
status,
style: TextStyle(
color: color,
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
);
}
Widget _buildTypeChip(String type) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: const Color(0xFF6C5CE7).withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
type,
style: const TextStyle(
color: Color(0xFF6C5CE7),
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
);
}
Widget _buildCostChip(double cost) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
decoration: BoxDecoration(
color: const Color(0xFFFFBE76).withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
child: Text(
'${cost.toStringAsFixed(2)}',
style: const TextStyle(
color: Color(0xFFFFBE76),
fontSize: 10,
fontWeight: FontWeight.w600,
),
),
);
}
/// Pagination
Widget _buildPagination() {
return Container(
padding: const EdgeInsets.all(12),
decoration: const BoxDecoration(
color: Colors.white,
border: Border(top: BorderSide(color: Color(0xFFE0E0E0))),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: const Icon(Icons.chevron_left),
onPressed: widget.currentPage > 0
? () {
AppLogger.userAction('Previous page', data: {'page': widget.currentPage - 1});
// TODO: Charger la page précédente
}
: null,
),
Text('Page ${widget.currentPage + 1} / ${widget.totalPages}'),
IconButton(
icon: const Icon(Icons.chevron_right),
onPressed: widget.currentPage < widget.totalPages - 1
? () {
AppLogger.userAction('Next page', data: {'page': widget.currentPage + 1});
// TODO: Charger la page suivante
}
: null,
),
],
),
);
}
/// Filtrer les événements
List<Map<String, dynamic>> _getFilteredEvents() {
var filtered = widget.events;
if (_searchQuery.isNotEmpty) {
filtered = filtered.where((e) {
final title = e['title'].toString().toLowerCase();
final description = e['description'].toString().toLowerCase();
final query = _searchQuery.toLowerCase();
return title.contains(query) || description.contains(query);
}).toList();
}
return filtered;
}
/// Vérifier permissions
bool _canManageEvents(UserRole role) {
return role.level >= UserRole.moderator.level;
}
/// Afficher détails événement
void _showEventDetails(Map<String, dynamic> event) {
showDialog(
context: context,
builder: (context) => AlertDialog(
title: Text(event['title']),
content: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Description: ${event['description']}'),
const SizedBox(height: 8),
Text('Lieu: ${event['location']}'),
Text('Type: ${event['type']}'),
Text('Statut: ${event['status']}'),
Text('Participants: ${event['currentParticipants']}/${event['maxParticipants']}'),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Fermer'),
),
],
),
);
}
/// Dialogue ajout événement
void _showAddEventDialog() {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Fonctionnalité à implémenter')),
);
}
}

View File

@@ -0,0 +1,275 @@
/// Wrapper BLoC pour la page des événements
///
/// Ce fichier enveloppe la EventsPage existante avec le EvenementsBloc
/// pour connecter l'UI riche existante à l'API backend réelle.
library events_page_wrapper;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:get_it/get_it.dart';
import '../../../../core/widgets/error_widget.dart';
import '../../../../core/widgets/loading_widget.dart';
import '../../../../core/utils/logger.dart';
import '../../bloc/evenements_bloc.dart';
import '../../bloc/evenements_event.dart';
import '../../bloc/evenements_state.dart';
import '../../data/models/evenement_model.dart';
import 'events_page_connected.dart';
final _getIt = GetIt.instance;
/// Wrapper qui fournit le BLoC à la page des événements
class EventsPageWrapper extends StatelessWidget {
const EventsPageWrapper({super.key});
@override
Widget build(BuildContext context) {
AppLogger.info('EventsPageWrapper: Création du BlocProvider');
return BlocProvider<EvenementsBloc>(
create: (context) {
AppLogger.info('EventsPageWrapper: Initialisation du EvenementsBloc');
final bloc = _getIt<EvenementsBloc>();
// Charger les événements au démarrage
bloc.add(const LoadEvenements());
return bloc;
},
child: const EventsPageConnected(),
);
}
}
/// Page des événements connectée au BLoC
///
/// Cette page gère les états du BLoC et affiche l'UI appropriée
class EventsPageConnected extends StatelessWidget {
const EventsPageConnected({super.key});
@override
Widget build(BuildContext context) {
return BlocListener<EvenementsBloc, EvenementsState>(
listener: (context, state) {
// Gestion des erreurs avec SnackBar
if (state is EvenementsError) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
backgroundColor: Colors.red,
duration: const Duration(seconds: 4),
action: SnackBarAction(
label: 'Réessayer',
textColor: Colors.white,
onPressed: () {
context.read<EvenementsBloc>().add(const LoadEvenements());
},
),
),
);
}
},
child: BlocBuilder<EvenementsBloc, EvenementsState>(
builder: (context, state) {
AppLogger.blocState('EvenementsBloc', state.runtimeType.toString());
// État initial
if (state is EvenementsInitial) {
return Container(
color: const Color(0xFFF8F9FA),
child: const Center(
child: AppLoadingWidget(message: 'Initialisation...'),
),
);
}
// État de chargement
if (state is EvenementsLoading) {
return Container(
color: const Color(0xFFF8F9FA),
child: const Center(
child: AppLoadingWidget(message: 'Chargement des événements...'),
),
);
}
// État de rafraîchissement
if (state is EvenementsRefreshing) {
return Container(
color: const Color(0xFFF8F9FA),
child: const Center(
child: AppLoadingWidget(message: 'Actualisation...'),
),
);
}
// État chargé avec succès
if (state is EvenementsLoaded) {
final evenements = state.evenements;
AppLogger.info('EventsPageConnected: ${evenements.length} événements chargés');
// Convertir les événements en format Map pour l'UI existante
final eventsData = _convertEvenementsToMapList(evenements);
return EventsPageWithData(
events: eventsData,
totalCount: state.total,
currentPage: state.page,
totalPages: state.totalPages,
);
}
// État d'erreur réseau
if (state is EvenementsNetworkError) {
AppLogger.error('EventsPageConnected: Erreur réseau', error: state.message);
return Container(
color: const Color(0xFFF8F9FA),
child: NetworkErrorWidget(
onRetry: () {
AppLogger.userAction('Retry load evenements after network error');
context.read<EvenementsBloc>().add(const LoadEvenements());
},
),
);
}
// État d'erreur générale
if (state is EvenementsError) {
AppLogger.error('EventsPageConnected: Erreur', error: state.message);
return Container(
color: const Color(0xFFF8F9FA),
child: AppErrorWidget(
message: state.message,
onRetry: () {
AppLogger.userAction('Retry load evenements after error');
context.read<EvenementsBloc>().add(const LoadEvenements());
},
),
);
}
// État par défaut
AppLogger.warning('EventsPageConnected: État non géré: ${state.runtimeType}');
return Container(
color: const Color(0xFFF8F9FA),
child: const Center(
child: AppLoadingWidget(message: 'Chargement...'),
),
);
},
),
);
}
/// Convertit une liste de EvenementModel en List<Map<String, dynamic>>
List<Map<String, dynamic>> _convertEvenementsToMapList(List<EvenementModel> evenements) {
return evenements.map((evenement) => _convertEvenementToMap(evenement)).toList();
}
/// Convertit un EvenementModel en Map<String, dynamic>
Map<String, dynamic> _convertEvenementToMap(EvenementModel evenement) {
return {
'id': evenement.id ?? '',
'title': evenement.titre,
'description': evenement.description ?? '',
'startDate': evenement.dateDebut,
'endDate': evenement.dateFin,
'location': evenement.lieu ?? '',
'address': evenement.adresse ?? '',
'type': _mapTypeToString(evenement.type),
'status': _mapStatutToString(evenement.statut),
'maxParticipants': evenement.maxParticipants ?? 0,
'currentParticipants': evenement.participantsActuels ?? 0,
'organizer': 'Organisateur', // TODO: Récupérer depuis organisateurId
'priority': _mapPrioriteToString(evenement.priorite),
'isPublic': evenement.estPublic ?? true,
'requiresRegistration': evenement.inscriptionRequise ?? false,
'cost': evenement.cout ?? 0.0,
'tags': evenement.tags ?? [],
'createdBy': 'Créateur', // TODO: Récupérer depuis organisateurId
'createdAt': DateTime.now(), // TODO: Ajouter au modèle
'lastModified': DateTime.now(), // TODO: Ajouter au modèle
// Champs supplémentaires du modèle
'ville': evenement.ville,
'codePostal': evenement.codePostal,
'organisateurId': evenement.organisateurId,
'organisationId': evenement.organisationId,
'devise': evenement.devise,
'imageUrl': evenement.imageUrl,
'documentUrl': evenement.documentUrl,
// Propriétés calculées
'dureeHeures': evenement.dureeHeures,
'joursAvantEvenement': evenement.joursAvantEvenement,
'estAVenir': evenement.estAVenir,
'estEnCours': evenement.estEnCours,
'estPasse': evenement.estPasse,
'placesDisponibles': evenement.placesDisponibles,
'estComplet': evenement.estComplet,
'peutSinscrire': evenement.peutSinscrire,
};
}
/// Mappe le type du modèle vers une chaîne lisible
String _mapTypeToString(TypeEvenement? type) {
if (type == null) return 'Autre';
switch (type) {
case TypeEvenement.assembleeGenerale:
return 'Assemblée Générale';
case TypeEvenement.reunion:
return 'Réunion';
case TypeEvenement.formation:
return 'Formation';
case TypeEvenement.conference:
return 'Conférence';
case TypeEvenement.atelier:
return 'Atelier';
case TypeEvenement.seminaire:
return 'Séminaire';
case TypeEvenement.evenementSocial:
return 'Événement Social';
case TypeEvenement.manifestation:
return 'Manifestation';
case TypeEvenement.celebration:
return 'Célébration';
case TypeEvenement.autre:
return 'Autre';
}
}
/// Mappe le statut du modèle vers une chaîne lisible
String _mapStatutToString(StatutEvenement? statut) {
if (statut == null) return 'Planifié';
switch (statut) {
case StatutEvenement.planifie:
return 'Planifié';
case StatutEvenement.confirme:
return 'Confirmé';
case StatutEvenement.enCours:
return 'En cours';
case StatutEvenement.termine:
return 'Terminé';
case StatutEvenement.annule:
return 'Annulé';
case StatutEvenement.reporte:
return 'Reporté';
}
}
/// Mappe la priorité du modèle vers une chaîne lisible
String _mapPrioriteToString(PrioriteEvenement? priorite) {
if (priorite == null) return 'Moyenne';
switch (priorite) {
case PrioriteEvenement.basse:
return 'Basse';
case PrioriteEvenement.moyenne:
return 'Moyenne';
case PrioriteEvenement.haute:
return 'Haute';
}
}
}

View File

@@ -0,0 +1,428 @@
/// Dialogue de création d'événement
/// Formulaire complet pour créer un nouvel événement
library create_event_dialog;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../bloc/evenements_bloc.dart';
import '../../bloc/evenements_event.dart';
import '../../data/models/evenement_model.dart';
/// Dialogue de création d'événement
class CreateEventDialog extends StatefulWidget {
const CreateEventDialog({super.key});
@override
State<CreateEventDialog> createState() => _CreateEventDialogState();
}
class _CreateEventDialogState extends State<CreateEventDialog> {
final _formKey = GlobalKey<FormState>();
// Contrôleurs de texte
final _titreController = TextEditingController();
final _descriptionController = TextEditingController();
final _lieuController = TextEditingController();
final _adresseController = TextEditingController();
final _capaciteController = TextEditingController();
// Valeurs sélectionnées
DateTime _dateDebut = DateTime.now().add(const Duration(days: 7));
DateTime? _dateFin;
TypeEvenement _selectedType = TypeEvenement.autre;
bool _inscriptionRequise = true;
bool _visiblePublic = true;
@override
void dispose() {
_titreController.dispose();
_descriptionController.dispose();
_lieuController.dispose();
_adresseController.dispose();
_capaciteController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Dialog(
child: Container(
width: MediaQuery.of(context).size.width * 0.9,
constraints: const BoxConstraints(maxHeight: 600),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// En-tête
Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: Color(0xFF3B82F6),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4),
topRight: Radius.circular(4),
),
),
child: Row(
children: [
const Icon(Icons.event, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Créer un événement',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
// Formulaire
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Informations de base
_buildSectionTitle('Informations de base'),
const SizedBox(height: 12),
TextFormField(
controller: _titreController,
decoration: const InputDecoration(
labelText: 'Titre *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.title),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Le titre est obligatoire';
}
if (value.length < 3) {
return 'Le titre doit contenir au moins 3 caractères';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: 'Description',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.description),
),
maxLines: 3,
),
const SizedBox(height: 12),
// Type d'événement
DropdownButtonFormField<TypeEvenement>(
value: _selectedType,
decoration: const InputDecoration(
labelText: 'Type d\'événement *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.category),
),
items: TypeEvenement.values.map((type) {
return DropdownMenuItem(
value: type,
child: Text(_getTypeLabel(type)),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedType = value!;
});
},
),
const SizedBox(height: 16),
// Dates
_buildSectionTitle('Dates et horaires'),
const SizedBox(height: 12),
InkWell(
onTap: () => _selectDateDebut(context),
child: InputDecorator(
decoration: const InputDecoration(
labelText: 'Date de début *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.calendar_today),
),
child: Text(
DateFormat('dd/MM/yyyy HH:mm').format(_dateDebut),
),
),
),
const SizedBox(height: 12),
InkWell(
onTap: () => _selectDateFin(context),
child: InputDecorator(
decoration: const InputDecoration(
labelText: 'Date de fin (optionnel)',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.event_available),
),
child: Text(
_dateFin != null
? DateFormat('dd/MM/yyyy HH:mm').format(_dateFin!)
: 'Sélectionner une date',
),
),
),
const SizedBox(height: 16),
// Lieu
_buildSectionTitle('Lieu'),
const SizedBox(height: 12),
TextFormField(
controller: _lieuController,
decoration: const InputDecoration(
labelText: 'Lieu *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.place),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Le lieu est obligatoire';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _adresseController,
decoration: const InputDecoration(
labelText: 'Adresse complète',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.location_on),
),
maxLines: 2,
),
const SizedBox(height: 16),
// Paramètres
_buildSectionTitle('Paramètres'),
const SizedBox(height: 12),
TextFormField(
controller: _capaciteController,
decoration: const InputDecoration(
labelText: 'Capacité maximale',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.people),
hintText: 'Nombre de places disponibles',
),
keyboardType: TextInputType.number,
validator: (value) {
if (value != null && value.isNotEmpty) {
final capacite = int.tryParse(value);
if (capacite == null || capacite <= 0) {
return 'Capacité invalide';
}
}
return null;
},
),
const SizedBox(height: 12),
SwitchListTile(
title: const Text('Inscription requise'),
subtitle: const Text('Les participants doivent s\'inscrire'),
value: _inscriptionRequise,
onChanged: (value) {
setState(() {
_inscriptionRequise = value;
});
},
),
SwitchListTile(
title: const Text('Visible publiquement'),
subtitle: const Text('L\'événement est visible par tous'),
value: _visiblePublic,
onChanged: (value) {
setState(() {
_visiblePublic = value;
});
},
),
],
),
),
),
),
// Boutons d'action
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[100],
border: Border(top: BorderSide(color: Colors.grey[300]!)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Annuler'),
),
const SizedBox(width: 12),
ElevatedButton(
onPressed: _submitForm,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF3B82F6),
foregroundColor: Colors.white,
),
child: const Text('Créer l\'événement'),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
return Text(
title,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF3B82F6),
),
);
}
String _getTypeLabel(TypeEvenement type) {
switch (type) {
case TypeEvenement.assembleeGenerale:
return 'Assemblée Générale';
case TypeEvenement.reunion:
return 'Réunion';
case TypeEvenement.formation:
return 'Formation';
case TypeEvenement.conference:
return 'Conférence';
case TypeEvenement.atelier:
return 'Atelier';
case TypeEvenement.seminaire:
return 'Séminaire';
case TypeEvenement.evenementSocial:
return 'Événement Social';
case TypeEvenement.manifestation:
return 'Manifestation';
case TypeEvenement.celebration:
return 'Célébration';
case TypeEvenement.autre:
return 'Autre';
}
}
Future<void> _selectDateDebut(BuildContext context) async {
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: _dateDebut,
firstDate: DateTime.now(),
lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
);
if (pickedDate != null) {
final TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_dateDebut),
);
if (pickedTime != null) {
setState(() {
_dateDebut = DateTime(
pickedDate.year,
pickedDate.month,
pickedDate.day,
pickedTime.hour,
pickedTime.minute,
);
});
}
}
}
Future<void> _selectDateFin(BuildContext context) async {
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: _dateFin ?? _dateDebut.add(const Duration(hours: 2)),
firstDate: _dateDebut,
lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
);
if (pickedDate != null) {
final TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_dateFin ?? _dateDebut.add(const Duration(hours: 2))),
);
if (pickedTime != null) {
setState(() {
_dateFin = DateTime(
pickedDate.year,
pickedDate.month,
pickedDate.day,
pickedTime.hour,
pickedTime.minute,
);
});
}
}
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
// Créer le modèle d'événement
final evenement = EvenementModel(
titre: _titreController.text,
description: _descriptionController.text.isNotEmpty ? _descriptionController.text : null,
dateDebut: _dateDebut,
dateFin: _dateFin ?? _dateDebut.add(const Duration(hours: 2)),
lieu: _lieuController.text,
adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
type: _selectedType,
maxParticipants: _capaciteController.text.isNotEmpty ? int.parse(_capaciteController.text) : null,
inscriptionRequise: _inscriptionRequise,
estPublic: _visiblePublic,
statut: StatutEvenement.planifie,
);
// Envoyer l'événement au BLoC
context.read<EvenementsBloc>().add(CreateEvenement(evenement));
// Fermer le dialogue
Navigator.pop(context);
// Afficher un message de succès
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Événement créé avec succès'),
backgroundColor: Colors.green,
),
);
}
}
}

View File

@@ -0,0 +1,511 @@
/// Dialogue de modification d'événement
/// Formulaire pré-rempli pour modifier un événement existant
library edit_event_dialog;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:intl/intl.dart';
import '../../bloc/evenements_bloc.dart';
import '../../bloc/evenements_event.dart';
import '../../data/models/evenement_model.dart';
/// Dialogue de modification d'événement
class EditEventDialog extends StatefulWidget {
final EvenementModel evenement;
const EditEventDialog({
super.key,
required this.evenement,
});
@override
State<EditEventDialog> createState() => _EditEventDialogState();
}
class _EditEventDialogState extends State<EditEventDialog> {
final _formKey = GlobalKey<FormState>();
// Contrôleurs de texte
late final TextEditingController _titreController;
late final TextEditingController _descriptionController;
late final TextEditingController _lieuController;
late final TextEditingController _adresseController;
late final TextEditingController _capaciteController;
// Valeurs sélectionnées
late DateTime _dateDebut;
late DateTime _dateFin;
late TypeEvenement _selectedType;
late StatutEvenement _selectedStatut;
late bool _inscriptionRequise;
late bool _estPublic;
@override
void initState() {
super.initState();
// Initialiser les contrôleurs avec les valeurs existantes
_titreController = TextEditingController(text: widget.evenement.titre);
_descriptionController = TextEditingController(text: widget.evenement.description ?? '');
_lieuController = TextEditingController(text: widget.evenement.lieu ?? '');
_adresseController = TextEditingController(text: widget.evenement.adresse ?? '');
_capaciteController = TextEditingController(
text: widget.evenement.maxParticipants?.toString() ?? '',
);
// Initialiser les valeurs
_dateDebut = widget.evenement.dateDebut;
_dateFin = widget.evenement.dateFin;
_selectedType = widget.evenement.type;
_selectedStatut = widget.evenement.statut;
_inscriptionRequise = widget.evenement.inscriptionRequise;
_estPublic = widget.evenement.estPublic;
}
@override
void dispose() {
_titreController.dispose();
_descriptionController.dispose();
_lieuController.dispose();
_adresseController.dispose();
_capaciteController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Dialog(
child: Container(
width: MediaQuery.of(context).size.width * 0.9,
constraints: const BoxConstraints(maxHeight: 600),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
// En-tête
Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: Color(0xFF3B82F6),
borderRadius: BorderRadius.only(
topLeft: Radius.circular(4),
topRight: Radius.circular(4),
),
),
child: Row(
children: [
const Icon(Icons.edit, color: Colors.white),
const SizedBox(width: 12),
const Text(
'Modifier l\'événement',
style: TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const Spacer(),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
),
// Formulaire
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Informations de base
_buildSectionTitle('Informations de base'),
const SizedBox(height: 12),
TextFormField(
controller: _titreController,
decoration: const InputDecoration(
labelText: 'Titre *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.title),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Le titre est obligatoire';
}
if (value.length < 3) {
return 'Le titre doit contenir au moins 3 caractères';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _descriptionController,
decoration: const InputDecoration(
labelText: 'Description',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.description),
),
maxLines: 3,
),
const SizedBox(height: 12),
// Type et statut
Row(
children: [
Expanded(
child: DropdownButtonFormField<TypeEvenement>(
value: _selectedType,
decoration: const InputDecoration(
labelText: 'Type *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.category),
),
items: TypeEvenement.values.map((type) {
return DropdownMenuItem(
value: type,
child: Text(_getTypeLabel(type)),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedType = value!;
});
},
),
),
const SizedBox(width: 12),
Expanded(
child: DropdownButtonFormField<StatutEvenement>(
value: _selectedStatut,
decoration: const InputDecoration(
labelText: 'Statut *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.flag),
),
items: StatutEvenement.values.map((statut) {
return DropdownMenuItem(
value: statut,
child: Text(_getStatutLabel(statut)),
);
}).toList(),
onChanged: (value) {
setState(() {
_selectedStatut = value!;
});
},
),
),
],
),
const SizedBox(height: 16),
// Dates
_buildSectionTitle('Dates et horaires'),
const SizedBox(height: 12),
InkWell(
onTap: () => _selectDateDebut(context),
child: InputDecorator(
decoration: const InputDecoration(
labelText: 'Date de début *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.calendar_today),
),
child: Text(
DateFormat('dd/MM/yyyy HH:mm').format(_dateDebut),
),
),
),
const SizedBox(height: 12),
InkWell(
onTap: () => _selectDateFin(context),
child: InputDecorator(
decoration: const InputDecoration(
labelText: 'Date de fin *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.event_available),
),
child: Text(
DateFormat('dd/MM/yyyy HH:mm').format(_dateFin),
),
),
),
const SizedBox(height: 16),
// Lieu
_buildSectionTitle('Lieu'),
const SizedBox(height: 12),
TextFormField(
controller: _lieuController,
decoration: const InputDecoration(
labelText: 'Lieu *',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.place),
),
validator: (value) {
if (value == null || value.isEmpty) {
return 'Le lieu est obligatoire';
}
return null;
},
),
const SizedBox(height: 12),
TextFormField(
controller: _adresseController,
decoration: const InputDecoration(
labelText: 'Adresse complète',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.location_on),
),
maxLines: 2,
),
const SizedBox(height: 16),
// Capacité
_buildSectionTitle('Paramètres'),
const SizedBox(height: 12),
TextFormField(
controller: _capaciteController,
decoration: InputDecoration(
labelText: 'Capacité maximale',
border: const OutlineInputBorder(),
prefixIcon: const Icon(Icons.people),
suffixText: widget.evenement.participantsActuels > 0
? '${widget.evenement.participantsActuels} inscrits'
: null,
),
keyboardType: TextInputType.number,
validator: (value) {
if (value != null && value.isNotEmpty) {
final capacite = int.tryParse(value);
if (capacite == null || capacite <= 0) {
return 'La capacité doit être un nombre positif';
}
if (capacite < widget.evenement.participantsActuels) {
return 'La capacité ne peut pas être inférieure au nombre d\'inscrits (${widget.evenement.participantsActuels})';
}
}
return null;
},
),
const SizedBox(height: 12),
SwitchListTile(
title: const Text('Inscription requise'),
subtitle: const Text('Les participants doivent s\'inscrire'),
value: _inscriptionRequise,
onChanged: (value) {
setState(() {
_inscriptionRequise = value;
});
},
),
SwitchListTile(
title: const Text('Événement public'),
subtitle: const Text('Visible par tous les membres'),
value: _estPublic,
onChanged: (value) {
setState(() {
_estPublic = value;
});
},
),
],
),
),
),
),
// Boutons d'action
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[100],
border: Border(top: BorderSide(color: Colors.grey[300]!)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Annuler'),
),
const SizedBox(width: 12),
ElevatedButton(
onPressed: _submitForm,
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF3B82F6),
foregroundColor: Colors.white,
),
child: const Text('Enregistrer'),
),
],
),
),
],
),
),
);
}
Widget _buildSectionTitle(String title) {
return Text(
title,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
color: Color(0xFF3B82F6),
),
);
}
String _getTypeLabel(TypeEvenement type) {
switch (type) {
case TypeEvenement.assembleeGenerale:
return 'Assemblée Générale';
case TypeEvenement.reunion:
return 'Réunion';
case TypeEvenement.formation:
return 'Formation';
case TypeEvenement.conference:
return 'Conférence';
case TypeEvenement.atelier:
return 'Atelier';
case TypeEvenement.seminaire:
return 'Séminaire';
case TypeEvenement.evenementSocial:
return 'Événement Social';
case TypeEvenement.manifestation:
return 'Manifestation';
case TypeEvenement.celebration:
return 'Célébration';
case TypeEvenement.autre:
return 'Autre';
}
}
String _getStatutLabel(StatutEvenement statut) {
switch (statut) {
case StatutEvenement.planifie:
return 'Planifié';
case StatutEvenement.confirme:
return 'Confirmé';
case StatutEvenement.enCours:
return 'En cours';
case StatutEvenement.termine:
return 'Terminé';
case StatutEvenement.annule:
return 'Annulé';
case StatutEvenement.reporte:
return 'Reporté';
}
}
Future<void> _selectDateDebut(BuildContext context) async {
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: _dateDebut,
firstDate: DateTime.now().subtract(const Duration(days: 365)),
lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
);
if (pickedDate != null) {
final TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_dateDebut),
);
if (pickedTime != null) {
setState(() {
_dateDebut = DateTime(
pickedDate.year,
pickedDate.month,
pickedDate.day,
pickedTime.hour,
pickedTime.minute,
);
// Ajuster la date de fin si elle est avant la date de début
if (_dateFin.isBefore(_dateDebut)) {
_dateFin = _dateDebut.add(const Duration(hours: 2));
}
});
}
}
}
Future<void> _selectDateFin(BuildContext context) async {
final DateTime? pickedDate = await showDatePicker(
context: context,
initialDate: _dateFin,
firstDate: _dateDebut,
lastDate: DateTime.now().add(const Duration(days: 365 * 2)),
);
if (pickedDate != null) {
final TimeOfDay? pickedTime = await showTimePicker(
context: context,
initialTime: TimeOfDay.fromDateTime(_dateFin),
);
if (pickedTime != null) {
setState(() {
_dateFin = DateTime(
pickedDate.year,
pickedDate.month,
pickedDate.day,
pickedTime.hour,
pickedTime.minute,
);
});
}
}
}
void _submitForm() {
if (_formKey.currentState!.validate()) {
// Créer le modèle d'événement mis à jour
final evenementUpdated = widget.evenement.copyWith(
titre: _titreController.text,
description: _descriptionController.text.isNotEmpty ? _descriptionController.text : null,
dateDebut: _dateDebut,
dateFin: _dateFin,
lieu: _lieuController.text,
adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
type: _selectedType,
statut: _selectedStatut,
maxParticipants: _capaciteController.text.isNotEmpty ? int.parse(_capaciteController.text) : null,
inscriptionRequise: _inscriptionRequise,
estPublic: _estPublic,
);
// Envoyer l'événement au BLoC
context.read<EvenementsBloc>().add(UpdateEvenement(widget.evenement.id!, evenementUpdated));
// Fermer le dialogue
Navigator.pop(context);
// Afficher un message de succès
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Événement modifié avec succès'),
backgroundColor: Colors.green,
),
);
}
}
}

View File

@@ -0,0 +1,320 @@
/// Dialogue d'inscription à un événement
library inscription_event_dialog;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/evenements_bloc.dart';
import '../../bloc/evenements_event.dart';
import '../../data/models/evenement_model.dart';
class InscriptionEventDialog extends StatefulWidget {
final EvenementModel evenement;
final bool isInscrit;
const InscriptionEventDialog({
super.key,
required this.evenement,
this.isInscrit = false,
});
@override
State<InscriptionEventDialog> createState() => _InscriptionEventDialogState();
}
class _InscriptionEventDialogState extends State<InscriptionEventDialog> {
final _formKey = GlobalKey<FormState>();
final _commentaireController = TextEditingController();
@override
void dispose() {
_commentaireController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Dialog(
child: Container(
width: MediaQuery.of(context).size.width * 0.9,
constraints: const BoxConstraints(maxHeight: 500),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
_buildHeader(),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Form(
key: _formKey,
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_buildEventInfo(),
const SizedBox(height: 16),
if (!widget.isInscrit) ...[
_buildPlacesInfo(),
const SizedBox(height: 16),
_buildCommentaireField(),
] else ...[
_buildDesinscriptionWarning(),
],
],
),
),
),
),
_buildActionButtons(),
],
),
),
);
}
Widget _buildHeader() {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: widget.isInscrit ? Colors.red : const Color(0xFF3B82F6),
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(4),
topRight: Radius.circular(4),
),
),
child: Row(
children: [
Icon(
widget.isInscrit ? Icons.cancel : Icons.event_available,
color: Colors.white,
),
const SizedBox(width: 12),
Expanded(
child: Text(
widget.isInscrit ? 'Se désinscrire' : 'S\'inscrire à l\'événement',
style: const TextStyle(
color: Colors.white,
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
),
IconButton(
icon: const Icon(Icons.close, color: Colors.white),
onPressed: () => Navigator.pop(context),
),
],
),
);
}
Widget _buildEventInfo() {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue[50],
border: Border.all(color: Colors.blue[200]!),
borderRadius: BorderRadius.circular(4),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.event, color: Color(0xFF3B82F6)),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.evenement.titre,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.bold,
),
),
),
],
),
const SizedBox(height: 8),
Row(
children: [
const Icon(Icons.calendar_today, size: 16, color: Colors.grey),
const SizedBox(width: 8),
Text(
_formatDate(widget.evenement.dateDebut),
style: const TextStyle(fontSize: 14),
),
],
),
if (widget.evenement.lieu != null) ...[
const SizedBox(height: 4),
Row(
children: [
const Icon(Icons.location_on, size: 16, color: Colors.grey),
const SizedBox(width: 8),
Expanded(
child: Text(
widget.evenement.lieu!,
style: const TextStyle(fontSize: 14),
),
),
],
),
],
],
),
);
}
Widget _buildPlacesInfo() {
final placesRestantes = (widget.evenement.maxParticipants ?? 0) -
widget.evenement.participantsActuels;
final isComplet = placesRestantes <= 0 && widget.evenement.maxParticipants != null;
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: isComplet ? Colors.red[50] : Colors.green[50],
border: Border.all(
color: isComplet ? Colors.red[200]! : Colors.green[200]!,
),
borderRadius: BorderRadius.circular(4),
),
child: Row(
children: [
Icon(
isComplet ? Icons.warning : Icons.check_circle,
color: isComplet ? Colors.red : Colors.green,
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isComplet ? 'Événement complet' : 'Places disponibles',
style: TextStyle(
fontWeight: FontWeight.bold,
color: isComplet ? Colors.red[900] : Colors.green[900],
),
),
if (widget.evenement.maxParticipants != null)
Text(
'$placesRestantes places restantes sur ${widget.evenement.maxParticipants}',
style: const TextStyle(fontSize: 12),
)
else
const Text(
'Nombre de places illimité',
style: TextStyle(fontSize: 12),
),
],
),
),
],
),
);
}
Widget _buildCommentaireField() {
return TextFormField(
controller: _commentaireController,
decoration: const InputDecoration(
labelText: 'Commentaire (optionnel)',
border: OutlineInputBorder(),
prefixIcon: Icon(Icons.comment),
hintText: 'Ajoutez un commentaire...',
),
maxLines: 3,
);
}
Widget _buildDesinscriptionWarning() {
return Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.orange[50],
border: Border.all(color: Colors.orange[200]!),
borderRadius: BorderRadius.circular(4),
),
child: Row(
children: [
const Icon(Icons.warning, color: Colors.orange),
const SizedBox(width: 12),
const Expanded(
child: Text(
'Êtes-vous sûr de vouloir vous désinscrire de cet événement ?',
style: TextStyle(fontSize: 14),
),
),
],
),
);
}
Widget _buildActionButtons() {
final placesRestantes = (widget.evenement.maxParticipants ?? 0) -
widget.evenement.participantsActuels;
final isComplet = placesRestantes <= 0 && widget.evenement.maxParticipants != null;
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[100],
border: Border(top: BorderSide(color: Colors.grey[300]!)),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.end,
children: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('Annuler'),
),
const SizedBox(width: 12),
ElevatedButton(
onPressed: (widget.isInscrit || !isComplet) ? _submitForm : null,
style: ElevatedButton.styleFrom(
backgroundColor: widget.isInscrit ? Colors.red : const Color(0xFF3B82F6),
foregroundColor: Colors.white,
),
child: Text(widget.isInscrit ? 'Se désinscrire' : 'S\'inscrire'),
),
],
),
);
}
String _formatDate(DateTime date) {
final months = [
'janvier', 'février', 'mars', 'avril', 'mai', 'juin',
'juillet', 'août', 'septembre', 'octobre', 'novembre', 'décembre'
];
return '${date.day} ${months[date.month - 1]} ${date.year} à ${date.hour}:${date.minute.toString().padLeft(2, '0')}';
}
void _submitForm() {
if (widget.isInscrit) {
// Désinscription
context.read<EvenementsBloc>().add(DesinscrireEvenement(widget.evenement.id!));
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Désinscription réussie'),
backgroundColor: Colors.orange,
),
);
} else {
// Inscription
context.read<EvenementsBloc>().add(
InscrireEvenement(widget.evenement.id!),
);
Navigator.pop(context);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Inscription réussie'),
backgroundColor: Colors.green,
),
);
}
}
}