Initial commit: unionflow-mobile-apps
Application Flutter complète (sans build artifacts). Signed-off-by: lions dev Team
This commit is contained in:
444
lib/features/members/bloc/membres_bloc.dart
Normal file
444
lib/features/members/bloc/membres_bloc.dart
Normal file
@@ -0,0 +1,444 @@
|
||||
/// BLoC pour la gestion des membres
|
||||
library membres_bloc;
|
||||
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
import 'membres_event.dart';
|
||||
import 'membres_state.dart';
|
||||
import '../domain/usecases/get_members.dart';
|
||||
import '../domain/usecases/get_member_by_id.dart';
|
||||
import '../domain/usecases/create_member.dart' as uc;
|
||||
import '../domain/usecases/update_member.dart' as uc;
|
||||
import '../domain/usecases/delete_member.dart' as uc;
|
||||
import '../domain/usecases/search_members.dart';
|
||||
import '../domain/usecases/get_member_stats.dart';
|
||||
import '../domain/repositories/membre_repository.dart';
|
||||
|
||||
/// BLoC pour la gestion des membres (Clean Architecture)
|
||||
@injectable
|
||||
class MembresBloc extends Bloc<MembresEvent, MembresState> {
|
||||
final GetMembers _getMembers;
|
||||
final GetMemberById _getMemberById;
|
||||
final uc.CreateMember _createMember;
|
||||
final uc.UpdateMember _updateMember;
|
||||
final uc.DeleteMember _deleteMember;
|
||||
final SearchMembers _searchMembers;
|
||||
final GetMemberStats _getMemberStats;
|
||||
final IMembreRepository _repository; // Pour méthodes non-couvertes par use cases
|
||||
|
||||
MembresBloc(
|
||||
this._getMembers,
|
||||
this._getMemberById,
|
||||
this._createMember,
|
||||
this._updateMember,
|
||||
this._deleteMember,
|
||||
this._searchMembers,
|
||||
this._getMemberStats,
|
||||
this._repository,
|
||||
) : super(const MembresInitial()) {
|
||||
on<LoadMembres>(_onLoadMembres);
|
||||
on<LoadMembreById>(_onLoadMembreById);
|
||||
on<CreateMembre>(_onCreateMembre);
|
||||
on<UpdateMembre>(_onUpdateMembre);
|
||||
on<DeleteMembre>(_onDeleteMembre);
|
||||
on<ActivateMembre>(_onActivateMembre);
|
||||
on<DeactivateMembre>(_onDeactivateMembre);
|
||||
on<SearchMembres>(_onSearchMembres);
|
||||
on<LoadActiveMembres>(_onLoadActiveMembres);
|
||||
on<LoadBureauMembres>(_onLoadBureauMembres);
|
||||
on<LoadMembresStats>(_onLoadMembresStats);
|
||||
}
|
||||
|
||||
/// Charge la liste des membres
|
||||
Future<void> _onLoadMembres(
|
||||
LoadMembres event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
// Si refresh et qu'on a déjà des données, on garde l'état actuel
|
||||
if (event.refresh && state is MembresLoaded) {
|
||||
final currentState = state as MembresLoaded;
|
||||
emit(MembresRefreshing(currentState.membres));
|
||||
} else {
|
||||
emit(const MembresLoading());
|
||||
}
|
||||
|
||||
final result = await _getMembers(
|
||||
page: event.page,
|
||||
size: event.size,
|
||||
recherche: event.recherche,
|
||||
);
|
||||
|
||||
emit(MembresLoaded(
|
||||
membres: result.membres,
|
||||
totalElements: result.totalElements,
|
||||
currentPage: result.currentPage,
|
||||
pageSize: result.pageSize,
|
||||
totalPages: result.totalPages,
|
||||
));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur inattendue lors du chargement des membres: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge un membre par ID
|
||||
Future<void> _onLoadMembreById(
|
||||
LoadMembreById event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final membre = await _getMemberById(event.id);
|
||||
|
||||
if (membre != null) {
|
||||
emit(MembreDetailLoaded(membre));
|
||||
} else {
|
||||
emit(const MembresError(
|
||||
message: 'Membre non trouvé',
|
||||
code: '404',
|
||||
));
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors du chargement du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Crée un nouveau membre
|
||||
Future<void> _onCreateMembre(
|
||||
CreateMembre event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final membre = await _createMember(event.membre);
|
||||
|
||||
emit(MembreCreated(membre));
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 400) {
|
||||
// Erreur de validation
|
||||
final errors = _extractValidationErrors(e.response?.data);
|
||||
emit(MembresValidationError(
|
||||
message: 'Erreur de validation',
|
||||
validationErrors: errors,
|
||||
code: '400',
|
||||
));
|
||||
} else {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de la création du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Met à jour un membre
|
||||
Future<void> _onUpdateMembre(
|
||||
UpdateMembre event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final membre = await _updateMember(event.id, event.membre);
|
||||
|
||||
emit(MembreUpdated(membre));
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 400) {
|
||||
final errors = _extractValidationErrors(e.response?.data);
|
||||
emit(MembresValidationError(
|
||||
message: 'Erreur de validation',
|
||||
validationErrors: errors,
|
||||
code: '400',
|
||||
));
|
||||
} else {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de la mise à jour du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Supprime un membre
|
||||
Future<void> _onDeleteMembre(
|
||||
DeleteMembre event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
await _deleteMember(event.id);
|
||||
|
||||
emit(MembreDeleted(event.id));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de la suppression du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Active un membre
|
||||
Future<void> _onActivateMembre(
|
||||
ActivateMembre event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final membre = await _repository.activateMembre(event.id);
|
||||
|
||||
emit(MembreActivated(membre));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de l\'activation du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Désactive un membre
|
||||
Future<void> _onDeactivateMembre(
|
||||
DeactivateMembre event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final membre = await _repository.deactivateMembre(event.id);
|
||||
|
||||
emit(MembreDeactivated(membre));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de la désactivation du membre: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Recherche avancée de membres
|
||||
Future<void> _onSearchMembres(
|
||||
SearchMembres event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final result = await _searchMembers(
|
||||
criteria: event.criteria,
|
||||
page: event.page,
|
||||
size: event.size,
|
||||
);
|
||||
|
||||
emit(MembresLoaded(
|
||||
membres: result.membres,
|
||||
totalElements: result.totalElements,
|
||||
currentPage: result.currentPage,
|
||||
pageSize: result.pageSize,
|
||||
totalPages: result.totalPages,
|
||||
));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors de la recherche de membres: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge les membres actifs
|
||||
Future<void> _onLoadActiveMembres(
|
||||
LoadActiveMembres event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final result = await _repository.getActiveMembers(
|
||||
page: event.page,
|
||||
size: event.size,
|
||||
);
|
||||
|
||||
emit(MembresLoaded(
|
||||
membres: result.membres,
|
||||
totalElements: result.totalElements,
|
||||
currentPage: result.currentPage,
|
||||
pageSize: result.pageSize,
|
||||
totalPages: result.totalPages,
|
||||
));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors du chargement des membres actifs: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge les membres du bureau
|
||||
Future<void> _onLoadBureauMembres(
|
||||
LoadBureauMembres event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final result = await _repository.getBureauMembers(
|
||||
page: event.page,
|
||||
size: event.size,
|
||||
);
|
||||
|
||||
emit(MembresLoaded(
|
||||
membres: result.membres,
|
||||
totalElements: result.totalElements,
|
||||
currentPage: result.currentPage,
|
||||
pageSize: result.pageSize,
|
||||
totalPages: result.totalPages,
|
||||
));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors du chargement des membres du bureau: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Charge les statistiques
|
||||
Future<void> _onLoadMembresStats(
|
||||
LoadMembresStats event,
|
||||
Emitter<MembresState> emit,
|
||||
) async {
|
||||
try {
|
||||
emit(const MembresLoading());
|
||||
|
||||
final stats = await _getMemberStats();
|
||||
|
||||
emit(MembresStatsLoaded(stats));
|
||||
} on DioException catch (e) {
|
||||
emit(MembresNetworkError(
|
||||
message: _getNetworkErrorMessage(e),
|
||||
code: e.response?.statusCode.toString(),
|
||||
error: e,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(MembresError(
|
||||
message: 'Erreur lors du chargement des statistiques: $e',
|
||||
error: e,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Extrait les erreurs de validation de la réponse
|
||||
Map<String, String> _extractValidationErrors(dynamic data) {
|
||||
final errors = <String, String>{};
|
||||
if (data is Map<String, dynamic> && data.containsKey('errors')) {
|
||||
final errorsData = data['errors'];
|
||||
if (errorsData is Map<String, dynamic>) {
|
||||
errorsData.forEach((key, value) {
|
||||
errors[key] = value.toString();
|
||||
});
|
||||
}
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
/// Génère un message d'erreur réseau approprié
|
||||
String _getNetworkErrorMessage(DioException e) {
|
||||
switch (e.type) {
|
||||
case DioExceptionType.connectionTimeout:
|
||||
return 'Délai de connexion dépassé. Vérifiez votre connexion internet.';
|
||||
case DioExceptionType.sendTimeout:
|
||||
return 'Délai d\'envoi dépassé. Vérifiez votre connexion internet.';
|
||||
case DioExceptionType.receiveTimeout:
|
||||
return 'Délai de réception dépassé. Vérifiez votre connexion internet.';
|
||||
case DioExceptionType.badResponse:
|
||||
final statusCode = e.response?.statusCode;
|
||||
if (statusCode == 401) {
|
||||
return 'Non autorisé. Veuillez vous reconnecter.';
|
||||
} else if (statusCode == 403) {
|
||||
return 'Accès refusé. Vous n\'avez pas les permissions nécessaires.';
|
||||
} else if (statusCode == 404) {
|
||||
return 'Ressource non trouvée.';
|
||||
} else if (statusCode == 409) {
|
||||
return 'Conflit. Cette ressource existe déjà.';
|
||||
} else if (statusCode != null && statusCode >= 500) {
|
||||
return 'Erreur serveur. Veuillez réessayer plus tard.';
|
||||
}
|
||||
return 'Erreur lors de la communication avec le serveur.';
|
||||
case DioExceptionType.cancel:
|
||||
return 'Requête annulée.';
|
||||
case DioExceptionType.unknown:
|
||||
return 'Erreur de connexion. Vérifiez votre connexion internet.';
|
||||
default:
|
||||
return 'Erreur réseau inattendue.';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
143
lib/features/members/bloc/membres_event.dart
Normal file
143
lib/features/members/bloc/membres_event.dart
Normal file
@@ -0,0 +1,143 @@
|
||||
/// Événements pour le BLoC des membres
|
||||
library membres_event;
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../data/models/membre_complete_model.dart';
|
||||
import '../../../shared/models/membre_search_criteria.dart';
|
||||
|
||||
/// Classe de base pour tous les événements des membres
|
||||
abstract class MembresEvent extends Equatable {
|
||||
const MembresEvent();
|
||||
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
/// Événement pour charger la liste des membres
|
||||
class LoadMembres extends MembresEvent {
|
||||
final int page;
|
||||
final int size;
|
||||
final String? recherche;
|
||||
final bool refresh;
|
||||
|
||||
const LoadMembres({
|
||||
this.page = 0,
|
||||
this.size = 20,
|
||||
this.recherche,
|
||||
this.refresh = false,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [page, size, recherche, refresh];
|
||||
}
|
||||
|
||||
/// Événement pour charger un membre par ID
|
||||
class LoadMembreById extends MembresEvent {
|
||||
final String id;
|
||||
|
||||
const LoadMembreById(this.id);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
|
||||
/// Événement pour créer un nouveau membre
|
||||
class CreateMembre extends MembresEvent {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const CreateMembre(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// Événement pour mettre à jour un membre
|
||||
class UpdateMembre extends MembresEvent {
|
||||
final String id;
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const UpdateMembre(this.id, this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id, membre];
|
||||
}
|
||||
|
||||
/// Événement pour supprimer un membre
|
||||
class DeleteMembre extends MembresEvent {
|
||||
final String id;
|
||||
|
||||
const DeleteMembre(this.id);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
|
||||
/// Événement pour activer un membre
|
||||
class ActivateMembre extends MembresEvent {
|
||||
final String id;
|
||||
|
||||
const ActivateMembre(this.id);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
|
||||
/// Événement pour désactiver un membre
|
||||
class DeactivateMembre extends MembresEvent {
|
||||
final String id;
|
||||
|
||||
const DeactivateMembre(this.id);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
|
||||
/// Événement pour recherche avancée
|
||||
class SearchMembres extends MembresEvent {
|
||||
final MembreSearchCriteria criteria;
|
||||
final int page;
|
||||
final int size;
|
||||
|
||||
const SearchMembres({
|
||||
required this.criteria,
|
||||
this.page = 0,
|
||||
this.size = 20,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [criteria, page, size];
|
||||
}
|
||||
|
||||
/// Événement pour charger les membres actifs
|
||||
class LoadActiveMembres extends MembresEvent {
|
||||
final int page;
|
||||
final int size;
|
||||
|
||||
const LoadActiveMembres({
|
||||
this.page = 0,
|
||||
this.size = 20,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [page, size];
|
||||
}
|
||||
|
||||
/// Événement pour charger les membres du bureau
|
||||
class LoadBureauMembres extends MembresEvent {
|
||||
final int page;
|
||||
final int size;
|
||||
|
||||
const LoadBureauMembres({
|
||||
this.page = 0,
|
||||
this.size = 20,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [page, size];
|
||||
}
|
||||
|
||||
/// Événement pour charger les statistiques
|
||||
class LoadMembresStats extends MembresEvent {
|
||||
const LoadMembresStats();
|
||||
}
|
||||
|
||||
180
lib/features/members/bloc/membres_state.dart
Normal file
180
lib/features/members/bloc/membres_state.dart
Normal file
@@ -0,0 +1,180 @@
|
||||
/// États pour le BLoC des membres
|
||||
library membres_state;
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import '../data/models/membre_complete_model.dart';
|
||||
|
||||
/// Classe de base pour tous les états des membres
|
||||
abstract class MembresState extends Equatable {
|
||||
const MembresState();
|
||||
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
/// État initial
|
||||
class MembresInitial extends MembresState {
|
||||
const MembresInitial();
|
||||
}
|
||||
|
||||
/// État de chargement
|
||||
class MembresLoading extends MembresState {
|
||||
const MembresLoading();
|
||||
}
|
||||
|
||||
/// État de chargement avec données existantes (pour refresh)
|
||||
class MembresRefreshing extends MembresState {
|
||||
final List<MembreCompletModel> currentMembres;
|
||||
|
||||
const MembresRefreshing(this.currentMembres);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [currentMembres];
|
||||
}
|
||||
|
||||
/// État de succès avec liste de membres
|
||||
class MembresLoaded extends MembresState {
|
||||
final List<MembreCompletModel> membres;
|
||||
final int totalElements;
|
||||
final int currentPage;
|
||||
final int pageSize;
|
||||
final int totalPages;
|
||||
final bool hasMore;
|
||||
|
||||
const MembresLoaded({
|
||||
required this.membres,
|
||||
required this.totalElements,
|
||||
this.currentPage = 0,
|
||||
this.pageSize = 20,
|
||||
required this.totalPages,
|
||||
}) : hasMore = currentPage < totalPages - 1;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membres, totalElements, currentPage, pageSize, totalPages, hasMore];
|
||||
|
||||
MembresLoaded copyWith({
|
||||
List<MembreCompletModel>? membres,
|
||||
int? totalElements,
|
||||
int? currentPage,
|
||||
int? pageSize,
|
||||
int? totalPages,
|
||||
}) {
|
||||
return MembresLoaded(
|
||||
membres: membres ?? this.membres,
|
||||
totalElements: totalElements ?? this.totalElements,
|
||||
currentPage: currentPage ?? this.currentPage,
|
||||
pageSize: pageSize ?? this.pageSize,
|
||||
totalPages: totalPages ?? this.totalPages,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// État de succès avec un seul membre
|
||||
class MembreDetailLoaded extends MembresState {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const MembreDetailLoaded(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// État de succès après création
|
||||
class MembreCreated extends MembresState {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const MembreCreated(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// État de succès après mise à jour
|
||||
class MembreUpdated extends MembresState {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const MembreUpdated(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// État de succès après suppression
|
||||
class MembreDeleted extends MembresState {
|
||||
final String id;
|
||||
|
||||
const MembreDeleted(this.id);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [id];
|
||||
}
|
||||
|
||||
/// État de succès après activation
|
||||
class MembreActivated extends MembresState {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const MembreActivated(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// État de succès après désactivation
|
||||
class MembreDeactivated extends MembresState {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const MembreDeactivated(this.membre);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [membre];
|
||||
}
|
||||
|
||||
/// État avec statistiques
|
||||
class MembresStatsLoaded extends MembresState {
|
||||
final Map<String, dynamic> stats;
|
||||
|
||||
const MembresStatsLoaded(this.stats);
|
||||
|
||||
@override
|
||||
List<Object?> get props => [stats];
|
||||
}
|
||||
|
||||
/// État d'erreur
|
||||
class MembresError extends MembresState {
|
||||
final String message;
|
||||
final String? code;
|
||||
final dynamic error;
|
||||
|
||||
const MembresError({
|
||||
required this.message,
|
||||
this.code,
|
||||
this.error,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [message, code, error];
|
||||
}
|
||||
|
||||
/// État d'erreur réseau
|
||||
class MembresNetworkError extends MembresError {
|
||||
const MembresNetworkError({
|
||||
required super.message,
|
||||
super.code,
|
||||
super.error,
|
||||
});
|
||||
}
|
||||
|
||||
/// État d'erreur de validation
|
||||
class MembresValidationError extends MembresError {
|
||||
final Map<String, String> validationErrors;
|
||||
|
||||
const MembresValidationError({
|
||||
required super.message,
|
||||
required this.validationErrors,
|
||||
super.code,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [message, code, validationErrors];
|
||||
}
|
||||
|
||||
373
lib/features/members/data/models/membre_complete_model.dart
Normal file
373
lib/features/members/data/models/membre_complete_model.dart
Normal file
@@ -0,0 +1,373 @@
|
||||
/// Modèle complet de données pour un membre
|
||||
/// Aligné avec le backend MembreDTO
|
||||
library membre_complete_model;
|
||||
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:json_annotation/json_annotation.dart';
|
||||
|
||||
part 'membre_complete_model.g.dart';
|
||||
|
||||
/// Énumération des genres
|
||||
enum Genre {
|
||||
@JsonValue('HOMME')
|
||||
homme,
|
||||
@JsonValue('FEMME')
|
||||
femme,
|
||||
@JsonValue('AUTRE')
|
||||
autre,
|
||||
}
|
||||
|
||||
/// Énumération des statuts de membre
|
||||
enum StatutMembre {
|
||||
@JsonValue('ACTIF')
|
||||
actif,
|
||||
@JsonValue('INACTIF')
|
||||
inactif,
|
||||
@JsonValue('SUSPENDU')
|
||||
suspendu,
|
||||
@JsonValue('EN_ATTENTE')
|
||||
enAttente,
|
||||
}
|
||||
|
||||
/// Niveau de vigilance KYC (LCB-FT)
|
||||
enum NiveauVigilanceKyc {
|
||||
@JsonValue('SIMPLIFIE')
|
||||
simplifie,
|
||||
@JsonValue('RENFORCE')
|
||||
renforce,
|
||||
}
|
||||
|
||||
/// Statut KYC (vérification identité)
|
||||
enum StatutKyc {
|
||||
@JsonValue('NON_VERIFIE')
|
||||
nonVerifie,
|
||||
@JsonValue('EN_COURS')
|
||||
enCours,
|
||||
@JsonValue('VERIFIE')
|
||||
verifie,
|
||||
@JsonValue('REFUSE')
|
||||
refuse,
|
||||
}
|
||||
|
||||
/// Modèle complet d'un membre
|
||||
@JsonSerializable()
|
||||
class MembreCompletModel extends Equatable {
|
||||
/// Identifiant unique
|
||||
final String? id;
|
||||
|
||||
/// Nom de famille
|
||||
final String nom;
|
||||
|
||||
/// Prénom
|
||||
final String prenom;
|
||||
|
||||
/// Email (unique)
|
||||
final String email;
|
||||
|
||||
/// Téléphone
|
||||
final String? telephone;
|
||||
|
||||
/// Date de naissance
|
||||
@JsonKey(name: 'dateNaissance')
|
||||
final DateTime? dateNaissance;
|
||||
|
||||
/// Genre
|
||||
final Genre? genre;
|
||||
|
||||
/// Adresse complète
|
||||
final String? adresse;
|
||||
|
||||
/// Ville
|
||||
final String? ville;
|
||||
|
||||
/// Code postal
|
||||
@JsonKey(name: 'codePostal')
|
||||
final String? codePostal;
|
||||
|
||||
/// Région
|
||||
final String? region;
|
||||
|
||||
/// Pays
|
||||
final String? pays;
|
||||
|
||||
/// Profession
|
||||
final String? profession;
|
||||
|
||||
/// Nationalité
|
||||
final String? nationalite;
|
||||
|
||||
/// URL de la photo
|
||||
final String? photo;
|
||||
|
||||
/// Statut du membre
|
||||
final StatutMembre statut;
|
||||
|
||||
/// Rôle dans l'organisation
|
||||
final String? role;
|
||||
|
||||
/// ID de l'organisation
|
||||
@JsonKey(name: 'organisationId')
|
||||
final String? organisationId;
|
||||
|
||||
/// Nom de l'organisation (pour affichage)
|
||||
@JsonKey(name: 'organisationNom')
|
||||
final String? organisationNom;
|
||||
|
||||
/// Date d'adhésion
|
||||
@JsonKey(name: 'dateAdhesion')
|
||||
final DateTime? dateAdhesion;
|
||||
|
||||
/// Date de fin d'adhésion
|
||||
@JsonKey(name: 'dateFinAdhesion')
|
||||
final DateTime? dateFinAdhesion;
|
||||
|
||||
/// Membre du bureau
|
||||
@JsonKey(name: 'membreBureau')
|
||||
final bool membreBureau;
|
||||
|
||||
/// Est responsable
|
||||
final bool responsable;
|
||||
|
||||
/// Fonction au bureau
|
||||
@JsonKey(name: 'fonctionBureau')
|
||||
final String? fonctionBureau;
|
||||
|
||||
/// Numéro de membre (unique)
|
||||
@JsonKey(name: 'numeroMembre')
|
||||
final String? numeroMembre;
|
||||
|
||||
/// Cotisation à jour
|
||||
@JsonKey(name: 'cotisationAJour')
|
||||
final bool cotisationAJour;
|
||||
|
||||
/// Nombre d'événements participés
|
||||
@JsonKey(name: 'nombreEvenementsParticipes')
|
||||
final int nombreEvenementsParticipes;
|
||||
|
||||
/// Dernière activité
|
||||
@JsonKey(name: 'derniereActivite')
|
||||
final DateTime? derniereActivite;
|
||||
|
||||
/// Notes internes
|
||||
final String? notes;
|
||||
|
||||
/// Date de création
|
||||
@JsonKey(name: 'dateCreation')
|
||||
final DateTime? dateCreation;
|
||||
|
||||
/// Date de modification
|
||||
@JsonKey(name: 'dateModification')
|
||||
final DateTime? dateModification;
|
||||
|
||||
/// Actif
|
||||
final bool actif;
|
||||
|
||||
/// Niveau de vigilance KYC (LCB-FT anti-blanchiment)
|
||||
@JsonKey(name: 'niveauVigilanceKyc')
|
||||
final NiveauVigilanceKyc? niveauVigilanceKyc;
|
||||
|
||||
/// Statut de vérification KYC (Know Your Customer)
|
||||
@JsonKey(name: 'statutKyc')
|
||||
final StatutKyc? statutKyc;
|
||||
|
||||
/// Date de vérification de l'identité (LCB-FT)
|
||||
@JsonKey(name: 'dateVerificationIdentite')
|
||||
final DateTime? dateVerificationIdentite;
|
||||
|
||||
const MembreCompletModel({
|
||||
this.id,
|
||||
required this.nom,
|
||||
required this.prenom,
|
||||
required this.email,
|
||||
this.telephone,
|
||||
this.dateNaissance,
|
||||
this.genre,
|
||||
this.adresse,
|
||||
this.ville,
|
||||
this.codePostal,
|
||||
this.region,
|
||||
this.pays,
|
||||
this.profession,
|
||||
this.nationalite,
|
||||
this.photo,
|
||||
this.statut = StatutMembre.actif,
|
||||
this.role,
|
||||
this.organisationId,
|
||||
this.organisationNom,
|
||||
this.dateAdhesion,
|
||||
this.dateFinAdhesion,
|
||||
this.membreBureau = false,
|
||||
this.responsable = false,
|
||||
this.fonctionBureau,
|
||||
this.numeroMembre,
|
||||
this.cotisationAJour = false,
|
||||
this.nombreEvenementsParticipes = 0,
|
||||
this.derniereActivite,
|
||||
this.notes,
|
||||
this.dateCreation,
|
||||
this.dateModification,
|
||||
this.actif = true,
|
||||
this.niveauVigilanceKyc,
|
||||
this.statutKyc,
|
||||
this.dateVerificationIdentite,
|
||||
});
|
||||
|
||||
/// Création depuis JSON
|
||||
factory MembreCompletModel.fromJson(Map<String, dynamic> json) =>
|
||||
_$MembreCompletModelFromJson(json);
|
||||
|
||||
/// Conversion vers JSON
|
||||
Map<String, dynamic> toJson() => _$MembreCompletModelToJson(this);
|
||||
|
||||
/// Copie avec modifications
|
||||
MembreCompletModel copyWith({
|
||||
String? id,
|
||||
String? nom,
|
||||
String? prenom,
|
||||
String? email,
|
||||
String? telephone,
|
||||
DateTime? dateNaissance,
|
||||
Genre? genre,
|
||||
String? adresse,
|
||||
String? ville,
|
||||
String? codePostal,
|
||||
String? region,
|
||||
String? pays,
|
||||
String? profession,
|
||||
String? nationalite,
|
||||
String? photo,
|
||||
StatutMembre? statut,
|
||||
String? role,
|
||||
String? organisationId,
|
||||
String? organisationNom,
|
||||
DateTime? dateAdhesion,
|
||||
DateTime? dateFinAdhesion,
|
||||
bool? membreBureau,
|
||||
bool? responsable,
|
||||
String? fonctionBureau,
|
||||
String? numeroMembre,
|
||||
bool? cotisationAJour,
|
||||
int? nombreEvenementsParticipes,
|
||||
DateTime? derniereActivite,
|
||||
String? notes,
|
||||
DateTime? dateCreation,
|
||||
DateTime? dateModification,
|
||||
bool? actif,
|
||||
NiveauVigilanceKyc? niveauVigilanceKyc,
|
||||
StatutKyc? statutKyc,
|
||||
DateTime? dateVerificationIdentite,
|
||||
}) {
|
||||
return MembreCompletModel(
|
||||
id: id ?? this.id,
|
||||
nom: nom ?? this.nom,
|
||||
prenom: prenom ?? this.prenom,
|
||||
email: email ?? this.email,
|
||||
telephone: telephone ?? this.telephone,
|
||||
dateNaissance: dateNaissance ?? this.dateNaissance,
|
||||
genre: genre ?? this.genre,
|
||||
adresse: adresse ?? this.adresse,
|
||||
ville: ville ?? this.ville,
|
||||
codePostal: codePostal ?? this.codePostal,
|
||||
region: region ?? this.region,
|
||||
pays: pays ?? this.pays,
|
||||
profession: profession ?? this.profession,
|
||||
nationalite: nationalite ?? this.nationalite,
|
||||
photo: photo ?? this.photo,
|
||||
statut: statut ?? this.statut,
|
||||
role: role ?? this.role,
|
||||
organisationId: organisationId ?? this.organisationId,
|
||||
organisationNom: organisationNom ?? this.organisationNom,
|
||||
dateAdhesion: dateAdhesion ?? this.dateAdhesion,
|
||||
dateFinAdhesion: dateFinAdhesion ?? this.dateFinAdhesion,
|
||||
membreBureau: membreBureau ?? this.membreBureau,
|
||||
responsable: responsable ?? this.responsable,
|
||||
fonctionBureau: fonctionBureau ?? this.fonctionBureau,
|
||||
numeroMembre: numeroMembre ?? this.numeroMembre,
|
||||
cotisationAJour: cotisationAJour ?? this.cotisationAJour,
|
||||
nombreEvenementsParticipes: nombreEvenementsParticipes ?? this.nombreEvenementsParticipes,
|
||||
derniereActivite: derniereActivite ?? this.derniereActivite,
|
||||
notes: notes ?? this.notes,
|
||||
dateCreation: dateCreation ?? this.dateCreation,
|
||||
dateModification: dateModification ?? this.dateModification,
|
||||
actif: actif ?? this.actif,
|
||||
niveauVigilanceKyc: niveauVigilanceKyc ?? this.niveauVigilanceKyc,
|
||||
statutKyc: statutKyc ?? this.statutKyc,
|
||||
dateVerificationIdentite: dateVerificationIdentite ?? this.dateVerificationIdentite,
|
||||
);
|
||||
}
|
||||
|
||||
/// Nom complet
|
||||
String get nomComplet => '$prenom $nom';
|
||||
|
||||
/// Initiales
|
||||
String get initiales {
|
||||
final p = prenom.isNotEmpty ? prenom[0].toUpperCase() : '';
|
||||
final n = nom.isNotEmpty ? nom[0].toUpperCase() : '';
|
||||
return '$p$n';
|
||||
}
|
||||
|
||||
/// Âge calculé
|
||||
int? get age {
|
||||
if (dateNaissance == null) return null;
|
||||
final now = DateTime.now();
|
||||
int age = now.year - dateNaissance!.year;
|
||||
if (now.month < dateNaissance!.month ||
|
||||
(now.month == dateNaissance!.month && now.day < dateNaissance!.day)) {
|
||||
age--;
|
||||
}
|
||||
return age;
|
||||
}
|
||||
|
||||
/// Ancienneté en jours
|
||||
int? get ancienneteJours {
|
||||
if (dateAdhesion == null) return null;
|
||||
return DateTime.now().difference(dateAdhesion!).inDays;
|
||||
}
|
||||
|
||||
/// Est actif et cotisation à jour
|
||||
bool get estActifEtAJour => actif && statut == StatutMembre.actif && cotisationAJour;
|
||||
|
||||
@override
|
||||
List<Object?> get props => [
|
||||
id,
|
||||
nom,
|
||||
prenom,
|
||||
email,
|
||||
telephone,
|
||||
dateNaissance,
|
||||
genre,
|
||||
adresse,
|
||||
ville,
|
||||
codePostal,
|
||||
region,
|
||||
pays,
|
||||
profession,
|
||||
nationalite,
|
||||
photo,
|
||||
statut,
|
||||
role,
|
||||
organisationId,
|
||||
organisationNom,
|
||||
dateAdhesion,
|
||||
dateFinAdhesion,
|
||||
membreBureau,
|
||||
responsable,
|
||||
fonctionBureau,
|
||||
numeroMembre,
|
||||
cotisationAJour,
|
||||
nombreEvenementsParticipes,
|
||||
derniereActivite,
|
||||
notes,
|
||||
dateCreation,
|
||||
dateModification,
|
||||
actif,
|
||||
niveauVigilanceKyc,
|
||||
statutKyc,
|
||||
dateVerificationIdentite,
|
||||
];
|
||||
|
||||
@override
|
||||
String toString() =>
|
||||
'MembreCompletModel(id: $id, nom: $nomComplet, email: $email, statut: $statut)';
|
||||
}
|
||||
|
||||
129
lib/features/members/data/models/membre_complete_model.g.dart
Normal file
129
lib/features/members/data/models/membre_complete_model.g.dart
Normal file
@@ -0,0 +1,129 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'membre_complete_model.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// JsonSerializableGenerator
|
||||
// **************************************************************************
|
||||
|
||||
MembreCompletModel _$MembreCompletModelFromJson(Map<String, dynamic> json) =>
|
||||
MembreCompletModel(
|
||||
id: json['id'] as String?,
|
||||
nom: json['nom'] as String,
|
||||
prenom: json['prenom'] as String,
|
||||
email: json['email'] as String,
|
||||
telephone: json['telephone'] as String?,
|
||||
dateNaissance: json['dateNaissance'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateNaissance'] as String),
|
||||
genre: $enumDecodeNullable(_$GenreEnumMap, json['genre']),
|
||||
adresse: json['adresse'] as String?,
|
||||
ville: json['ville'] as String?,
|
||||
codePostal: json['codePostal'] as String?,
|
||||
region: json['region'] as String?,
|
||||
pays: json['pays'] as String?,
|
||||
profession: json['profession'] as String?,
|
||||
nationalite: json['nationalite'] as String?,
|
||||
photo: json['photo'] as String?,
|
||||
statut: $enumDecodeNullable(_$StatutMembreEnumMap, json['statut']) ??
|
||||
StatutMembre.actif,
|
||||
role: json['role'] as String?,
|
||||
organisationId: json['organisationId'] as String?,
|
||||
organisationNom: json['organisationNom'] as String?,
|
||||
dateAdhesion: json['dateAdhesion'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateAdhesion'] as String),
|
||||
dateFinAdhesion: json['dateFinAdhesion'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateFinAdhesion'] as String),
|
||||
membreBureau: json['membreBureau'] as bool? ?? false,
|
||||
responsable: json['responsable'] as bool? ?? false,
|
||||
fonctionBureau: json['fonctionBureau'] as String?,
|
||||
numeroMembre: json['numeroMembre'] as String?,
|
||||
cotisationAJour: json['cotisationAJour'] as bool? ?? false,
|
||||
nombreEvenementsParticipes:
|
||||
(json['nombreEvenementsParticipes'] as num?)?.toInt() ?? 0,
|
||||
derniereActivite: json['derniereActivite'] == null
|
||||
? null
|
||||
: DateTime.parse(json['derniereActivite'] as String),
|
||||
notes: json['notes'] as String?,
|
||||
dateCreation: json['dateCreation'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateCreation'] as String),
|
||||
dateModification: json['dateModification'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateModification'] as String),
|
||||
actif: json['actif'] as bool? ?? true,
|
||||
niveauVigilanceKyc: $enumDecodeNullable(
|
||||
_$NiveauVigilanceKycEnumMap, json['niveauVigilanceKyc']),
|
||||
statutKyc: $enumDecodeNullable(_$StatutKycEnumMap, json['statutKyc']),
|
||||
dateVerificationIdentite: json['dateVerificationIdentite'] == null
|
||||
? null
|
||||
: DateTime.parse(json['dateVerificationIdentite'] as String),
|
||||
);
|
||||
|
||||
Map<String, dynamic> _$MembreCompletModelToJson(MembreCompletModel instance) =>
|
||||
<String, dynamic>{
|
||||
'id': instance.id,
|
||||
'nom': instance.nom,
|
||||
'prenom': instance.prenom,
|
||||
'email': instance.email,
|
||||
'telephone': instance.telephone,
|
||||
'dateNaissance': instance.dateNaissance?.toIso8601String(),
|
||||
'genre': _$GenreEnumMap[instance.genre],
|
||||
'adresse': instance.adresse,
|
||||
'ville': instance.ville,
|
||||
'codePostal': instance.codePostal,
|
||||
'region': instance.region,
|
||||
'pays': instance.pays,
|
||||
'profession': instance.profession,
|
||||
'nationalite': instance.nationalite,
|
||||
'photo': instance.photo,
|
||||
'statut': _$StatutMembreEnumMap[instance.statut]!,
|
||||
'role': instance.role,
|
||||
'organisationId': instance.organisationId,
|
||||
'organisationNom': instance.organisationNom,
|
||||
'dateAdhesion': instance.dateAdhesion?.toIso8601String(),
|
||||
'dateFinAdhesion': instance.dateFinAdhesion?.toIso8601String(),
|
||||
'membreBureau': instance.membreBureau,
|
||||
'responsable': instance.responsable,
|
||||
'fonctionBureau': instance.fonctionBureau,
|
||||
'numeroMembre': instance.numeroMembre,
|
||||
'cotisationAJour': instance.cotisationAJour,
|
||||
'nombreEvenementsParticipes': instance.nombreEvenementsParticipes,
|
||||
'derniereActivite': instance.derniereActivite?.toIso8601String(),
|
||||
'notes': instance.notes,
|
||||
'dateCreation': instance.dateCreation?.toIso8601String(),
|
||||
'dateModification': instance.dateModification?.toIso8601String(),
|
||||
'actif': instance.actif,
|
||||
'niveauVigilanceKyc':
|
||||
_$NiveauVigilanceKycEnumMap[instance.niveauVigilanceKyc],
|
||||
'statutKyc': _$StatutKycEnumMap[instance.statutKyc],
|
||||
'dateVerificationIdentite':
|
||||
instance.dateVerificationIdentite?.toIso8601String(),
|
||||
};
|
||||
|
||||
const _$GenreEnumMap = {
|
||||
Genre.homme: 'HOMME',
|
||||
Genre.femme: 'FEMME',
|
||||
Genre.autre: 'AUTRE',
|
||||
};
|
||||
|
||||
const _$StatutMembreEnumMap = {
|
||||
StatutMembre.actif: 'ACTIF',
|
||||
StatutMembre.inactif: 'INACTIF',
|
||||
StatutMembre.suspendu: 'SUSPENDU',
|
||||
StatutMembre.enAttente: 'EN_ATTENTE',
|
||||
};
|
||||
|
||||
const _$NiveauVigilanceKycEnumMap = {
|
||||
NiveauVigilanceKyc.simplifie: 'SIMPLIFIE',
|
||||
NiveauVigilanceKyc.renforce: 'RENFORCE',
|
||||
};
|
||||
|
||||
const _$StatutKycEnumMap = {
|
||||
StatutKyc.nonVerifie: 'NON_VERIFIE',
|
||||
StatutKyc.enCours: 'EN_COURS',
|
||||
StatutKyc.verifie: 'VERIFIE',
|
||||
StatutKyc.refuse: 'REFUSE',
|
||||
};
|
||||
69
lib/features/members/data/models/membre_model.dart
Normal file
69
lib/features/members/data/models/membre_model.dart
Normal file
@@ -0,0 +1,69 @@
|
||||
/// Modèle de données pour un membre
|
||||
class MembreModel {
|
||||
final String id;
|
||||
final String nom;
|
||||
final String prenom;
|
||||
final String email;
|
||||
final String? telephone;
|
||||
final String? statut;
|
||||
final String? role;
|
||||
final OrganisationModel? organisation;
|
||||
|
||||
const MembreModel({
|
||||
required this.id,
|
||||
required this.nom,
|
||||
required this.prenom,
|
||||
required this.email,
|
||||
this.telephone,
|
||||
this.statut,
|
||||
this.role,
|
||||
this.organisation,
|
||||
});
|
||||
|
||||
factory MembreModel.fromJson(Map<String, dynamic> json) {
|
||||
return MembreModel(
|
||||
id: json['id'] as String,
|
||||
nom: json['nom'] as String,
|
||||
prenom: json['prenom'] as String,
|
||||
email: json['email'] as String,
|
||||
telephone: json['telephone'] as String?,
|
||||
statut: json['statut'] as String?,
|
||||
role: json['role'] as String?,
|
||||
organisation: json['organisation'] != null
|
||||
? OrganisationModel.fromJson(json['organisation'] as Map<String, dynamic>)
|
||||
: null,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'id': id,
|
||||
'nom': nom,
|
||||
'prenom': prenom,
|
||||
'email': email,
|
||||
'telephone': telephone,
|
||||
'statut': statut,
|
||||
'role': role,
|
||||
'organisation': organisation?.toJson(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Modèle pour une organisation
|
||||
class OrganisationModel {
|
||||
final String? nom;
|
||||
|
||||
const OrganisationModel({this.nom});
|
||||
|
||||
factory OrganisationModel.fromJson(Map<String, dynamic> json) {
|
||||
return OrganisationModel(
|
||||
nom: json['nom'] as String?,
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'nom': nom,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,325 @@
|
||||
/// Implémentation du repository pour la gestion des membres
|
||||
/// Interface avec l'API backend MembreResource
|
||||
library membre_repository_impl;
|
||||
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:unionflow_mobile_apps/core/network/api_client.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../domain/repositories/membre_repository.dart';
|
||||
import '../models/membre_complete_model.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
|
||||
/// Implémentation du repository des membres
|
||||
@LazySingleton(as: IMembreRepository)
|
||||
class MembreRepositoryImpl implements IMembreRepository {
|
||||
final ApiClient _apiClient;
|
||||
static const String _baseUrl = '/api/membres';
|
||||
|
||||
MembreRepositoryImpl(this._apiClient);
|
||||
|
||||
@override
|
||||
Future<MembreSearchResult> getMembres({
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
String? recherche,
|
||||
}) async {
|
||||
try {
|
||||
// Si une recherche est fournie, utiliser l'endpoint de recherche
|
||||
if (recherche?.isNotEmpty == true) {
|
||||
final response = await _apiClient.get(
|
||||
'$_baseUrl/recherche',
|
||||
queryParameters: {
|
||||
'q': recherche,
|
||||
'page': page,
|
||||
'size': size,
|
||||
},
|
||||
);
|
||||
|
||||
return _parseMembreSearchResult(response, page, size, MembreSearchCriteria(query: recherche));
|
||||
}
|
||||
|
||||
// Sinon, récupérer tous les membres
|
||||
final response = await _apiClient.get(
|
||||
_baseUrl,
|
||||
queryParameters: {
|
||||
'page': page,
|
||||
'size': size,
|
||||
},
|
||||
);
|
||||
|
||||
return _parseMembreSearchResult(response, page, size, const MembreSearchCriteria());
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la récupération des membres: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la récupération des membres: $e');
|
||||
}
|
||||
}
|
||||
|
||||
/// Normalise les clés backend pour alignement API ↔ modèle (cohérence des données).
|
||||
MembreCompletModel _normalizeAndParseMembre(Map<String, dynamic> map) {
|
||||
if (map.containsKey('associationNom') && !map.containsKey('organisationNom')) {
|
||||
map['organisationNom'] = map['associationNom'];
|
||||
}
|
||||
if (map.containsKey('organisationId') && map['organisationId'] != null && map['organisationId'] is! String) {
|
||||
map['organisationId'] = map['organisationId'].toString();
|
||||
}
|
||||
if (map.containsKey('statutCompte') && !map.containsKey('statut')) {
|
||||
map['statut'] = map['statutCompte'];
|
||||
}
|
||||
if (map.containsKey('photoUrl') && !map.containsKey('photo')) {
|
||||
map['photo'] = map['photoUrl'];
|
||||
}
|
||||
if (map['id'] != null && map['id'] is! String) {
|
||||
map['id'] = map['id'].toString();
|
||||
}
|
||||
return MembreCompletModel.fromJson(map);
|
||||
}
|
||||
|
||||
/// Parse la réponse API et retourne un MembreSearchResult
|
||||
/// Gère les deux formats possibles : List (simple) ou Map (paginé)
|
||||
MembreSearchResult _parseMembreSearchResult(
|
||||
Response response,
|
||||
int page,
|
||||
int size,
|
||||
MembreSearchCriteria criteria,
|
||||
) {
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Erreur HTTP: ${response.statusCode}');
|
||||
}
|
||||
|
||||
// Format simple : liste directe de membres
|
||||
if (response.data is List) {
|
||||
final List<dynamic> listData = response.data as List<dynamic>;
|
||||
final membres = listData
|
||||
.map((e) => _normalizeAndParseMembre(e as Map<String, dynamic>))
|
||||
.toList();
|
||||
|
||||
return MembreSearchResult(
|
||||
membres: membres,
|
||||
totalElements: membres.length,
|
||||
totalPages: 1,
|
||||
currentPage: page,
|
||||
pageSize: membres.length,
|
||||
numberOfElements: membres.length,
|
||||
hasNext: false,
|
||||
hasPrevious: false,
|
||||
isFirst: true,
|
||||
isLast: true,
|
||||
criteria: criteria,
|
||||
executionTimeMs: 0,
|
||||
);
|
||||
}
|
||||
|
||||
// Format paginé : PagedResponse backend (data, total, page, size, totalPages)
|
||||
final Map<String, dynamic> data = response.data as Map<String, dynamic>;
|
||||
final List<dynamic>? listData = data['data'] as List<dynamic>?;
|
||||
if (listData != null) {
|
||||
final membres = listData
|
||||
.map((e) => _normalizeAndParseMembre(Map<String, dynamic>.from(e as Map<String, dynamic>)))
|
||||
.toList();
|
||||
final total = (data['total'] as num?)?.toInt() ?? membres.length;
|
||||
final currentPage = (data['page'] as num?)?.toInt() ?? page;
|
||||
final pageSize = (data['size'] as num?)?.toInt() ?? size;
|
||||
final totalPages = (data['totalPages'] as num?)?.toInt() ?? (total > 0 ? 1 : 0);
|
||||
return MembreSearchResult(
|
||||
membres: membres,
|
||||
totalElements: total,
|
||||
totalPages: totalPages,
|
||||
currentPage: currentPage,
|
||||
pageSize: pageSize,
|
||||
numberOfElements: membres.length,
|
||||
hasNext: currentPage + 1 < totalPages,
|
||||
hasPrevious: currentPage > 0,
|
||||
isFirst: currentPage == 0,
|
||||
isLast: currentPage >= totalPages - 1,
|
||||
criteria: criteria,
|
||||
executionTimeMs: 0,
|
||||
);
|
||||
}
|
||||
return MembreSearchResult.fromJson(data);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@override
|
||||
Future<MembreCompletModel?> getMembreById(String id) async {
|
||||
try {
|
||||
final response = await _apiClient.get('$_baseUrl/$id');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
|
||||
} else if (response.statusCode == 404) {
|
||||
return null;
|
||||
} else {
|
||||
throw Exception('Erreur lors de la récupération du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
if (e.response?.statusCode == 404) {
|
||||
return null;
|
||||
}
|
||||
throw Exception('Erreur réseau lors de la récupération du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la récupération du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreCompletModel> createMembre(MembreCompletModel membre) async {
|
||||
try {
|
||||
final response = await _apiClient.post(
|
||||
_baseUrl,
|
||||
data: membre.toJson(),
|
||||
);
|
||||
|
||||
if (response.statusCode == 201 || response.statusCode == 200) {
|
||||
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
|
||||
} else {
|
||||
throw Exception('Erreur lors de la création du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la création du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la création du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreCompletModel> updateMembre(String id, MembreCompletModel membre) async {
|
||||
try {
|
||||
final response = await _apiClient.put(
|
||||
'$_baseUrl/$id',
|
||||
data: membre.toJson(),
|
||||
);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
|
||||
} else {
|
||||
throw Exception('Erreur lors de la mise à jour du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la mise à jour du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la mise à jour du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> deleteMembre(String id) async {
|
||||
try {
|
||||
final response = await _apiClient.delete('$_baseUrl/$id');
|
||||
|
||||
if (response.statusCode != 204 && response.statusCode != 200) {
|
||||
throw Exception('Erreur lors de la suppression du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la suppression du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la suppression du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreCompletModel> activateMembre(String id) async {
|
||||
try {
|
||||
final response = await _apiClient.post('$_baseUrl/$id/activer');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
|
||||
} else {
|
||||
throw Exception('Erreur lors de l\'activation du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de l\'activation du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de l\'activation du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreCompletModel> deactivateMembre(String id) async {
|
||||
try {
|
||||
final response = await _apiClient.post('$_baseUrl/$id/desactiver');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
|
||||
} else {
|
||||
throw Exception('Erreur lors de la désactivation du membre: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la désactivation du membre: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la désactivation du membre: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreSearchResult> searchMembres({
|
||||
required MembreSearchCriteria criteria,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
try {
|
||||
// Les paramètres de pagination vont dans queryParameters
|
||||
// Les critères de recherche vont directement dans le body
|
||||
final response = await _apiClient.post(
|
||||
'$_baseUrl/search/advanced',
|
||||
queryParameters: {
|
||||
'page': page,
|
||||
'size': size,
|
||||
},
|
||||
data: criteria.toJson(),
|
||||
);
|
||||
|
||||
return _parseMembreSearchResult(response, page, size, criteria);
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la recherche de membres: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la recherche de membres: $e');
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreSearchResult> getActiveMembers({int page = 0, int size = 20}) async {
|
||||
// Utiliser la recherche avancée avec le critère statut=ACTIF
|
||||
return searchMembres(
|
||||
criteria: const MembreSearchCriteria(
|
||||
statut: 'ACTIF',
|
||||
includeInactifs: false,
|
||||
),
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<MembreSearchResult> getBureauMembers({int page = 0, int size = 20}) async {
|
||||
// Utiliser la recherche avancée avec le critère membreBureau=true
|
||||
return searchMembres(
|
||||
criteria: const MembreSearchCriteria(
|
||||
membreBureau: true,
|
||||
statut: 'ACTIF',
|
||||
),
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> getMembresStats() async {
|
||||
try {
|
||||
final response = await _apiClient.get('$_baseUrl/statistiques');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return response.data as Map<String, dynamic>;
|
||||
} else {
|
||||
throw Exception('Erreur lors de la récupération des statistiques: ${response.statusCode}');
|
||||
}
|
||||
} on DioException catch (e) {
|
||||
throw Exception('Erreur réseau lors de la récupération des statistiques: ${e.message}');
|
||||
} catch (e) {
|
||||
throw Exception('Erreur inattendue lors de la récupération des statistiques: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
282
lib/features/members/data/services/membre_search_service.dart
Normal file
282
lib/features/members/data/services/membre_search_service.dart
Normal file
@@ -0,0 +1,282 @@
|
||||
import 'package:dio/dio.dart';
|
||||
import 'package:injectable/injectable.dart';
|
||||
import 'package:unionflow_mobile_apps/core/network/api_client.dart';
|
||||
import 'package:unionflow_mobile_apps/core/utils/logger.dart';
|
||||
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
|
||||
/// Service pour la recherche avancée de membres
|
||||
/// Gère les appels API vers l'endpoint de recherche sophistiquée
|
||||
@lazySingleton
|
||||
class MembreSearchService {
|
||||
final ApiClient _apiClient;
|
||||
|
||||
MembreSearchService(this._apiClient);
|
||||
|
||||
/// Effectue une recherche avancée de membres
|
||||
///
|
||||
/// [criteria] Critères de recherche
|
||||
/// [page] Numéro de page (0-based)
|
||||
/// [size] Taille de la page
|
||||
/// [sortField] Champ de tri
|
||||
/// [sortDirection] Direction du tri (asc/desc)
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les résultats paginés
|
||||
Future<MembreSearchResult> searchMembresAdvanced({
|
||||
required MembreSearchCriteria criteria,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
String sortField = 'nom',
|
||||
String sortDirection = 'asc',
|
||||
}) async {
|
||||
AppLogger.info('Recherche avancée de membres: ${criteria.description}');
|
||||
|
||||
try {
|
||||
// Validation des critères
|
||||
if (!criteria.hasAnyCriteria) {
|
||||
throw Exception('Au moins un critère de recherche doit être spécifié');
|
||||
}
|
||||
|
||||
if (!criteria.isValid) {
|
||||
throw Exception('Critères de recherche invalides');
|
||||
}
|
||||
|
||||
// Préparation des paramètres de requête
|
||||
final queryParams = {
|
||||
'page': page.toString(),
|
||||
'size': size.toString(),
|
||||
'sort': sortField,
|
||||
'direction': sortDirection,
|
||||
};
|
||||
|
||||
// Appel API
|
||||
final response = await _apiClient.post(
|
||||
'/api/membres/search/advanced',
|
||||
data: criteria.toJson(),
|
||||
queryParameters: queryParams,
|
||||
);
|
||||
|
||||
// Parsing de la réponse
|
||||
final result = MembreSearchResult.fromJson(response.data);
|
||||
|
||||
AppLogger.info('Recherche terminée: ${result.totalElements} résultats en ${result.executionTimeMs}ms');
|
||||
|
||||
return result;
|
||||
} on DioException catch (e, st) {
|
||||
AppLogger.error('MembreSearchService: recherche avancée échouée', error: e, stackTrace: st);
|
||||
rethrow;
|
||||
} catch (e, st) {
|
||||
AppLogger.error('MembreSearchService: erreur inattendue recherche', error: e, stackTrace: st);
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
/// Recherche rapide par terme général
|
||||
///
|
||||
/// [query] Terme de recherche
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les résultats
|
||||
Future<MembreSearchResult> quickSearch({
|
||||
required String query,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria.quickSearch(query);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche des membres actifs uniquement
|
||||
///
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres actifs
|
||||
Future<MembreSearchResult> searchActiveMembers({
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
return searchMembresAdvanced(
|
||||
criteria: MembreSearchCriteria.activeMembers,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche des membres du bureau
|
||||
///
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres du bureau
|
||||
Future<MembreSearchResult> searchBureauMembers({
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
return searchMembresAdvanced(
|
||||
criteria: MembreSearchCriteria.bureauMembers,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche par organisation
|
||||
///
|
||||
/// [organisationIds] Liste des IDs d'organisations
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres des organisations
|
||||
Future<MembreSearchResult> searchByOrganisations({
|
||||
required List<String> organisationIds,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria(
|
||||
organisationIds: organisationIds,
|
||||
statut: 'ACTIF',
|
||||
);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche par tranche d'âge
|
||||
///
|
||||
/// [ageMin] Âge minimum
|
||||
/// [ageMax] Âge maximum
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres dans la tranche d'âge
|
||||
Future<MembreSearchResult> searchByAgeRange({
|
||||
int? ageMin,
|
||||
int? ageMax,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria(
|
||||
ageMin: ageMin,
|
||||
ageMax: ageMax,
|
||||
statut: 'ACTIF',
|
||||
);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche par région
|
||||
///
|
||||
/// [region] Nom de la région
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres de la région
|
||||
Future<MembreSearchResult> searchByRegion({
|
||||
required String region,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria(
|
||||
region: region,
|
||||
statut: 'ACTIF',
|
||||
);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche par rôles
|
||||
///
|
||||
/// [roles] Liste des rôles
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres ayant ces rôles
|
||||
Future<MembreSearchResult> searchByRoles({
|
||||
required List<String> roles,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria(
|
||||
roles: roles,
|
||||
statut: 'ACTIF',
|
||||
);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Recherche par période d'adhésion
|
||||
///
|
||||
/// [dateMin] Date minimum (ISO 8601)
|
||||
/// [dateMax] Date maximum (ISO 8601)
|
||||
/// [page] Numéro de page
|
||||
/// [size] Taille de la page
|
||||
///
|
||||
/// Returns [MembreSearchResult] avec les membres adhérés dans la période
|
||||
Future<MembreSearchResult> searchByAdhesionPeriod({
|
||||
String? dateMin,
|
||||
String? dateMax,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
final criteria = MembreSearchCriteria(
|
||||
dateAdhesionMin: dateMin,
|
||||
dateAdhesionMax: dateMax,
|
||||
statut: 'ACTIF',
|
||||
);
|
||||
return searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
|
||||
/// Valide les critères de recherche avant envoi
|
||||
bool validateCriteria(MembreSearchCriteria criteria) {
|
||||
if (!criteria.hasAnyCriteria) {
|
||||
AppLogger.warning('MembreSearchService: aucun critère de recherche spécifié');
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!criteria.isValid) {
|
||||
AppLogger.warning('MembreSearchService: critères invalides', tag: criteria.description);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Estime le temps de recherche basé sur les critères
|
||||
Duration estimateSearchTime(MembreSearchCriteria criteria) {
|
||||
// Estimation basique - peut être améliorée avec des métriques réelles
|
||||
int complexityScore = 0;
|
||||
|
||||
if (criteria.query?.isNotEmpty == true) complexityScore += 2;
|
||||
if (criteria.organisationIds?.isNotEmpty == true) complexityScore += 1;
|
||||
if (criteria.roles?.isNotEmpty == true) complexityScore += 1;
|
||||
if (criteria.ageMin != null || criteria.ageMax != null) complexityScore += 1;
|
||||
if (criteria.dateAdhesionMin != null || criteria.dateAdhesionMax != null) complexityScore += 1;
|
||||
|
||||
// Temps de base + complexité
|
||||
const baseTime = 100; // 100ms de base
|
||||
final additionalTime = complexityScore * 50; // 50ms par critère
|
||||
|
||||
return Duration(milliseconds: baseTime + additionalTime);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/// Interface du repository des membres (Clean Architecture)
|
||||
library membre_repository_interface;
|
||||
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
|
||||
/// Interface définissant le contrat du repository des membres
|
||||
/// Implémentée par MembreRepositoryImpl dans la couche data
|
||||
abstract class IMembreRepository {
|
||||
/// Récupère la liste des membres avec pagination
|
||||
Future<MembreSearchResult> getMembres({
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
String? recherche,
|
||||
});
|
||||
|
||||
/// Récupère un membre par son ID
|
||||
Future<MembreCompletModel?> getMembreById(String id);
|
||||
|
||||
/// Crée un nouveau membre
|
||||
Future<MembreCompletModel> createMembre(MembreCompletModel membre);
|
||||
|
||||
/// Met à jour un membre
|
||||
Future<MembreCompletModel> updateMembre(String id, MembreCompletModel membre);
|
||||
|
||||
/// Supprime un membre
|
||||
Future<void> deleteMembre(String id);
|
||||
|
||||
/// Active un membre
|
||||
Future<MembreCompletModel> activateMembre(String id);
|
||||
|
||||
/// Désactive un membre
|
||||
Future<MembreCompletModel> deactivateMembre(String id);
|
||||
|
||||
/// Recherche avancée de membres
|
||||
Future<MembreSearchResult> searchMembres({
|
||||
required MembreSearchCriteria criteria,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
});
|
||||
|
||||
/// Récupère les membres actifs
|
||||
Future<MembreSearchResult> getActiveMembers({int page = 0, int size = 20});
|
||||
|
||||
/// Récupère les membres du bureau
|
||||
Future<MembreSearchResult> getBureauMembers({int page = 0, int size = 20});
|
||||
|
||||
/// Récupère les statistiques des membres
|
||||
Future<Map<String, dynamic>> getMembresStats();
|
||||
}
|
||||
25
lib/features/members/domain/usecases/create_member.dart
Normal file
25
lib/features/members/domain/usecases/create_member.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
/// Use case: Créer un nouveau membre
|
||||
library create_member;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour créer un membre
|
||||
/// Réservé aux utilisateurs avec le rôle HR_MANAGER
|
||||
@injectable
|
||||
class CreateMember {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
CreateMember(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [membre] - Modèle complet du membre à créer
|
||||
///
|
||||
/// Retourne le membre créé avec son ID généré
|
||||
/// Lève une exception en cas d'erreur de validation ou de création
|
||||
Future<MembreCompletModel> call(MembreCompletModel membre) async {
|
||||
return _repository.createMembre(membre);
|
||||
}
|
||||
}
|
||||
25
lib/features/members/domain/usecases/delete_member.dart
Normal file
25
lib/features/members/domain/usecases/delete_member.dart
Normal file
@@ -0,0 +1,25 @@
|
||||
/// Use case: Supprimer un membre
|
||||
library delete_member;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour supprimer un membre
|
||||
/// Réservé aux utilisateurs avec le rôle HR_MANAGER ou ADMIN_ORGANISATION
|
||||
@injectable
|
||||
class DeleteMember {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
DeleteMember(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [id] - UUID du membre à supprimer
|
||||
///
|
||||
/// Supprime le membre de manière définitive ou le marque comme inactif
|
||||
/// selon la configuration de l'organisation
|
||||
/// Lève une exception si le membre n'existe pas ou ne peut être supprimé
|
||||
Future<void> call(String id) async {
|
||||
return _repository.deleteMembre(id);
|
||||
}
|
||||
}
|
||||
49
lib/features/members/domain/usecases/export_members.dart
Normal file
49
lib/features/members/domain/usecases/export_members.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
/// Use case: Exporter la liste des membres
|
||||
library export_members;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour exporter la liste des membres au format CSV ou PDF
|
||||
/// Réservé aux utilisateurs avec le rôle ADMIN_ORGANISATION
|
||||
@injectable
|
||||
class ExportMembers {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
ExportMembers(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [criteria] - Critères de filtre pour l'export (optionnel)
|
||||
/// [format] - Format d'export ('csv' ou 'pdf')
|
||||
///
|
||||
/// Retourne les données exportées (liste complète des membres selon critères)
|
||||
/// TODO: Ajouter endpoint backend GET /api/membres/export?format=csv|pdf
|
||||
/// Le use case actuel récupère toutes les données, l'export final se fait côté UI
|
||||
Future<List<Map<String, dynamic>>> call({
|
||||
MembreSearchCriteria? criteria,
|
||||
String format = 'csv',
|
||||
}) async {
|
||||
// Récupérer tous les membres (pagination large)
|
||||
final result = await _repository.searchMembres(
|
||||
criteria: criteria ?? const MembreSearchCriteria(),
|
||||
page: 0,
|
||||
size: 10000, // Grande pagination pour export complet
|
||||
);
|
||||
|
||||
// Convertir en liste de maps pour l'export
|
||||
return result.membres.map((membre) => {
|
||||
'id': membre.id,
|
||||
'nom': membre.nom,
|
||||
'prenom': membre.prenom,
|
||||
'email': membre.email,
|
||||
'telephone': membre.telephone,
|
||||
'adresse': membre.adresse,
|
||||
'dateNaissance': membre.dateNaissance?.toIso8601String(),
|
||||
'dateAdhesion': membre.dateAdhesion?.toIso8601String(),
|
||||
'statut': membre.statut,
|
||||
'actif': membre.actif,
|
||||
}).toList();
|
||||
}
|
||||
}
|
||||
24
lib/features/members/domain/usecases/get_member_by_id.dart
Normal file
24
lib/features/members/domain/usecases/get_member_by_id.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
/// Use case: Récupérer un membre par son ID
|
||||
library get_member_by_id;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour récupérer le détail complet d'un membre
|
||||
@injectable
|
||||
class GetMemberById {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
GetMemberById(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [id] - UUID du membre
|
||||
///
|
||||
/// Retourne le détail complet du membre avec toutes ses informations
|
||||
/// Retourne null si le membre n'existe pas
|
||||
Future<MembreCompletModel?> call(String id) async {
|
||||
return _repository.getMembreById(id);
|
||||
}
|
||||
}
|
||||
29
lib/features/members/domain/usecases/get_member_stats.dart
Normal file
29
lib/features/members/domain/usecases/get_member_stats.dart
Normal file
@@ -0,0 +1,29 @@
|
||||
/// Use case: Récupérer les statistiques des membres
|
||||
library get_member_stats;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour récupérer les statistiques globales des membres
|
||||
/// Réservé aux utilisateurs avec le rôle ADMIN_ORGANISATION
|
||||
@injectable
|
||||
class GetMemberStats {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
GetMemberStats(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// Retourne un Map contenant les statistiques:
|
||||
/// - totalMembres: Nombre total de membres
|
||||
/// - membresActifs: Nombre de membres actifs
|
||||
/// - membresInactifs: Nombre de membres inactifs
|
||||
/// - nouveauxMembres30j: Nouveaux membres sur les 30 derniers jours
|
||||
/// - membresBureau: Nombre de membres du bureau
|
||||
/// - tauxActivite: Taux d'activité en pourcentage
|
||||
///
|
||||
/// Lève une exception en cas d'erreur d'accès
|
||||
Future<Map<String, dynamic>> call() async {
|
||||
return _repository.getMembresStats();
|
||||
}
|
||||
}
|
||||
33
lib/features/members/domain/usecases/get_members.dart
Normal file
33
lib/features/members/domain/usecases/get_members.dart
Normal file
@@ -0,0 +1,33 @@
|
||||
/// Use case: Récupérer la liste des membres
|
||||
library get_members;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour récupérer la liste des membres avec pagination
|
||||
@injectable
|
||||
class GetMembers {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
GetMembers(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [page] - Numéro de page (pagination)
|
||||
/// [size] - Taille de la page
|
||||
/// [recherche] - Terme de recherche simple (optionnel)
|
||||
///
|
||||
/// Retourne la liste paginée des membres
|
||||
Future<MembreSearchResult> call({
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
String? recherche,
|
||||
}) async {
|
||||
return _repository.getMembres(
|
||||
page: page,
|
||||
size: size,
|
||||
recherche: recherche,
|
||||
);
|
||||
}
|
||||
}
|
||||
35
lib/features/members/domain/usecases/search_members.dart
Normal file
35
lib/features/members/domain/usecases/search_members.dart
Normal file
@@ -0,0 +1,35 @@
|
||||
/// Use case: Recherche avancée de membres
|
||||
library search_members;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour effectuer une recherche avancée de membres
|
||||
/// avec critères multiples (nom, email, téléphone, statut, rôle, organisation, etc.)
|
||||
@injectable
|
||||
class SearchMembers {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
SearchMembers(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [criteria] - Critères de recherche avancée
|
||||
/// [page] - Numéro de page (pagination)
|
||||
/// [size] - Taille de la page
|
||||
///
|
||||
/// Retourne la liste paginée des membres correspondant aux critères
|
||||
Future<MembreSearchResult> call({
|
||||
required MembreSearchCriteria criteria,
|
||||
int page = 0,
|
||||
int size = 20,
|
||||
}) async {
|
||||
return _repository.searchMembres(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
size: size,
|
||||
);
|
||||
}
|
||||
}
|
||||
26
lib/features/members/domain/usecases/update_member.dart
Normal file
26
lib/features/members/domain/usecases/update_member.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
/// Use case: Mettre à jour un membre existant
|
||||
library update_member;
|
||||
|
||||
import 'package:injectable/injectable.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
import '../repositories/membre_repository.dart';
|
||||
|
||||
/// Use case pour modifier un membre
|
||||
/// Réservé aux utilisateurs avec le rôle HR_MANAGER
|
||||
@injectable
|
||||
class UpdateMember {
|
||||
final IMembreRepository _repository;
|
||||
|
||||
UpdateMember(this._repository);
|
||||
|
||||
/// Exécute le use case
|
||||
///
|
||||
/// [id] - UUID du membre à modifier
|
||||
/// [membre] - Données mises à jour
|
||||
///
|
||||
/// Retourne le membre modifié
|
||||
/// Lève une exception si le membre n'existe pas ou erreur de validation
|
||||
Future<MembreCompletModel> call(String id, MembreCompletModel membre) async {
|
||||
return _repository.updateMembre(id, membre);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,694 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../../core/di/injection_container.dart';
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
import '../../../organizations/data/repositories/organization_repository.dart';
|
||||
import '../../../organizations/data/models/organization_model.dart';
|
||||
import '../../data/services/membre_search_service.dart';
|
||||
import '../widgets/membre_search_results.dart';
|
||||
import '../widgets/search_statistics_card.dart';
|
||||
|
||||
/// Page de recherche avancée des membres
|
||||
/// Interface complète pour la recherche sophistiquée avec filtres multiples
|
||||
class AdvancedSearchPage extends StatefulWidget {
|
||||
const AdvancedSearchPage({super.key});
|
||||
|
||||
@override
|
||||
State<AdvancedSearchPage> createState() => _AdvancedSearchPageState();
|
||||
}
|
||||
|
||||
class _AdvancedSearchPageState extends State<AdvancedSearchPage>
|
||||
with TickerProviderStateMixin {
|
||||
late TabController _tabController;
|
||||
late final MembreSearchService _searchService = sl<MembreSearchService>();
|
||||
MembreSearchCriteria _currentCriteria = MembreSearchCriteria.empty;
|
||||
List<OrganizationModel> _organisations = [];
|
||||
bool _organisationsLoaded = false;
|
||||
MembreSearchResult? _currentResult;
|
||||
bool _isSearching = false;
|
||||
String? _errorMessage;
|
||||
|
||||
// Contrôleurs pour les champs de recherche
|
||||
final _queryController = TextEditingController();
|
||||
final _nomController = TextEditingController();
|
||||
final _prenomController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _telephoneController = TextEditingController();
|
||||
final _regionController = TextEditingController();
|
||||
final _villeController = TextEditingController();
|
||||
final _professionController = TextEditingController();
|
||||
|
||||
// Valeurs pour les filtres
|
||||
String? _selectedStatut;
|
||||
final List<String> _selectedRoles = [];
|
||||
final List<String> _selectedOrganisations = [];
|
||||
RangeValues _ageRange = const RangeValues(18, 65);
|
||||
DateTimeRange? _adhesionDateRange;
|
||||
bool _includeInactifs = false;
|
||||
bool _membreBureau = false;
|
||||
bool _responsable = false;
|
||||
|
||||
/// Rôles Keycloak utilisables pour le filtre (noms envoyés à l'API)
|
||||
static const List<String> _searchRoleCodes = [
|
||||
'MEMBRE_ACTIF',
|
||||
'MEMBRE_SIMPLE',
|
||||
'ADMIN_ORGANISATION',
|
||||
'SECRETAIRE',
|
||||
'TRESORIER',
|
||||
'CONSULTANT',
|
||||
'GESTIONNAIRE_RH',
|
||||
'SUPER_ADMINISTRATEUR',
|
||||
];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tabController = TabController(length: 3, vsync: this);
|
||||
_loadOrganisations();
|
||||
}
|
||||
|
||||
static String _roleDisplayName(String code) {
|
||||
const labels = {
|
||||
'MEMBRE_ACTIF': 'Membre actif',
|
||||
'MEMBRE_SIMPLE': 'Membre',
|
||||
'ADMIN_ORGANISATION': 'Admin organisation',
|
||||
'SECRETAIRE': 'Secrétaire',
|
||||
'TRESORIER': 'Trésorier',
|
||||
'CONSULTANT': 'Consultant',
|
||||
'GESTIONNAIRE_RH': 'Gestionnaire RH',
|
||||
'SUPER_ADMINISTRATEUR': 'Super admin',
|
||||
};
|
||||
return labels[code] ?? code;
|
||||
}
|
||||
|
||||
Future<void> _loadOrganisations() async {
|
||||
if (_organisationsLoaded) return;
|
||||
try {
|
||||
final repo = sl<OrganizationRepository>();
|
||||
final list = await repo.getOrganizations(page: 0, size: 200);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_organisations = list;
|
||||
_organisationsLoaded = true;
|
||||
});
|
||||
}
|
||||
} catch (_) {
|
||||
if (mounted) setState(() => _organisationsLoaded = true);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tabController.dispose();
|
||||
_queryController.dispose();
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_telephoneController.dispose();
|
||||
_regionController.dispose();
|
||||
_villeController.dispose();
|
||||
_professionController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(
|
||||
title: const Text('Recherche Avancée'),
|
||||
backgroundColor: Theme.of(context).primaryColor,
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
bottom: TabBar(
|
||||
controller: _tabController,
|
||||
indicatorColor: Colors.white,
|
||||
labelColor: Colors.white,
|
||||
unselectedLabelColor: Colors.white70,
|
||||
tabs: const [
|
||||
Tab(icon: Icon(Icons.search), text: 'Critères'),
|
||||
Tab(icon: Icon(Icons.list), text: 'Résultats'),
|
||||
Tab(icon: Icon(Icons.analytics), text: 'Statistiques'),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: TabBarView(
|
||||
controller: _tabController,
|
||||
children: [
|
||||
_buildSearchCriteriaTab(),
|
||||
_buildSearchResultsTab(),
|
||||
_buildStatisticsTab(),
|
||||
],
|
||||
),
|
||||
floatingActionButton: _buildSearchFab(),
|
||||
);
|
||||
}
|
||||
|
||||
/// Onglet des critères de recherche
|
||||
Widget _buildSearchCriteriaTab() {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Recherche rapide
|
||||
_buildQuickSearchSection(),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Critères détaillés
|
||||
_buildDetailedCriteriaSection(),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Filtres avancés
|
||||
_buildAdvancedFiltersSection(),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Boutons d'action
|
||||
_buildActionButtons(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Section de recherche rapide
|
||||
Widget _buildQuickSearchSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.flash_on, color: Theme.of(context).primaryColor),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Recherche Rapide',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _queryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Rechercher un membre',
|
||||
hintText: 'Nom, prénom ou email...',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: (_) => _performQuickSearch(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
children: [
|
||||
_buildQuickFilterChip('Membres actifs', () {
|
||||
_selectedStatut = 'ACTIF';
|
||||
_includeInactifs = false;
|
||||
}),
|
||||
_buildQuickFilterChip('Membres bureau', () {
|
||||
_membreBureau = true;
|
||||
_selectedStatut = 'ACTIF';
|
||||
}),
|
||||
_buildQuickFilterChip('Responsables', () {
|
||||
_responsable = true;
|
||||
_selectedStatut = 'ACTIF';
|
||||
}),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Section des critères détaillés
|
||||
Widget _buildDetailedCriteriaSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.tune, color: Theme.of(context).primaryColor),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Critères Détaillés',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _nomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _prenomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
hintText: 'email@domaine.org',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _telephoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Téléphone',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<String>(
|
||||
value: _selectedStatut,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Statut',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(value: null, child: Text('Tous')),
|
||||
DropdownMenuItem(value: 'ACTIF', child: Text('Actif')),
|
||||
DropdownMenuItem(value: 'INACTIF', child: Text('Inactif')),
|
||||
DropdownMenuItem(value: 'SUSPENDU', child: Text('Suspendu')),
|
||||
DropdownMenuItem(value: 'RADIE', child: Text('Radié')),
|
||||
],
|
||||
onChanged: (value) => setState(() => _selectedStatut = value),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Section des filtres avancés
|
||||
Widget _buildAdvancedFiltersSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(Icons.filter_alt, color: Theme.of(context).primaryColor),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Filtres Avancés',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Tranche d'âge
|
||||
Text('Tranche d\'âge: ${_ageRange.start.round()}-${_ageRange.end.round()} ans'),
|
||||
RangeSlider(
|
||||
values: _ageRange,
|
||||
min: 18,
|
||||
max: 80,
|
||||
divisions: 62,
|
||||
labels: RangeLabels(
|
||||
'${_ageRange.start.round()}',
|
||||
'${_ageRange.end.round()}',
|
||||
),
|
||||
onChanged: (values) => setState(() => _ageRange = values),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Organisations (multi-select)
|
||||
Text(
|
||||
'Organisations',
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
_organisations.isEmpty && !_organisationsLoaded
|
||||
? const SizedBox(
|
||||
height: 24,
|
||||
child: Center(child: CircularProgressIndicator(strokeWidth: 2)),
|
||||
)
|
||||
: Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: _organisations
|
||||
.where((o) => o.id != null && o.id!.isNotEmpty)
|
||||
.map((org) {
|
||||
final id = org.id!;
|
||||
final selected = _selectedOrganisations.contains(id);
|
||||
return FilterChip(
|
||||
label: Text(org.nomCourt ?? org.nom, overflow: TextOverflow.ellipsis, maxLines: 1),
|
||||
selected: selected,
|
||||
onSelected: (v) {
|
||||
setState(() {
|
||||
if (v) {
|
||||
_selectedOrganisations.add(id);
|
||||
} else {
|
||||
_selectedOrganisations.remove(id);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Rôles (multi-select)
|
||||
Text(
|
||||
'Rôles',
|
||||
style: Theme.of(context).textTheme.titleSmall?.copyWith(
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: _searchRoleCodes.map((code) {
|
||||
final selected = _selectedRoles.contains(code);
|
||||
return FilterChip(
|
||||
label: Text(_roleDisplayName(code)),
|
||||
selected: selected,
|
||||
onSelected: (v) {
|
||||
setState(() {
|
||||
if (v) {
|
||||
_selectedRoles.add(code);
|
||||
} else {
|
||||
_selectedRoles.remove(code);
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
}).toList(),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Options booléennes
|
||||
CheckboxListTile(
|
||||
title: const Text('Inclure les membres inactifs'),
|
||||
value: _includeInactifs,
|
||||
onChanged: (value) => setState(() => _includeInactifs = value ?? false),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Membres du bureau uniquement'),
|
||||
value: _membreBureau,
|
||||
onChanged: (value) => setState(() => _membreBureau = value ?? false),
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Responsables uniquement'),
|
||||
value: _responsable,
|
||||
onChanged: (value) => setState(() => _responsable = value ?? false),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Boutons d'action
|
||||
Widget _buildActionButtons() {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _clearCriteria,
|
||||
icon: const Icon(Icons.clear),
|
||||
label: const Text('Effacer'),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 16),
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _isSearching ? null : _performAdvancedSearch,
|
||||
icon: _isSearching
|
||||
? const SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: const Icon(Icons.search),
|
||||
label: Text(_isSearching ? 'Recherche...' : 'Rechercher'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Onglet des résultats
|
||||
Widget _buildSearchResultsTab() {
|
||||
if (_currentResult == null) {
|
||||
return const Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.search, size: 64, color: Colors.grey),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Aucune recherche effectuée',
|
||||
style: TextStyle(fontSize: 18, color: Colors.grey),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Utilisez l\'onglet Critères pour lancer une recherche',
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
if (_errorMessage != null) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.error, size: 64, color: Colors.red),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Erreur de recherche',
|
||||
style: Theme.of(context).textTheme.titleLarge,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_errorMessage!,
|
||||
textAlign: TextAlign.center,
|
||||
style: const TextStyle(color: Colors.red),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: () => setState(() => _errorMessage = null),
|
||||
child: const Text('Réessayer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return MembreSearchResults(
|
||||
result: _currentResult!,
|
||||
onPageChanged: (page) => _performSearch(_currentCriteria, page: page),
|
||||
);
|
||||
}
|
||||
|
||||
/// Onglet des statistiques
|
||||
Widget _buildStatisticsTab() {
|
||||
if (_currentResult?.statistics == null) {
|
||||
return const Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.analytics, size: 64, color: Colors.grey),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Aucune statistique disponible',
|
||||
style: TextStyle(fontSize: 18, color: Colors.grey),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Effectuez une recherche pour voir les statistiques',
|
||||
style: TextStyle(color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return SearchStatisticsCard(statistics: _currentResult!.statistics!);
|
||||
}
|
||||
|
||||
/// FAB de recherche
|
||||
Widget _buildSearchFab() {
|
||||
return FloatingActionButton.extended(
|
||||
onPressed: _isSearching ? null : _performAdvancedSearch,
|
||||
icon: _isSearching
|
||||
? const SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
|
||||
)
|
||||
: const Icon(Icons.search),
|
||||
label: Text(_isSearching ? 'Recherche...' : 'Rechercher'),
|
||||
);
|
||||
}
|
||||
|
||||
/// Chip de filtre rapide
|
||||
Widget _buildQuickFilterChip(String label, VoidCallback onTap) {
|
||||
return ActionChip(
|
||||
label: Text(label),
|
||||
onPressed: onTap,
|
||||
backgroundColor: Theme.of(context).primaryColor.withOpacity(0.1),
|
||||
labelStyle: TextStyle(color: Theme.of(context).primaryColor),
|
||||
);
|
||||
}
|
||||
|
||||
/// Effectue une recherche rapide
|
||||
void _performQuickSearch() {
|
||||
if (_queryController.text.trim().isEmpty) return;
|
||||
|
||||
final criteria = MembreSearchCriteria.quickSearch(_queryController.text.trim());
|
||||
_performSearch(criteria);
|
||||
}
|
||||
|
||||
/// Effectue une recherche avancée
|
||||
void _performAdvancedSearch() {
|
||||
final criteria = _buildSearchCriteria();
|
||||
_performSearch(criteria);
|
||||
}
|
||||
|
||||
/// Construit les critères de recherche à partir des champs
|
||||
MembreSearchCriteria _buildSearchCriteria() {
|
||||
return MembreSearchCriteria(
|
||||
query: _queryController.text.trim().isEmpty ? null : _queryController.text.trim(),
|
||||
nom: _nomController.text.trim().isEmpty ? null : _nomController.text.trim(),
|
||||
prenom: _prenomController.text.trim().isEmpty ? null : _prenomController.text.trim(),
|
||||
email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
|
||||
telephone: _telephoneController.text.trim().isEmpty ? null : _telephoneController.text.trim(),
|
||||
statut: _selectedStatut,
|
||||
ageMin: _ageRange.start.round(),
|
||||
ageMax: _ageRange.end.round(),
|
||||
region: _regionController.text.trim().isEmpty ? null : _regionController.text.trim(),
|
||||
ville: _villeController.text.trim().isEmpty ? null : _villeController.text.trim(),
|
||||
profession: _professionController.text.trim().isEmpty ? null : _professionController.text.trim(),
|
||||
organisationIds: _selectedOrganisations.isEmpty ? null : _selectedOrganisations,
|
||||
roles: _selectedRoles.isEmpty ? null : _selectedRoles,
|
||||
membreBureau: _membreBureau ? true : null,
|
||||
responsable: _responsable ? true : null,
|
||||
includeInactifs: _includeInactifs,
|
||||
);
|
||||
}
|
||||
|
||||
/// Effectue la recherche
|
||||
void _performSearch(MembreSearchCriteria criteria, {int page = 0}) async {
|
||||
if (!criteria.hasAnyCriteria) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Veuillez spécifier au moins un critère de recherche'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isSearching = true;
|
||||
_errorMessage = null;
|
||||
_currentCriteria = criteria;
|
||||
});
|
||||
|
||||
try {
|
||||
final result = await _searchService.searchMembresAdvanced(
|
||||
criteria: criteria,
|
||||
page: page,
|
||||
);
|
||||
|
||||
setState(() {
|
||||
_currentResult = result;
|
||||
_isSearching = false;
|
||||
});
|
||||
|
||||
// Basculer vers l'onglet des résultats
|
||||
_tabController.animateTo(1);
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(result.resultDescription),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = e.toString();
|
||||
_isSearching = false;
|
||||
});
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur de recherche: $e'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Efface tous les critères
|
||||
void _clearCriteria() {
|
||||
setState(() {
|
||||
_queryController.clear();
|
||||
_nomController.clear();
|
||||
_prenomController.clear();
|
||||
_emailController.clear();
|
||||
_telephoneController.clear();
|
||||
_regionController.clear();
|
||||
_villeController.clear();
|
||||
_professionController.clear();
|
||||
_selectedStatut = null;
|
||||
_selectedRoles.clear();
|
||||
_selectedOrganisations.clear();
|
||||
_ageRange = const RangeValues(18, 65);
|
||||
_adhesionDateRange = null;
|
||||
_includeInactifs = false;
|
||||
_membreBureau = false;
|
||||
_responsable = false;
|
||||
_currentResult = null;
|
||||
_errorMessage = null;
|
||||
});
|
||||
}
|
||||
}
|
||||
1985
lib/features/members/presentation/pages/members_page.dart
Normal file
1985
lib/features/members/presentation/pages/members_page.dart
Normal file
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,445 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../../../shared/design_system/unionflow_design_v2.dart';
|
||||
import '../../../../shared/design_system/components/uf_app_bar.dart';
|
||||
import '../../../../core/constants/app_constants.dart';
|
||||
import '../widgets/add_member_dialog.dart';
|
||||
|
||||
/// Annuaire des Membres - Design UnionFlow
|
||||
class MembersPageWithDataAndPagination extends StatefulWidget {
|
||||
final List<Map<String, dynamic>> members;
|
||||
final int totalCount;
|
||||
final int currentPage;
|
||||
final int totalPages;
|
||||
final Function(int page, String? recherche) onPageChanged;
|
||||
final VoidCallback onRefresh;
|
||||
final void Function(String? query)? onSearch;
|
||||
final VoidCallback? onAddMember;
|
||||
|
||||
const MembersPageWithDataAndPagination({
|
||||
super.key,
|
||||
required this.members,
|
||||
required this.totalCount,
|
||||
required this.currentPage,
|
||||
required this.totalPages,
|
||||
required this.onPageChanged,
|
||||
required this.onRefresh,
|
||||
this.onSearch,
|
||||
this.onAddMember,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MembersPageWithDataAndPagination> createState() => _MembersPageWithDataAndPaginationState();
|
||||
}
|
||||
|
||||
class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAndPagination> {
|
||||
final TextEditingController _searchController = TextEditingController();
|
||||
String _searchQuery = '';
|
||||
String _filterStatus = 'Tous';
|
||||
Timer? _searchDebounce;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_searchDebounce?.cancel();
|
||||
_searchController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: UnionFlowColors.background,
|
||||
appBar: UFAppBar(
|
||||
title: 'Annuaire Membres',
|
||||
backgroundColor: UnionFlowColors.surface,
|
||||
foregroundColor: UnionFlowColors.textPrimary,
|
||||
actions: [
|
||||
if (widget.onAddMember != null)
|
||||
IconButton(
|
||||
icon: const Icon(Icons.person_add_outlined),
|
||||
color: UnionFlowColors.unionGreen,
|
||||
onPressed: widget.onAddMember,
|
||||
tooltip: 'Ajouter un membre',
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
body: Column(
|
||||
children: [
|
||||
_buildHeader(),
|
||||
_buildSearchAndFilters(),
|
||||
Expanded(child: _buildMembersList()),
|
||||
if (widget.totalPages > 1) _buildPagination(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader() {
|
||||
final activeCount = widget.members.where((m) => m['status'] == 'Actif').length;
|
||||
final pendingCount = widget.members.where((m) => m['status'] == 'En attente').length;
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: UnionFlowColors.surface,
|
||||
border: Border(
|
||||
bottom: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(child: _buildStatBadge('Total', widget.totalCount.toString(), UnionFlowColors.unionGreen)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildStatBadge('Actifs', activeCount.toString(), UnionFlowColors.success)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: _buildStatBadge('Attente', pendingCount.toString(), UnionFlowColors.warning)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatBadge(String label, String value, Color color) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12, horizontal: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color.withOpacity(0.3), width: 1),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: color)),
|
||||
const SizedBox(height: 2),
|
||||
Text(label, style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: color)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSearchAndFilters() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: UnionFlowColors.surface,
|
||||
border: Border(bottom: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(
|
||||
controller: _searchController,
|
||||
onChanged: (v) {
|
||||
setState(() => _searchQuery = v);
|
||||
_searchDebounce?.cancel();
|
||||
_searchDebounce = Timer(AppConstants.searchDebounce, () {
|
||||
widget.onSearch?.call(v.isEmpty ? null : v);
|
||||
});
|
||||
},
|
||||
style: const TextStyle(fontSize: 14, color: UnionFlowColors.textPrimary),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Rechercher un membre...',
|
||||
hintStyle: const TextStyle(fontSize: 13, color: UnionFlowColors.textTertiary),
|
||||
prefixIcon: const Icon(Icons.search, size: 20, color: UnionFlowColors.textSecondary),
|
||||
suffixIcon: _searchQuery.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear, size: 18, color: UnionFlowColors.textSecondary),
|
||||
onPressed: () {
|
||||
_searchDebounce?.cancel();
|
||||
_searchController.clear();
|
||||
setState(() => _searchQuery = '');
|
||||
widget.onSearch?.call(null);
|
||||
},
|
||||
)
|
||||
: null,
|
||||
contentPadding: const EdgeInsets.symmetric(vertical: 12, horizontal: 16),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: UnionFlowColors.border.withOpacity(0.3)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: UnionFlowColors.border.withOpacity(0.3)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: UnionFlowColors.unionGreen, width: 1.5),
|
||||
),
|
||||
filled: true,
|
||||
fillColor: UnionFlowColors.surfaceVariant.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
child: Row(
|
||||
children: [
|
||||
_buildFilterChip('Tous'),
|
||||
const SizedBox(width: 8),
|
||||
_buildFilterChip('Actif'),
|
||||
const SizedBox(width: 8),
|
||||
_buildFilterChip('Inactif'),
|
||||
const SizedBox(width: 8),
|
||||
_buildFilterChip('En attente'),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildFilterChip(String label) {
|
||||
final isSelected = _filterStatus == label;
|
||||
return GestureDetector(
|
||||
onTap: () => setState(() => _filterStatus = label),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: isSelected ? UnionFlowColors.unionGreen : UnionFlowColors.surface,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: isSelected ? UnionFlowColors.unionGreen : UnionFlowColors.border, width: 1),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: isSelected ? Colors.white : UnionFlowColors.textSecondary,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMembersList() {
|
||||
final filtered = widget.members.where((m) {
|
||||
final matchesSearch = _searchQuery.isEmpty ||
|
||||
m['name']!.toLowerCase().contains(_searchQuery.toLowerCase()) ||
|
||||
(m['email']?.toLowerCase().contains(_searchQuery.toLowerCase()) ?? false);
|
||||
final matchesStatus = _filterStatus == 'Tous' || m['status'] == _filterStatus;
|
||||
return matchesSearch && matchesStatus;
|
||||
}).toList();
|
||||
|
||||
if (filtered.isEmpty) return _buildEmptyState();
|
||||
|
||||
return RefreshIndicator(
|
||||
onRefresh: () async => widget.onRefresh(),
|
||||
color: UnionFlowColors.unionGreen,
|
||||
child: ListView.separated(
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: filtered.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 12),
|
||||
itemBuilder: (context, index) => _buildMemberCard(filtered[index]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMemberCard(Map<String, dynamic> member) {
|
||||
return GestureDetector(
|
||||
onTap: () => _showMemberDetails(member),
|
||||
child: Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: UnionFlowColors.surface,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: UnionFlowColors.softShadow,
|
||||
border: Border.all(color: UnionFlowColors.border.withOpacity(0.3), width: 1),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: const BoxDecoration(gradient: UnionFlowColors.primaryGradient, shape: BoxShape.circle),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
member['initiales'] ?? '??',
|
||||
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700, fontSize: 18),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
member['name'] ?? 'Inconnu',
|
||||
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: UnionFlowColors.textPrimary),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(
|
||||
member['role'] ?? 'Membre',
|
||||
style: const TextStyle(fontSize: 12, color: UnionFlowColors.textSecondary),
|
||||
),
|
||||
if (member['email'] != null) ...[
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.email_outlined, size: 12, color: UnionFlowColors.textTertiary),
|
||||
const SizedBox(width: 4),
|
||||
Text(member['email']!, style: const TextStyle(fontSize: 11, color: UnionFlowColors.textTertiary)),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
_buildStatusBadge(member['status']),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusBadge(String? status) {
|
||||
Color color;
|
||||
switch (status) {
|
||||
case 'Actif':
|
||||
color = UnionFlowColors.success;
|
||||
break;
|
||||
case 'Inactif':
|
||||
color = UnionFlowColors.error;
|
||||
break;
|
||||
case 'En attente':
|
||||
color = UnionFlowColors.warning;
|
||||
break;
|
||||
default:
|
||||
color = UnionFlowColors.textSecondary;
|
||||
}
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color.withOpacity(0.3), width: 1),
|
||||
),
|
||||
child: Text(status ?? '?', style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: color)),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildEmptyState() {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: const BoxDecoration(color: UnionFlowColors.unionGreenPale, shape: BoxShape.circle),
|
||||
child: const Icon(Icons.people_outline, size: 64, color: UnionFlowColors.unionGreen),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
const Text(
|
||||
'Aucun membre trouvé',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_searchQuery.isEmpty ? 'Changez vos filtres' : 'Essayez une autre recherche',
|
||||
style: const TextStyle(fontSize: 13, color: UnionFlowColors.textSecondary),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPagination() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color: UnionFlowColors.surface,
|
||||
border: Border(top: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_left, size: 24),
|
||||
color: widget.currentPage > 0 ? UnionFlowColors.unionGreen : UnionFlowColors.textTertiary,
|
||||
onPressed: widget.currentPage > 0
|
||||
? () => widget.onPageChanged(
|
||||
widget.currentPage - 1,
|
||||
_searchQuery.isEmpty ? null : _searchQuery,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(gradient: UnionFlowColors.primaryGradient, borderRadius: BorderRadius.circular(20)),
|
||||
child: Text(
|
||||
'Page ${widget.currentPage + 1} / ${widget.totalPages}',
|
||||
style: const TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Colors.white),
|
||||
),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.chevron_right, size: 24),
|
||||
color: widget.currentPage < widget.totalPages - 1 ? UnionFlowColors.unionGreen : UnionFlowColors.textTertiary,
|
||||
onPressed: widget.currentPage < widget.totalPages - 1
|
||||
? () => widget.onPageChanged(
|
||||
widget.currentPage + 1,
|
||||
_searchQuery.isEmpty ? null : _searchQuery,
|
||||
)
|
||||
: null,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
void _showMemberDetails(Map<String, dynamic> member) {
|
||||
showModalBottomSheet(
|
||||
context: context,
|
||||
backgroundColor: Colors.transparent,
|
||||
builder: (context) => Container(
|
||||
padding: const EdgeInsets.all(24),
|
||||
decoration: const BoxDecoration(
|
||||
color: UnionFlowColors.surface,
|
||||
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 80,
|
||||
height: 80,
|
||||
decoration: const BoxDecoration(gradient: UnionFlowColors.primaryGradient, shape: BoxShape.circle),
|
||||
alignment: Alignment.center,
|
||||
child: Text(
|
||||
member['initiales'] ?? '??',
|
||||
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 32),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
member['name'] ?? '',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
member['role'] ?? '',
|
||||
style: const TextStyle(fontSize: 13, color: UnionFlowColors.textSecondary),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
_buildInfoRow(Icons.email_outlined, member['email'] ?? 'Non fourni'),
|
||||
_buildInfoRow(Icons.phone_outlined, member['phone'] ?? 'Non fourni'),
|
||||
_buildInfoRow(Icons.location_on_outlined, member['location'] ?? 'Non renseigné'),
|
||||
_buildInfoRow(Icons.work_outline, member['department'] ?? 'Aucun département'),
|
||||
const SizedBox(height: 24),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildInfoRow(IconData icon, String text) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(icon, size: 18, color: UnionFlowColors.unionGreen),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(child: Text(text, style: const TextStyle(fontSize: 13, color: UnionFlowColors.textPrimary))),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
/// Wrapper BLoC pour la page des membres
|
||||
///
|
||||
/// Ce fichier enveloppe la MembersPage existante avec le MembresBloc
|
||||
/// pour connecter l'UI riche existante à l'API backend réelle.
|
||||
library members_page_wrapper;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:get_it/get_it.dart';
|
||||
|
||||
import '../../../../shared/widgets/error_widget.dart';
|
||||
import '../../../../shared/widgets/loading_widget.dart';
|
||||
import '../../../../core/utils/logger.dart';
|
||||
import '../../bloc/membres_bloc.dart';
|
||||
import '../../bloc/membres_event.dart';
|
||||
import '../../bloc/membres_state.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
import '../widgets/add_member_dialog.dart';
|
||||
import 'members_page_connected.dart';
|
||||
|
||||
final _getIt = GetIt.instance;
|
||||
|
||||
/// Wrapper qui fournit le BLoC à la page des membres
|
||||
class MembersPageWrapper extends StatelessWidget {
|
||||
const MembersPageWrapper({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
AppLogger.info('MembersPageWrapper: Création du BlocProvider');
|
||||
|
||||
return BlocProvider<MembresBloc>(
|
||||
create: (context) {
|
||||
AppLogger.info('MembresPageWrapper: Initialisation du MembresBloc');
|
||||
final bloc = _getIt<MembresBloc>();
|
||||
// Charger les membres au démarrage
|
||||
bloc.add(const LoadMembres());
|
||||
return bloc;
|
||||
},
|
||||
child: const MembersPageConnected(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Page des membres connectée au BLoC
|
||||
///
|
||||
/// Cette page gère les états du BLoC et affiche l'UI appropriée
|
||||
class MembersPageConnected extends StatelessWidget {
|
||||
const MembersPageConnected({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<MembresBloc, MembresState>(
|
||||
listener: (context, state) {
|
||||
// Après création : recharger la liste
|
||||
if (state is MembreCreated) {
|
||||
context.read<MembresBloc>().add(const LoadMembres(refresh: true));
|
||||
}
|
||||
|
||||
// Gestion des erreurs avec SnackBar
|
||||
if (state is MembresError) {
|
||||
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<MembresBloc>().add(const LoadMembres());
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: BlocBuilder<MembresBloc, MembresState>(
|
||||
builder: (context, state) {
|
||||
AppLogger.blocState('MembresBloc', state.runtimeType.toString());
|
||||
|
||||
// État initial
|
||||
if (state is MembresInitial) {
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: const Center(
|
||||
child: AppLoadingWidget(message: 'Initialisation...'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// État de chargement
|
||||
if (state is MembresLoading) {
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: const Center(
|
||||
child: AppLoadingWidget(message: 'Chargement des membres...'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// État de rafraîchissement (afficher l'UI avec un indicateur)
|
||||
if (state is MembresRefreshing) {
|
||||
// Affiche un indicateur pendant le rafraîchissement
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: const Center(
|
||||
child: AppLoadingWidget(message: 'Actualisation...'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Après création : on recharge la liste (listener a dispatché LoadMembres)
|
||||
if (state is MembreCreated) {
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: const Center(
|
||||
child: AppLoadingWidget(message: 'Actualisation...'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// État chargé avec succès
|
||||
if (state is MembresLoaded) {
|
||||
final membres = state.membres;
|
||||
AppLogger.info('MembresPageConnected: ${membres.length} membres chargés');
|
||||
|
||||
// Convertir les membres en format Map pour l'UI existante
|
||||
final membersData = _convertMembersToMapList(membres);
|
||||
|
||||
return MembersPageWithDataAndPagination(
|
||||
members: membersData,
|
||||
totalCount: state.totalElements,
|
||||
currentPage: state.currentPage,
|
||||
totalPages: state.totalPages,
|
||||
onPageChanged: (newPage, recherche) {
|
||||
AppLogger.userAction('Load page', data: {'page': newPage});
|
||||
context.read<MembresBloc>().add(LoadMembres(page: newPage, recherche: recherche));
|
||||
},
|
||||
onRefresh: () {
|
||||
AppLogger.userAction('Refresh membres');
|
||||
context.read<MembresBloc>().add(const LoadMembres(refresh: true));
|
||||
},
|
||||
onSearch: (query) {
|
||||
context.read<MembresBloc>().add(LoadMembres(page: 0, recherche: query));
|
||||
},
|
||||
onAddMember: () async {
|
||||
await showDialog<void>(
|
||||
context: context,
|
||||
builder: (_) => const AddMemberDialog(),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// État d'erreur réseau
|
||||
if (state is MembresNetworkError) {
|
||||
AppLogger.error('MembersPageConnected: Erreur réseau', error: state.message);
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: NetworkErrorWidget(
|
||||
onRetry: () {
|
||||
AppLogger.userAction('Retry load membres after network error');
|
||||
context.read<MembresBloc>().add(const LoadMembres());
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// État d'erreur générale
|
||||
if (state is MembresError) {
|
||||
AppLogger.error('MembersPageConnected: Erreur', error: state.message);
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: AppErrorWidget(
|
||||
message: state.message,
|
||||
onRetry: () {
|
||||
AppLogger.userAction('Retry load membres after error');
|
||||
context.read<MembresBloc>().add(const LoadMembres());
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// État par défaut (ne devrait jamais arriver)
|
||||
AppLogger.warning('MembersPageConnected: État non géré: ${state.runtimeType}');
|
||||
return Container(
|
||||
color: const Color(0xFFF8F9FA),
|
||||
child: const Center(
|
||||
child: AppLoadingWidget(message: 'Chargement...'),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Convertit une liste de MembreCompletModel en List<Map<String, dynamic>>
|
||||
/// pour compatibilité avec l'UI existante
|
||||
List<Map<String, dynamic>> _convertMembersToMapList(List<MembreCompletModel> membres) {
|
||||
return membres.map((membre) => _convertMembreToMap(membre)).toList();
|
||||
}
|
||||
|
||||
/// Convertit un MembreCompletModel en Map<String, dynamic>
|
||||
Map<String, dynamic> _convertMembreToMap(MembreCompletModel membre) {
|
||||
return {
|
||||
'id': membre.id ?? '',
|
||||
'name': membre.nomComplet,
|
||||
'email': membre.email,
|
||||
'role': _mapRoleToString(membre.role),
|
||||
'status': _mapStatutToString(membre.statut),
|
||||
'joinDate': membre.dateAdhesion,
|
||||
'lastActivity': membre.derniereActivite ?? DateTime.now(),
|
||||
'avatar': membre.photo,
|
||||
'phone': membre.telephone ?? '',
|
||||
'department': membre.profession ?? '',
|
||||
'location': '${membre.ville ?? ''}, ${membre.pays ?? ''}',
|
||||
'permissions': 15, // Valeurs par défaut tant que l'API ne fournit pas permissions
|
||||
'contributionScore': 0, // Valeurs par défaut tant que l'API ne fournit pas contributionScore
|
||||
'eventsAttended': membre.nombreEvenementsParticipes,
|
||||
'projectsInvolved': 0, // Valeurs par défaut tant que l'API ne fournit pas projectsInvolved
|
||||
|
||||
// Champs supplémentaires du modèle
|
||||
'prenom': membre.prenom,
|
||||
'nom': membre.nom,
|
||||
'dateNaissance': membre.dateNaissance,
|
||||
'genre': membre.genre?.name,
|
||||
'adresse': membre.adresse,
|
||||
'ville': membre.ville,
|
||||
'codePostal': membre.codePostal,
|
||||
'region': membre.region,
|
||||
'pays': membre.pays,
|
||||
'profession': membre.profession,
|
||||
'nationalite': membre.nationalite,
|
||||
'organisationId': membre.organisationId,
|
||||
'membreBureau': membre.membreBureau,
|
||||
'responsable': membre.responsable,
|
||||
'fonctionBureau': membre.fonctionBureau,
|
||||
'numeroMembre': membre.numeroMembre,
|
||||
'cotisationAJour': membre.cotisationAJour,
|
||||
|
||||
// Propriétés calculées
|
||||
'initiales': membre.initiales,
|
||||
'age': membre.age,
|
||||
'estActifEtAJour': membre.estActifEtAJour,
|
||||
};
|
||||
}
|
||||
|
||||
/// Mappe le rôle du modèle vers une chaîne lisible
|
||||
String _mapRoleToString(String? role) {
|
||||
if (role == null) return 'Membre Simple';
|
||||
|
||||
switch (role.toLowerCase()) {
|
||||
case 'superadmin':
|
||||
return 'Super Administrateur';
|
||||
case 'orgadmin':
|
||||
return 'Administrateur Org';
|
||||
case 'moderator':
|
||||
return 'Modérateur';
|
||||
case 'activemember':
|
||||
return 'Membre Actif';
|
||||
case 'simplemember':
|
||||
return 'Membre Simple';
|
||||
case 'visitor':
|
||||
return 'Visiteur';
|
||||
default:
|
||||
return role;
|
||||
}
|
||||
}
|
||||
|
||||
/// Mappe le statut du modèle vers une chaîne lisible
|
||||
String _mapStatutToString(StatutMembre? statut) {
|
||||
if (statut == null) return 'Actif';
|
||||
|
||||
switch (statut) {
|
||||
case StatutMembre.actif:
|
||||
return 'Actif';
|
||||
case StatutMembre.inactif:
|
||||
return 'Inactif';
|
||||
case StatutMembre.suspendu:
|
||||
return 'Suspendu';
|
||||
case StatutMembre.enAttente:
|
||||
return 'En attente';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
403
lib/features/members/presentation/widgets/add_member_dialog.dart
Normal file
403
lib/features/members/presentation/widgets/add_member_dialog.dart
Normal file
@@ -0,0 +1,403 @@
|
||||
/// Dialogue d'ajout de membre
|
||||
/// Formulaire complet pour créer un nouveau membre
|
||||
library add_member_dialog;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../bloc/membres_bloc.dart';
|
||||
import '../../bloc/membres_event.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
|
||||
/// Dialogue d'ajout de membre
|
||||
class AddMemberDialog extends StatefulWidget {
|
||||
const AddMemberDialog({super.key});
|
||||
|
||||
@override
|
||||
State<AddMemberDialog> createState() => _AddMemberDialogState();
|
||||
}
|
||||
|
||||
class _AddMemberDialogState extends State<AddMemberDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
// Contrôleurs de texte
|
||||
final _nomController = TextEditingController();
|
||||
final _prenomController = TextEditingController();
|
||||
final _emailController = TextEditingController();
|
||||
final _telephoneController = TextEditingController();
|
||||
final _adresseController = TextEditingController();
|
||||
final _villeController = TextEditingController();
|
||||
final _codePostalController = TextEditingController();
|
||||
final _regionController = TextEditingController();
|
||||
final _paysController = TextEditingController();
|
||||
final _professionController = TextEditingController();
|
||||
final _nationaliteController = TextEditingController();
|
||||
|
||||
// Valeurs sélectionnées
|
||||
Genre? _selectedGenre;
|
||||
DateTime? _dateNaissance;
|
||||
final StatutMembre _selectedStatut = StatutMembre.actif;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_telephoneController.dispose();
|
||||
_adresseController.dispose();
|
||||
_villeController.dispose();
|
||||
_codePostalController.dispose();
|
||||
_regionController.dispose();
|
||||
_paysController.dispose();
|
||||
_professionController.dispose();
|
||||
_nationaliteController.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(0xFF6C5CE7),
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: Radius.circular(4),
|
||||
topRight: Radius.circular(4),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.person_add, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
const Text(
|
||||
'Ajouter un membre',
|
||||
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 personnelles
|
||||
_buildSectionTitle('Informations personnelles'),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _nomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Le nom est obligatoire';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _prenomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person_outline),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Le prénom est obligatoire';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.email),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'L\'email est obligatoire';
|
||||
}
|
||||
if (!value.contains('@')) {
|
||||
return 'Email invalide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _telephoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Téléphone',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.phone),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Genre
|
||||
DropdownButtonFormField<Genre>(
|
||||
value: _selectedGenre,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Genre',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.wc),
|
||||
),
|
||||
items: Genre.values.map((genre) {
|
||||
return DropdownMenuItem(
|
||||
value: genre,
|
||||
child: Text(_getGenreLabel(genre)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_selectedGenre = value;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Date de naissance
|
||||
InkWell(
|
||||
onTap: () => _selectDate(context),
|
||||
child: InputDecorator(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Date de naissance',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.calendar_today),
|
||||
),
|
||||
child: Text(
|
||||
_dateNaissance != null
|
||||
? DateFormat('dd/MM/yyyy').format(_dateNaissance!)
|
||||
: 'Sélectionner une date',
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Adresse
|
||||
_buildSectionTitle('Adresse'),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _adresseController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Adresse',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.home),
|
||||
),
|
||||
maxLines: 2,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _villeController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Ville',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _codePostalController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Code postal',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _regionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Région',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _paysController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Pays',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Informations professionnelles
|
||||
_buildSectionTitle('Informations professionnelles'),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _professionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Profession',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.work),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _nationaliteController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nationalité',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.flag),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 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(0xFF6C5CE7),
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: const Text('Créer le membre'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSectionTitle(String title) {
|
||||
return Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF6C5CE7),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _getGenreLabel(Genre genre) {
|
||||
switch (genre) {
|
||||
case Genre.homme:
|
||||
return 'Homme';
|
||||
case Genre.femme:
|
||||
return 'Femme';
|
||||
case Genre.autre:
|
||||
return 'Autre';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _selectDate(BuildContext context) async {
|
||||
final DateTime? picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _dateNaissance ?? DateTime.now().subtract(const Duration(days: 365 * 25)),
|
||||
firstDate: DateTime(1900),
|
||||
lastDate: DateTime.now(),
|
||||
);
|
||||
if (picked != null && picked != _dateNaissance) {
|
||||
setState(() {
|
||||
_dateNaissance = picked;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _submitForm() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
// Créer le modèle de membre
|
||||
final membre = MembreCompletModel(
|
||||
nom: _nomController.text,
|
||||
prenom: _prenomController.text,
|
||||
email: _emailController.text,
|
||||
telephone: _telephoneController.text.isNotEmpty ? _telephoneController.text : null,
|
||||
dateNaissance: _dateNaissance,
|
||||
genre: _selectedGenre,
|
||||
adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
|
||||
ville: _villeController.text.isNotEmpty ? _villeController.text : null,
|
||||
codePostal: _codePostalController.text.isNotEmpty ? _codePostalController.text : null,
|
||||
region: _regionController.text.isNotEmpty ? _regionController.text : null,
|
||||
pays: _paysController.text.isNotEmpty ? _paysController.text : null,
|
||||
profession: _professionController.text.isNotEmpty ? _professionController.text : null,
|
||||
nationalite: _nationaliteController.text.isNotEmpty ? _nationaliteController.text : null,
|
||||
statut: _selectedStatut,
|
||||
);
|
||||
|
||||
// Envoyer l'événement au BLoC
|
||||
context.read<MembresBloc>().add(CreateMembre(membre));
|
||||
|
||||
// Fermer le dialogue
|
||||
Navigator.pop(context);
|
||||
|
||||
// Afficher un message de succès
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Membre créé avec succès'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,441 @@
|
||||
/// Dialogue de modification de membre
|
||||
/// Formulaire complet pour modifier un membre existant
|
||||
library edit_member_dialog;
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../bloc/membres_bloc.dart';
|
||||
import '../../bloc/membres_event.dart';
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
|
||||
/// Dialogue de modification de membre
|
||||
class EditMemberDialog extends StatefulWidget {
|
||||
final MembreCompletModel membre;
|
||||
|
||||
const EditMemberDialog({
|
||||
super.key,
|
||||
required this.membre,
|
||||
});
|
||||
|
||||
@override
|
||||
State<EditMemberDialog> createState() => _EditMemberDialogState();
|
||||
}
|
||||
|
||||
class _EditMemberDialogState extends State<EditMemberDialog> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
|
||||
// Contrôleurs de texte
|
||||
late final TextEditingController _nomController;
|
||||
late final TextEditingController _prenomController;
|
||||
late final TextEditingController _emailController;
|
||||
late final TextEditingController _telephoneController;
|
||||
late final TextEditingController _adresseController;
|
||||
late final TextEditingController _villeController;
|
||||
late final TextEditingController _codePostalController;
|
||||
late final TextEditingController _regionController;
|
||||
late final TextEditingController _paysController;
|
||||
late final TextEditingController _professionController;
|
||||
late final TextEditingController _nationaliteController;
|
||||
|
||||
// Valeurs sélectionnées
|
||||
Genre? _selectedGenre;
|
||||
DateTime? _dateNaissance;
|
||||
StatutMembre? _selectedStatut;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
|
||||
// Initialiser les contrôleurs avec les valeurs existantes
|
||||
_nomController = TextEditingController(text: widget.membre.nom);
|
||||
_prenomController = TextEditingController(text: widget.membre.prenom);
|
||||
_emailController = TextEditingController(text: widget.membre.email);
|
||||
_telephoneController = TextEditingController(text: widget.membre.telephone ?? '');
|
||||
_adresseController = TextEditingController(text: widget.membre.adresse ?? '');
|
||||
_villeController = TextEditingController(text: widget.membre.ville ?? '');
|
||||
_codePostalController = TextEditingController(text: widget.membre.codePostal ?? '');
|
||||
_regionController = TextEditingController(text: widget.membre.region ?? '');
|
||||
_paysController = TextEditingController(text: widget.membre.pays ?? '');
|
||||
_professionController = TextEditingController(text: widget.membre.profession ?? '');
|
||||
_nationaliteController = TextEditingController(text: widget.membre.nationalite ?? '');
|
||||
|
||||
_selectedGenre = widget.membre.genre;
|
||||
_dateNaissance = widget.membre.dateNaissance;
|
||||
_selectedStatut = widget.membre.statut;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_telephoneController.dispose();
|
||||
_adresseController.dispose();
|
||||
_villeController.dispose();
|
||||
_codePostalController.dispose();
|
||||
_regionController.dispose();
|
||||
_paysController.dispose();
|
||||
_professionController.dispose();
|
||||
_nationaliteController.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(0xFF6C5CE7),
|
||||
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 le membre',
|
||||
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 personnelles
|
||||
_buildSectionTitle('Informations personnelles'),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _nomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Le nom est obligatoire';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _prenomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.person_outline),
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Le prénom est obligatoire';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.email),
|
||||
),
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'L\'email est obligatoire';
|
||||
}
|
||||
if (!value.contains('@')) {
|
||||
return 'Email invalide';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _telephoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Téléphone',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.phone),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Genre
|
||||
DropdownButtonFormField<Genre>(
|
||||
value: _selectedGenre,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Genre',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.wc),
|
||||
),
|
||||
items: Genre.values.map((genre) {
|
||||
return DropdownMenuItem(
|
||||
value: genre,
|
||||
child: Text(_getGenreLabel(genre)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_selectedGenre = value;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Statut
|
||||
DropdownButtonFormField<StatutMembre>(
|
||||
value: _selectedStatut,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Statut *',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.info),
|
||||
),
|
||||
items: StatutMembre.values.map((statut) {
|
||||
return DropdownMenuItem(
|
||||
value: statut,
|
||||
child: Text(_getStatutLabel(statut)),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
_selectedStatut = value;
|
||||
});
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Date de naissance
|
||||
InkWell(
|
||||
onTap: () => _selectDate(context),
|
||||
child: InputDecorator(
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Date de naissance',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.calendar_today),
|
||||
),
|
||||
child: Text(
|
||||
_dateNaissance != null
|
||||
? DateFormat('dd/MM/yyyy').format(_dateNaissance!)
|
||||
: 'Sélectionner une date',
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Adresse
|
||||
_buildSectionTitle('Adresse'),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _adresseController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Adresse',
|
||||
border: OutlineInputBorder(),
|
||||
prefixIcon: Icon(Icons.home),
|
||||
),
|
||||
maxLines: 2,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _villeController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Ville',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextFormField(
|
||||
controller: _codePostalController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Code postal',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _regionController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Région',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
TextFormField(
|
||||
controller: _paysController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Pays',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// 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(0xFF6C5CE7),
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
child: const Text('Enregistrer'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildSectionTitle(String title) {
|
||||
return Text(
|
||||
title,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF6C5CE7),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _getGenreLabel(Genre genre) {
|
||||
switch (genre) {
|
||||
case Genre.homme:
|
||||
return 'Homme';
|
||||
case Genre.femme:
|
||||
return 'Femme';
|
||||
case Genre.autre:
|
||||
return 'Autre';
|
||||
}
|
||||
}
|
||||
|
||||
String _getStatutLabel(StatutMembre statut) {
|
||||
switch (statut) {
|
||||
case StatutMembre.actif:
|
||||
return 'Actif';
|
||||
case StatutMembre.inactif:
|
||||
return 'Inactif';
|
||||
case StatutMembre.suspendu:
|
||||
return 'Suspendu';
|
||||
case StatutMembre.enAttente:
|
||||
return 'En attente';
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _selectDate(BuildContext context) async {
|
||||
final DateTime? picked = await showDatePicker(
|
||||
context: context,
|
||||
initialDate: _dateNaissance ?? DateTime.now().subtract(const Duration(days: 365 * 25)),
|
||||
firstDate: DateTime(1900),
|
||||
lastDate: DateTime.now(),
|
||||
);
|
||||
if (picked != null && picked != _dateNaissance) {
|
||||
setState(() {
|
||||
_dateNaissance = picked;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _submitForm() {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
// Créer le modèle de membre mis à jour
|
||||
final membreUpdated = widget.membre.copyWith(
|
||||
nom: _nomController.text,
|
||||
prenom: _prenomController.text,
|
||||
email: _emailController.text,
|
||||
telephone: _telephoneController.text.isNotEmpty ? _telephoneController.text : null,
|
||||
dateNaissance: _dateNaissance,
|
||||
genre: _selectedGenre,
|
||||
adresse: _adresseController.text.isNotEmpty ? _adresseController.text : null,
|
||||
ville: _villeController.text.isNotEmpty ? _villeController.text : null,
|
||||
codePostal: _codePostalController.text.isNotEmpty ? _codePostalController.text : null,
|
||||
region: _regionController.text.isNotEmpty ? _regionController.text : null,
|
||||
pays: _paysController.text.isNotEmpty ? _paysController.text : null,
|
||||
profession: _professionController.text.isNotEmpty ? _professionController.text : null,
|
||||
nationalite: _nationaliteController.text.isNotEmpty ? _nationaliteController.text : null,
|
||||
statut: _selectedStatut!,
|
||||
);
|
||||
|
||||
// Envoyer l'événement au BLoC
|
||||
context.read<MembresBloc>().add(UpdateMembre(widget.membre.id!, membreUpdated));
|
||||
|
||||
// Fermer le dialogue
|
||||
Navigator.pop(context);
|
||||
|
||||
// Afficher un message de succès
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Membre modifié avec succès'),
|
||||
backgroundColor: Colors.green,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,433 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../shared/models/membre_search_criteria.dart';
|
||||
|
||||
/// Formulaire de recherche de membres
|
||||
/// Widget réutilisable pour la saisie des critères de recherche
|
||||
class MembreSearchForm extends StatefulWidget {
|
||||
final MembreSearchCriteria initialCriteria;
|
||||
final Function(MembreSearchCriteria) onCriteriaChanged;
|
||||
final VoidCallback? onSearch;
|
||||
final VoidCallback? onClear;
|
||||
final bool isCompact;
|
||||
|
||||
const MembreSearchForm({
|
||||
super.key,
|
||||
this.initialCriteria = MembreSearchCriteria.empty,
|
||||
required this.onCriteriaChanged,
|
||||
this.onSearch,
|
||||
this.onClear,
|
||||
this.isCompact = false,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MembreSearchForm> createState() => _MembreSearchFormState();
|
||||
}
|
||||
|
||||
class _MembreSearchFormState extends State<MembreSearchForm> {
|
||||
late TextEditingController _queryController;
|
||||
late TextEditingController _nomController;
|
||||
late TextEditingController _prenomController;
|
||||
late TextEditingController _emailController;
|
||||
late TextEditingController _telephoneController;
|
||||
|
||||
String? _selectedStatut;
|
||||
List<String> _selectedRoles = [];
|
||||
RangeValues _ageRange = const RangeValues(18, 65);
|
||||
bool _includeInactifs = false;
|
||||
bool _membreBureau = false;
|
||||
bool _responsable = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initializeControllers();
|
||||
_loadInitialCriteria();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_queryController.dispose();
|
||||
_nomController.dispose();
|
||||
_prenomController.dispose();
|
||||
_emailController.dispose();
|
||||
_telephoneController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _initializeControllers() {
|
||||
_queryController = TextEditingController();
|
||||
_nomController = TextEditingController();
|
||||
_prenomController = TextEditingController();
|
||||
_emailController = TextEditingController();
|
||||
_telephoneController = TextEditingController();
|
||||
|
||||
// Écouter les changements pour mettre à jour les critères
|
||||
_queryController.addListener(_updateCriteria);
|
||||
_nomController.addListener(_updateCriteria);
|
||||
_prenomController.addListener(_updateCriteria);
|
||||
_emailController.addListener(_updateCriteria);
|
||||
_telephoneController.addListener(_updateCriteria);
|
||||
}
|
||||
|
||||
void _loadInitialCriteria() {
|
||||
final criteria = widget.initialCriteria;
|
||||
_queryController.text = criteria.query ?? '';
|
||||
_nomController.text = criteria.nom ?? '';
|
||||
_prenomController.text = criteria.prenom ?? '';
|
||||
_emailController.text = criteria.email ?? '';
|
||||
_telephoneController.text = criteria.telephone ?? '';
|
||||
_selectedStatut = criteria.statut;
|
||||
_selectedRoles = criteria.roles ?? [];
|
||||
_ageRange = RangeValues(
|
||||
criteria.ageMin?.toDouble() ?? 18,
|
||||
criteria.ageMax?.toDouble() ?? 65,
|
||||
);
|
||||
_includeInactifs = criteria.includeInactifs;
|
||||
_membreBureau = criteria.membreBureau ?? false;
|
||||
_responsable = criteria.responsable ?? false;
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.isCompact) {
|
||||
return _buildCompactForm();
|
||||
}
|
||||
return _buildFullForm();
|
||||
}
|
||||
|
||||
/// Formulaire compact pour recherche rapide
|
||||
Widget _buildCompactForm() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
children: [
|
||||
TextField(
|
||||
controller: _queryController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Rechercher un membre',
|
||||
hintText: 'Nom, prénom ou email...',
|
||||
prefixIcon: const Icon(Icons.search),
|
||||
suffixIcon: _queryController.text.isNotEmpty
|
||||
? IconButton(
|
||||
icon: const Icon(Icons.clear),
|
||||
onPressed: () {
|
||||
_queryController.clear();
|
||||
_updateCriteria();
|
||||
},
|
||||
)
|
||||
: null,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
onSubmitted: (_) => widget.onSearch?.call(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<String>(
|
||||
value: _selectedStatut,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Statut',
|
||||
border: OutlineInputBorder(),
|
||||
isDense: true,
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(value: null, child: Text('Tous')),
|
||||
DropdownMenuItem(value: 'ACTIF', child: Text('Actif')),
|
||||
DropdownMenuItem(value: 'INACTIF', child: Text('Inactif')),
|
||||
],
|
||||
onChanged: (value) {
|
||||
setState(() => _selectedStatut = value);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
if (widget.onSearch != null)
|
||||
ElevatedButton.icon(
|
||||
onPressed: widget.onSearch,
|
||||
icon: const Icon(Icons.search),
|
||||
label: const Text('Rechercher'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Formulaire complet avec tous les critères
|
||||
Widget _buildFullForm() {
|
||||
return Column(
|
||||
children: [
|
||||
// Recherche générale
|
||||
_buildGeneralSearchSection(),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Critères détaillés
|
||||
_buildDetailedCriteriaSection(),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Filtres avancés
|
||||
_buildAdvancedFiltersSection(),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Boutons d'action
|
||||
_buildActionButtons(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Section de recherche générale
|
||||
Widget _buildGeneralSearchSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Recherche Générale',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _queryController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Terme de recherche',
|
||||
hintText: 'Nom, prénom, email...',
|
||||
prefixIcon: Icon(Icons.search),
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Section des critères détaillés
|
||||
Widget _buildDetailedCriteriaSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Critères Détaillés',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _nomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _prenomController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Prénom',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Email',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _telephoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Téléphone',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: DropdownButtonFormField<String>(
|
||||
value: _selectedStatut,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Statut',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: const [
|
||||
DropdownMenuItem(value: null, child: Text('Tous')),
|
||||
DropdownMenuItem(value: 'ACTIF', child: Text('Actif')),
|
||||
DropdownMenuItem(value: 'INACTIF', child: Text('Inactif')),
|
||||
DropdownMenuItem(value: 'SUSPENDU', child: Text('Suspendu')),
|
||||
DropdownMenuItem(value: 'RADIE', child: Text('Radié')),
|
||||
],
|
||||
onChanged: (value) {
|
||||
setState(() => _selectedStatut = value);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Section des filtres avancés
|
||||
Widget _buildAdvancedFiltersSection() {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Filtres Avancés',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Tranche d'âge
|
||||
Text('Tranche d\'âge: ${_ageRange.start.round()}-${_ageRange.end.round()} ans'),
|
||||
RangeSlider(
|
||||
values: _ageRange,
|
||||
min: 18,
|
||||
max: 80,
|
||||
divisions: 62,
|
||||
labels: RangeLabels(
|
||||
'${_ageRange.start.round()}',
|
||||
'${_ageRange.end.round()}',
|
||||
),
|
||||
onChanged: (values) {
|
||||
setState(() => _ageRange = values);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Options booléennes
|
||||
CheckboxListTile(
|
||||
title: const Text('Inclure les membres inactifs'),
|
||||
value: _includeInactifs,
|
||||
onChanged: (value) {
|
||||
setState(() => _includeInactifs = value ?? false);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Membres du bureau uniquement'),
|
||||
value: _membreBureau,
|
||||
onChanged: (value) {
|
||||
setState(() => _membreBureau = value ?? false);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
CheckboxListTile(
|
||||
title: const Text('Responsables uniquement'),
|
||||
value: _responsable,
|
||||
onChanged: (value) {
|
||||
setState(() => _responsable = value ?? false);
|
||||
_updateCriteria();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Boutons d'action
|
||||
Widget _buildActionButtons() {
|
||||
return Row(
|
||||
children: [
|
||||
if (widget.onClear != null)
|
||||
Expanded(
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () {
|
||||
_clearForm();
|
||||
widget.onClear?.call();
|
||||
},
|
||||
icon: const Icon(Icons.clear),
|
||||
label: const Text('Effacer'),
|
||||
),
|
||||
),
|
||||
if (widget.onClear != null && widget.onSearch != null)
|
||||
const SizedBox(width: 16),
|
||||
if (widget.onSearch != null)
|
||||
Expanded(
|
||||
flex: widget.onClear != null ? 2 : 1,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: widget.onSearch,
|
||||
icon: const Icon(Icons.search),
|
||||
label: const Text('Rechercher'),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Met à jour les critères de recherche
|
||||
void _updateCriteria() {
|
||||
final criteria = MembreSearchCriteria(
|
||||
query: _queryController.text.trim().isEmpty ? null : _queryController.text.trim(),
|
||||
nom: _nomController.text.trim().isEmpty ? null : _nomController.text.trim(),
|
||||
prenom: _prenomController.text.trim().isEmpty ? null : _prenomController.text.trim(),
|
||||
email: _emailController.text.trim().isEmpty ? null : _emailController.text.trim(),
|
||||
telephone: _telephoneController.text.trim().isEmpty ? null : _telephoneController.text.trim(),
|
||||
statut: _selectedStatut,
|
||||
roles: _selectedRoles.isEmpty ? null : _selectedRoles,
|
||||
ageMin: _ageRange.start.round(),
|
||||
ageMax: _ageRange.end.round(),
|
||||
membreBureau: _membreBureau ? true : null,
|
||||
responsable: _responsable ? true : null,
|
||||
includeInactifs: _includeInactifs,
|
||||
);
|
||||
|
||||
widget.onCriteriaChanged(criteria);
|
||||
}
|
||||
|
||||
/// Efface le formulaire
|
||||
void _clearForm() {
|
||||
setState(() {
|
||||
_queryController.clear();
|
||||
_nomController.clear();
|
||||
_prenomController.clear();
|
||||
_emailController.clear();
|
||||
_telephoneController.clear();
|
||||
_selectedStatut = null;
|
||||
_selectedRoles.clear();
|
||||
_ageRange = const RangeValues(18, 65);
|
||||
_includeInactifs = false;
|
||||
_membreBureau = false;
|
||||
_responsable = false;
|
||||
});
|
||||
_updateCriteria();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
import '../../../../shared/models/membre_search_result.dart' as search_model;
|
||||
import '../../data/models/membre_complete_model.dart';
|
||||
|
||||
/// Widget d'affichage des résultats de recherche de membres
|
||||
/// Gère la pagination, le tri et l'affichage des membres trouvés
|
||||
class MembreSearchResults extends StatefulWidget {
|
||||
final search_model.MembreSearchResult result;
|
||||
final Function(MembreCompletModel)? onMembreSelected;
|
||||
final Function(int page)? onPageChanged;
|
||||
final bool showPagination;
|
||||
|
||||
const MembreSearchResults({
|
||||
super.key,
|
||||
required this.result,
|
||||
this.onMembreSelected,
|
||||
this.onPageChanged,
|
||||
this.showPagination = true,
|
||||
});
|
||||
|
||||
@override
|
||||
State<MembreSearchResults> createState() => _MembreSearchResultsState();
|
||||
}
|
||||
|
||||
class _MembreSearchResultsState extends State<MembreSearchResults> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (widget.result.isEmpty) {
|
||||
return _buildEmptyState();
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
// En-tête avec informations sur les résultats
|
||||
_buildResultsHeader(),
|
||||
|
||||
// Liste des membres
|
||||
Expanded(
|
||||
child: _buildMembersList(),
|
||||
),
|
||||
|
||||
// Pagination si activée
|
||||
if (widget.showPagination && widget.result.totalPages > 1)
|
||||
_buildPagination(),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// État vide quand aucun résultat
|
||||
Widget _buildEmptyState() {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.search_off,
|
||||
size: 64,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Aucun membre trouvé',
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Essayez de modifier vos critères de recherche',
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.grey[500],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton.icon(
|
||||
onPressed: () => Navigator.of(context).pop(),
|
||||
icon: const Icon(Icons.tune),
|
||||
label: const Text('Modifier les critères'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// En-tête avec informations sur les résultats
|
||||
Widget _buildResultsHeader() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).primaryColor.withOpacity(0.1),
|
||||
border: Border(
|
||||
bottom: BorderSide(
|
||||
color: Theme.of(context).dividerColor,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.search,
|
||||
color: Theme.of(context).primaryColor,
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
widget.result.resultDescription,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
Chip(
|
||||
label: Text('${widget.result.executionTimeMs}ms'),
|
||||
backgroundColor: Colors.green.withOpacity(0.1),
|
||||
labelStyle: const TextStyle(
|
||||
color: Colors.green,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (widget.result.criteria.description.isNotEmpty) ...[
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Critères: ${widget.result.criteria.description}',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Liste des membres trouvés
|
||||
Widget _buildMembersList() {
|
||||
return ListView.builder(
|
||||
itemCount: widget.result.membres.length,
|
||||
itemBuilder: (context, index) {
|
||||
final membre = widget.result.membres[index];
|
||||
return _buildMembreCard(membre, index);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
/// Carte d'affichage d'un membre
|
||||
Widget _buildMembreCard(MembreCompletModel membre, int index) {
|
||||
return Card(
|
||||
margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: _getStatusColor(membre.statut),
|
||||
child: Text(
|
||||
_getInitials(membre.nom, membre.prenom),
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
title: Text(
|
||||
'${membre.prenom} ${membre.nom}',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold),
|
||||
),
|
||||
subtitle: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (membre.email.isNotEmpty)
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.email, size: 14, color: Colors.grey),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
membre.email,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (membre.telephone?.isNotEmpty == true)
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.phone, size: 14, color: Colors.grey),
|
||||
const SizedBox(width: 4),
|
||||
Text(
|
||||
membre.telephone!,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (membre.organisationNom?.isNotEmpty == true)
|
||||
Row(
|
||||
children: [
|
||||
const Icon(Icons.business, size: 14, color: Colors.grey),
|
||||
const SizedBox(width: 4),
|
||||
Expanded(
|
||||
child: Text(
|
||||
membre.organisationNom!,
|
||||
style: const TextStyle(fontSize: 12),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
trailing: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
_buildStatusChip(membre.statut),
|
||||
if (membre.role?.isNotEmpty == true) ...[
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
_formatRoles(membre.role!),
|
||||
style: const TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.grey,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
onTap: widget.onMembreSelected != null
|
||||
? () => widget.onMembreSelected!(membre)
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Pagination
|
||||
Widget _buildPagination() {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).cardColor,
|
||||
border: Border(
|
||||
top: BorderSide(
|
||||
color: Theme.of(context).dividerColor,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
// Bouton page précédente
|
||||
ElevatedButton.icon(
|
||||
onPressed: widget.result.hasPrevious ? _goToPreviousPage : null,
|
||||
icon: const Icon(Icons.chevron_left),
|
||||
label: const Text('Précédent'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.grey[100],
|
||||
foregroundColor: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
|
||||
// Indicateur de page
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).primaryColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
'Page ${widget.result.currentPage + 1} / ${widget.result.totalPages}',
|
||||
style: TextStyle(
|
||||
color: Theme.of(context).primaryColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Bouton page suivante
|
||||
ElevatedButton.icon(
|
||||
onPressed: widget.result.hasNext ? _goToNextPage : null,
|
||||
icon: const Icon(Icons.chevron_right),
|
||||
label: const Text('Suivant'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Theme.of(context).primaryColor,
|
||||
foregroundColor: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Chip de statut
|
||||
Widget _buildStatusChip(StatutMembre statut) {
|
||||
final color = _getStatusColor(statut);
|
||||
return Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: color, width: 1),
|
||||
),
|
||||
child: Text(
|
||||
_getStatusLabel(statut),
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Obtient la couleur du statut
|
||||
Color _getStatusColor(StatutMembre statut) {
|
||||
switch (statut) {
|
||||
case StatutMembre.actif:
|
||||
return Colors.green;
|
||||
case StatutMembre.inactif:
|
||||
return Colors.orange;
|
||||
case StatutMembre.suspendu:
|
||||
return Colors.red;
|
||||
case StatutMembre.enAttente:
|
||||
return Colors.grey;
|
||||
default:
|
||||
return Colors.grey;
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtient le libellé du statut
|
||||
String _getStatusLabel(StatutMembre statut) {
|
||||
switch (statut) {
|
||||
case StatutMembre.actif:
|
||||
return 'Actif';
|
||||
case StatutMembre.inactif:
|
||||
return 'Inactif';
|
||||
case StatutMembre.suspendu:
|
||||
return 'Suspendu';
|
||||
case StatutMembre.enAttente:
|
||||
return 'En attente';
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtient les initiales d'un membre
|
||||
String _getInitials(String nom, String prenom) {
|
||||
final nomInitial = nom.isNotEmpty ? nom[0].toUpperCase() : '';
|
||||
final prenomInitial = prenom.isNotEmpty ? prenom[0].toUpperCase() : '';
|
||||
return '$prenomInitial$nomInitial';
|
||||
}
|
||||
|
||||
/// Formate les rôles pour l'affichage
|
||||
String _formatRoles(String roles) {
|
||||
final rolesList = roles.split(',').map((r) => r.trim()).toList();
|
||||
if (rolesList.length <= 2) {
|
||||
return rolesList.join(', ');
|
||||
}
|
||||
return '${rolesList.take(2).join(', ')}...';
|
||||
}
|
||||
|
||||
/// Navigation vers la page précédente
|
||||
void _goToPreviousPage() {
|
||||
if (widget.result.hasPrevious && widget.onPageChanged != null) {
|
||||
widget.onPageChanged!(widget.result.currentPage - 1);
|
||||
}
|
||||
}
|
||||
|
||||
/// Navigation vers la page suivante
|
||||
void _goToNextPage() {
|
||||
if (widget.result.hasNext && widget.onPageChanged != null) {
|
||||
widget.onPageChanged!(widget.result.currentPage + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,416 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:fl_chart/fl_chart.dart';
|
||||
|
||||
import '../../../../shared/models/membre_search_result.dart';
|
||||
|
||||
/// Widget d'affichage des statistiques de recherche
|
||||
/// Présente les métriques et graphiques des résultats de recherche
|
||||
class SearchStatisticsCard extends StatelessWidget {
|
||||
final SearchStatistics statistics;
|
||||
|
||||
const SearchStatisticsCard({
|
||||
super.key,
|
||||
required this.statistics,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Titre
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.analytics,
|
||||
color: Theme.of(context).primaryColor,
|
||||
size: 24,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Statistiques de Recherche',
|
||||
style: Theme.of(context).textTheme.titleLarge?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Métriques principales
|
||||
_buildMainMetrics(context),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Graphique de répartition actifs/inactifs
|
||||
_buildStatusChart(context),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Métriques détaillées
|
||||
_buildDetailedMetrics(context),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Informations complémentaires
|
||||
_buildAdditionalInfo(context),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Métriques principales
|
||||
Widget _buildMainMetrics(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Vue d\'ensemble',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
context,
|
||||
'Total Membres',
|
||||
statistics.totalMembres.toString(),
|
||||
Icons.people,
|
||||
Colors.blue,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
context,
|
||||
'Membres Actifs',
|
||||
statistics.membresActifs.toString(),
|
||||
Icons.person,
|
||||
Colors.green,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
context,
|
||||
'Âge Moyen',
|
||||
'${statistics.ageMoyen.toStringAsFixed(1)} ans',
|
||||
Icons.cake,
|
||||
Colors.orange,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: _buildMetricCard(
|
||||
context,
|
||||
'Ancienneté',
|
||||
'${statistics.ancienneteMoyenne.toStringAsFixed(1)} ans',
|
||||
Icons.schedule,
|
||||
Colors.purple,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Carte de métrique individuelle
|
||||
Widget _buildMetricCard(
|
||||
BuildContext context,
|
||||
String title,
|
||||
String value,
|
||||
IconData icon,
|
||||
Color color,
|
||||
) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: color.withOpacity(0.3)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Icon(icon, color: color, size: 24),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
title,
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Graphique de répartition des statuts
|
||||
Widget _buildStatusChart(BuildContext context) {
|
||||
if (statistics.totalMembres == 0) {
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Répartition par Statut',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
SizedBox(
|
||||
height: 200,
|
||||
child: Row(
|
||||
children: [
|
||||
// Graphique en secteurs
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: PieChart(
|
||||
PieChartData(
|
||||
sections: [
|
||||
PieChartSectionData(
|
||||
value: statistics.membresActifs.toDouble(),
|
||||
title: '${statistics.pourcentageActifs.toStringAsFixed(1)}%',
|
||||
color: Colors.green,
|
||||
radius: 60,
|
||||
titleStyle: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
if (statistics.membresInactifs > 0)
|
||||
PieChartSectionData(
|
||||
value: statistics.membresInactifs.toDouble(),
|
||||
title: '${statistics.pourcentageInactifs.toStringAsFixed(1)}%',
|
||||
color: Colors.orange,
|
||||
radius: 60,
|
||||
titleStyle: const TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
),
|
||||
),
|
||||
],
|
||||
sectionsSpace: 2,
|
||||
centerSpaceRadius: 40,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Légende
|
||||
Expanded(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
_buildLegendItem(
|
||||
'Actifs',
|
||||
statistics.membresActifs,
|
||||
Colors.green,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
if (statistics.membresInactifs > 0)
|
||||
_buildLegendItem(
|
||||
'Inactifs',
|
||||
statistics.membresInactifs,
|
||||
Colors.orange,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Item de légende
|
||||
Widget _buildLegendItem(String label, int count, Color color) {
|
||||
return Row(
|
||||
children: [
|
||||
Container(
|
||||
width: 12,
|
||||
height: 12,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'$label ($count)',
|
||||
style: const TextStyle(fontSize: 12),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Métriques détaillées
|
||||
Widget _buildDetailedMetrics(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Détails Démographiques',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
_buildDetailRow(
|
||||
context,
|
||||
'Tranche d\'âge',
|
||||
statistics.trancheAge,
|
||||
Icons.calendar_today,
|
||||
),
|
||||
_buildDetailRow(
|
||||
context,
|
||||
'Organisations',
|
||||
'${statistics.nombreOrganisations} représentées',
|
||||
Icons.business,
|
||||
),
|
||||
_buildDetailRow(
|
||||
context,
|
||||
'Régions',
|
||||
'${statistics.nombreRegions} représentées',
|
||||
Icons.location_on,
|
||||
),
|
||||
_buildDetailRow(
|
||||
context,
|
||||
'Taux d\'activité',
|
||||
'${statistics.pourcentageActifs.toStringAsFixed(1)}%',
|
||||
Icons.trending_up,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Ligne de détail
|
||||
Widget _buildDetailRow(
|
||||
BuildContext context,
|
||||
String label,
|
||||
String value,
|
||||
IconData icon,
|
||||
) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8.0),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: 20,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: Theme.of(context).textTheme.bodyMedium,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
value,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Informations complémentaires
|
||||
Widget _buildAdditionalInfo(BuildContext context) {
|
||||
return Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(16.0),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.info_outline,
|
||||
color: Theme.of(context).primaryColor,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Informations Complémentaires',
|
||||
style: Theme.of(context).textTheme.titleMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
statistics.description,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12.0),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.blue.withOpacity(0.3)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.lightbulb, color: Colors.blue),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Ces statistiques sont calculées en temps réel sur les résultats de votre recherche.',
|
||||
style: Theme.of(context).textTheme.bodySmall?.copyWith(
|
||||
color: Colors.blue[700],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user