fix(mobile): URL changement mdp corrigée + v3.0 — multi-org, AppAuth, sécurité prod

Auth:
- profile_repository.dart: /api/auth/change-password → /api/membres/auth/change-password

Multi-org (Phase 3):
- OrgSelectorPage, OrgSwitcherBloc, OrgSwitcherEntry
- org_context_service.dart: headers X-Active-Organisation-Id + X-Active-Role

Navigation:
- MorePage: navigation conditionnelle par typeOrganisation
- Suppression adaptive_navigation (remplacé par main_navigation_layout)

Auth AppAuth:
- keycloak_webview_auth_service: fixes AppAuth Android
- AuthBloc: gestion REAUTH_REQUIS + premierLoginComplet

Onboarding:
- Nouveaux états: payment_method_page, onboarding_shared_widgets
- SouscriptionStatusModel mis à jour StatutValidationSouscription

Android:
- build.gradle: ProGuard/R8, network_security_config
- Gradle wrapper mis à jour
This commit is contained in:
dahoud
2026-04-07 20:56:03 +00:00
parent 22f9c7e9a1
commit 70cbd1c873
63 changed files with 9316 additions and 6122 deletions

View File

@@ -80,7 +80,9 @@ class _AdhesionsPageState extends State<AdhesionsPage>
action: SnackBarAction(
label: 'Réessayer',
textColor: Colors.white,
onPressed: () => _loadTab(_tabController.index),
onPressed: () {
if (mounted) _loadTab(_tabController.index);
},
),
),
);

View File

@@ -126,10 +126,11 @@ class KeycloakWebViewAuthService {
),
);
// Clés de stockage sécurisé
static const String _accessTokenKey = 'keycloak_webview_access_token';
static const String _idTokenKey = 'keycloak_webview_id_token';
static const String _refreshTokenKey = 'keycloak_webview_refresh_token';
// Clés de stockage sécurisé — alignées avec KeycloakAuthService pour éviter IC-03
// KeycloakAuthService lit 'kc_access' / 'kc_refresh' / 'kc_id' ; ApiClient aussi.
static const String _accessTokenKey = 'kc_access';
static const String _idTokenKey = 'kc_id';
static const String _refreshTokenKey = 'kc_refresh';
static const String _userInfoKey = 'keycloak_webview_user_info';
static const String _authStateKey = 'keycloak_webview_auth_state';

View File

@@ -6,6 +6,7 @@ import '../../data/models/user_role.dart';
import '../../data/datasources/keycloak_auth_service.dart';
import '../../data/datasources/permission_engine.dart';
import '../../../../core/config/environment.dart';
import '../../../../core/network/org_context_service.dart';
import '../../../../core/storage/dashboard_cache_manager.dart';
import '../../../../core/utils/logger.dart';
import '../../../../core/di/injection.dart';
@@ -87,16 +88,32 @@ class AuthPendingOnboarding extends AuthState {
List<Object?> get props => [onboardingState, souscriptionId, organisationId, typeOrganisation];
}
// Nouvel événement : auto-select l'org active après login (pour membres mono-org)
class AuthOrgContextInitRequested extends AuthEvent {
final String organisationId;
final String organisationNom;
final String? type;
const AuthOrgContextInitRequested({
required this.organisationId,
required this.organisationNom,
this.type,
});
@override
List<Object?> get props => [organisationId, organisationNom, type];
}
// === BLOC ===
@lazySingleton
class AuthBloc extends Bloc<AuthEvent, AuthState> {
final KeycloakAuthService _authService;
final OrgContextService _orgContextService;
AuthBloc(this._authService) : super(AuthInitial()) {
AuthBloc(this._authService, this._orgContextService) : super(AuthInitial()) {
on<AuthLoginRequested>(_onLoginRequested);
on<AuthLogoutRequested>(_onLogoutRequested);
on<AuthStatusChecked>(_onStatusChecked);
on<AuthTokenRefreshRequested>(_onTokenRefreshRequested);
on<AuthOrgContextInitRequested>(_onOrgContextInit);
}
Future<void> _onLoginRequested(AuthLoginRequested event, Emitter<AuthState> emit) async {
@@ -185,9 +202,22 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
emit(AuthLoading());
await _authService.logout();
await DashboardCacheManager.clear();
_orgContextService.clear();
emit(AuthUnauthenticated());
}
Future<void> _onOrgContextInit(
AuthOrgContextInitRequested event,
Emitter<AuthState> emit,
) async {
_orgContextService.setActiveOrganisation(
organisationId: event.organisationId,
nom: event.organisationNom,
type: event.type,
);
AppLogger.info('AuthBloc: contexte org initialisé → ${event.organisationNom}');
}
Future<void> _onStatusChecked(AuthStatusChecked event, Emitter<AuthState> emit) async {
final tokenValid = await _authService.getValidToken();
final isAuth = tokenValid != null;
@@ -276,9 +306,18 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
///
/// Si le rôle est [UserRole.orgAdmin] et que [organizationContexts] est vide,
/// appelle GET /api/organisations/mes pour récupérer les organisations de l'admin.
/// Auto-initialise [OrgContextService] si une seule organisation.
Future<User> _enrichUserWithOrgContext(User user) async {
if (user.primaryRole != UserRole.orgAdmin ||
user.organizationContexts.isNotEmpty) {
// Auto-select le premier contexte existant si pas encore de contexte actif
if (!_orgContextService.hasContext && user.organizationContexts.isNotEmpty) {
final first = user.organizationContexts.first;
_orgContextService.setActiveOrganisation(
organisationId: first.organizationId,
nom: first.organizationName,
);
}
return user;
}
try {
@@ -296,7 +335,15 @@ class AuthBloc extends Bloc<AuthEvent, AuthState> {
),
)
.toList();
return contexts.isEmpty ? user : user.copyWith(organizationContexts: contexts);
if (contexts.isEmpty) return user;
// Auto-select si une seule organisation
if (contexts.length == 1 && !_orgContextService.hasContext) {
_orgContextService.setActiveOrganisation(
organisationId: contexts.first.organizationId,
nom: contexts.first.organizationName,
);
}
return user.copyWith(organizationContexts: contexts);
} catch (e) {
AppLogger.warning('AuthBloc: impossible de charger le contexte org: $e');
return user;

View File

@@ -1,327 +1,121 @@
/// Page d'Authentification UnionFlow
///
/// Interface utilisateur pour la connexion sécurisée
/// avec gestion complète des états et des erreurs.
/// Interface utilisateur pour la connexion sécurisée via AppAuth (RFC 8252).
library keycloak_webview_auth_page;
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:webview_flutter/webview_flutter.dart';
import '../../data/datasources/keycloak_webview_auth_service.dart';
import 'package:flutter_appauth/flutter_appauth.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:jwt_decoder/jwt_decoder.dart';
import '../../data/datasources/keycloak_auth_service.dart';
import '../../data/datasources/keycloak_role_mapper.dart';
import '../../data/models/user.dart';
import '../../../../shared/design_system/tokens/color_tokens.dart';
import '../../../../shared/design_system/tokens/spacing_tokens.dart';
import '../../../../shared/design_system/tokens/typography_tokens.dart';
/// États de l'authentification WebView
enum KeycloakWebViewAuthState {
/// Initialisation en cours
initializing,
/// Chargement de la page d'authentification
loading,
/// Page d'authentification affichée
ready,
/// Authentification en cours
authenticating,
/// Authentification réussie
success,
/// Erreur d'authentification
error,
/// Timeout
timeout,
}
/// Page d'authentification Keycloak avec WebView
/// Page d'authentification Keycloak via AppAuth
class KeycloakWebViewAuthPage extends StatefulWidget {
/// Callback appelé en cas de succès d'authentification
final Function(User user) onAuthSuccess;
/// Callback appelé en cas d'erreur
final Function(String error) onAuthError;
/// Callback appelé en cas d'annulation
final VoidCallback? onAuthCancel;
/// Timeout pour l'authentification (en secondes)
final int timeoutSeconds;
const KeycloakWebViewAuthPage({
super.key,
required this.onAuthSuccess,
required this.onAuthError,
this.onAuthCancel,
this.timeoutSeconds = 300, // 5 minutes par défaut
this.timeoutSeconds = 300,
});
@override
State<KeycloakWebViewAuthPage> createState() => _KeycloakWebViewAuthPageState();
}
class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage>
with TickerProviderStateMixin {
// Contrôleurs et état
late WebViewController _webViewController;
late AnimationController _progressAnimationController;
late Animation<double> _progressAnimation;
Timer? _timeoutTimer;
// État de l'authentification
KeycloakWebViewAuthState _authState = KeycloakWebViewAuthState.initializing;
class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage> {
bool _loading = true;
String? _errorMessage;
double _loadingProgress = 0.0;
// Paramètres d'authentification
String? _authUrl;
static const _appAuth = FlutterAppAuth();
static const _storage = FlutterSecureStorage(
aOptions: AndroidOptions(encryptedSharedPreferences: true),
iOptions: IOSOptions(accessibility: KeychainAccessibility.first_unlock_this_device),
);
@override
void initState() {
super.initState();
_initializeAnimations();
_initializeAuthentication();
_authenticate();
}
@override
void dispose() {
_progressAnimationController.dispose();
_timeoutTimer?.cancel();
super.dispose();
}
/// Initialise les animations
void _initializeAnimations() {
_progressAnimationController = AnimationController(
duration: const Duration(milliseconds: 300),
vsync: this,
);
_progressAnimation = Tween<double>(
begin: 0.0,
end: 1.0,
).animate(CurvedAnimation(
parent: _progressAnimationController,
curve: Curves.easeInOut,
));
}
/// Initialise l'authentification
Future<void> _initializeAuthentication() async {
Future<void> _authenticate() async {
try {
debugPrint('🚀 Initialisation de l\'authentification WebView...');
setState(() {
_authState = KeycloakWebViewAuthState.initializing;
});
// Préparer l'authentification
final Map<String, String> authParams =
await KeycloakWebViewAuthService.prepareAuthentication();
_authUrl = authParams['url'];
if (_authUrl == null) {
throw Exception('URL d\'authentification manquante');
}
// Initialiser la WebView
await _initializeWebView();
// Démarrer le timer de timeout
_startTimeoutTimer();
debugPrint('✅ Authentification initialisée avec succès');
} catch (e) {
debugPrint('💥 Erreur initialisation authentification: $e');
_handleError('Erreur d\'initialisation: $e');
}
}
/// Initialise la WebView
Future<void> _initializeWebView() async {
_webViewController = WebViewController()
..setJavaScriptMode(JavaScriptMode.unrestricted)
..setBackgroundColor(ColorTokens.surface)
..setNavigationDelegate(
NavigationDelegate(
onProgress: _onLoadingProgress,
onPageStarted: _onPageStarted,
onPageFinished: _onPageFinished,
onWebResourceError: _onWebResourceError,
onNavigationRequest: _onNavigationRequest,
final result = await _appAuth.authorizeAndExchangeCode(
AuthorizationTokenRequest(
KeycloakConfig.clientId,
'dev.lions.unionflow-mobile://auth/callback',
serviceConfiguration: AuthorizationServiceConfiguration(
authorizationEndpoint:
'${KeycloakConfig.baseUrl}/realms/${KeycloakConfig.realm}/protocol/openid-connect/auth',
tokenEndpoint: KeycloakConfig.tokenEndpoint,
),
scopes: ['openid', 'profile', 'email', 'roles', 'offline_access'],
additionalParameters: {'kc_locale': 'fr'},
allowInsecureConnections: true,
),
);
// Charger l'URL d'authentification
if (_authUrl != null) {
await _webViewController.loadRequest(Uri.parse(_authUrl!));
setState(() {
_authState = KeycloakWebViewAuthState.loading;
});
}
}
/// Démarre le timer de timeout
void _startTimeoutTimer() {
_timeoutTimer = Timer(Duration(seconds: widget.timeoutSeconds), () {
if (_authState != KeycloakWebViewAuthState.success) {
debugPrint('⏰ Timeout d\'authentification atteint');
_handleTimeout();
}
});
}
/// Gère la progression du chargement
void _onLoadingProgress(int progress) {
setState(() {
_loadingProgress = progress / 100.0;
});
if (progress == 100) {
_progressAnimationController.forward();
}
}
/// Gère le début du chargement d'une page
void _onPageStarted(String url) {
debugPrint('📄 Chargement de la page: $url');
setState(() {
_loadingProgress = 0.0;
});
_progressAnimationController.reset();
}
/// Gère la fin du chargement d'une page
void _onPageFinished(String url) {
debugPrint('✅ Page chargée: $url');
setState(() {
if (_authState == KeycloakWebViewAuthState.loading) {
_authState = KeycloakWebViewAuthState.ready;
}
});
}
/// Gère les erreurs de ressources web
void _onWebResourceError(WebResourceError error) {
debugPrint('💥 Erreur WebView: ${error.description}');
// Ignorer certaines erreurs non critiques
if (error.errorCode == -999) { // Code d'erreur pour annulation
return;
}
_handleError('Erreur de chargement: ${error.description}');
}
/// Gère les requêtes de navigation
NavigationDecision _onNavigationRequest(NavigationRequest request) {
final String url = request.url;
debugPrint('🔗 Navigation vers: $url');
// Vérifier si c'est notre URL de callback
if (url.startsWith('dev.lions.unionflow-mobile://auth/callback')) {
debugPrint('🎯 URL de callback détectée: $url');
_handleAuthCallback(url);
return NavigationDecision.prevent;
}
// Vérifier d'autres patterns de callback possibles
if (url.contains('code=') && url.contains('state=')) {
debugPrint('🎯 Callback potentiel détecté (avec code et state): $url');
_handleAuthCallback(url);
return NavigationDecision.prevent;
}
return NavigationDecision.navigate;
}
/// Traite le callback d'authentification
Future<void> _handleAuthCallback(String callbackUrl) async {
try {
setState(() {
_authState = KeycloakWebViewAuthState.authenticating;
});
debugPrint('🔄 Traitement du callback d\'authentification...');
debugPrint('📋 URL de callback reçue: $callbackUrl');
// Traiter le callback via le service
final User user = await KeycloakWebViewAuthService.handleAuthCallback(callbackUrl);
setState(() {
_authState = KeycloakWebViewAuthState.success;
});
// Annuler le timer de timeout
_timeoutTimer?.cancel();
debugPrint('🎉 Authentification réussie pour: ${user.fullName}');
debugPrint('👤 Rôle: ${user.primaryRole.displayName}');
debugPrint('🔐 Permissions: ${user.additionalPermissions.length}');
// Notifier le succès avec un délai pour l'animation
Future.delayed(const Duration(milliseconds: 500), () {
widget.onAuthSuccess(user);
});
} catch (e, stackTrace) {
debugPrint('💥 Erreur traitement callback: $e');
debugPrint('📋 Stack trace: $stackTrace');
// Essayer de donner plus d'informations sur l'erreur
String errorMessage = 'Erreur d\'authentification: $e';
if (e.toString().contains('MISSING_AUTH_STATE')) {
errorMessage = 'Session expirée. Veuillez réessayer.';
} else if (e.toString().contains('INVALID_STATE')) {
errorMessage = 'Erreur de sécurité. Veuillez réessayer.';
} else if (e.toString().contains('MISSING_AUTH_CODE')) {
errorMessage = 'Code d\'autorisation manquant. Veuillez réessayer.';
if (result?.accessToken == null) {
_onError('Authentification annulée ou échouée.');
return;
}
_handleError(errorMessage);
await _storage.write(key: 'kc_access', value: result!.accessToken);
if (result.refreshToken != null) {
await _storage.write(key: 'kc_refresh', value: result.refreshToken);
}
if (result.idToken != null) {
await _storage.write(key: 'kc_id', value: result.idToken);
}
final accessPayload = JwtDecoder.decode(result.accessToken!);
final idPayload = result.idToken != null ? JwtDecoder.decode(result.idToken!) : accessPayload;
final roles = _extractRoles(accessPayload);
final primaryRole = KeycloakRoleMapper.mapToUserRole(roles);
final user = User(
id: idPayload['sub'] ?? '',
email: idPayload['email'] ?? '',
firstName: idPayload['given_name'] ?? '',
lastName: idPayload['family_name'] ?? '',
primaryRole: primaryRole,
additionalPermissions: KeycloakRoleMapper.mapToPermissions(roles),
isActive: true,
lastLoginAt: DateTime.now(),
createdAt: DateTime.now(),
);
if (mounted) {
setState(() => _loading = false);
Future.delayed(const Duration(milliseconds: 300), () {
widget.onAuthSuccess(user);
});
}
} catch (e) {
_onError('Erreur d\'authentification: $e');
}
}
/// Gère les erreurs
void _handleError(String error) {
setState(() {
_authState = KeycloakWebViewAuthState.error;
_errorMessage = error;
});
_timeoutTimer?.cancel();
// Vibration pour indiquer l'erreur
void _onError(String error) {
HapticFeedback.lightImpact();
if (mounted) setState(() { _loading = false; _errorMessage = error; });
widget.onAuthError(error);
}
/// Gère le timeout
void _handleTimeout() {
setState(() {
_authState = KeycloakWebViewAuthState.timeout;
_errorMessage = 'Timeout d\'authentification atteint';
});
HapticFeedback.lightImpact();
widget.onAuthError('Timeout d\'authentification');
}
/// Gère l'annulation
void _handleCancel() {
debugPrint('❌ Authentification annulée par l\'utilisateur');
_timeoutTimer?.cancel();
if (widget.onAuthCancel != null) {
widget.onAuthCancel!();
} else {
@@ -329,92 +123,45 @@ class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage>
}
}
List<String> _extractRoles(Map<String, dynamic> payload) {
final roles = <String>[];
if (payload['realm_access']?['roles'] != null) {
roles.addAll((payload['realm_access']['roles'] as List).cast<String>());
}
if (payload['resource_access'] != null) {
(payload['resource_access'] as Map).values.forEach((v) {
if (v['roles'] != null) roles.addAll((v['roles'] as List).cast<String>());
});
}
return roles.where((r) => !r.startsWith('default-roles-') && r != 'offline_access').toList();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: ColorTokens.surface,
appBar: _buildAppBar(),
body: _buildBody(),
);
}
/// Construit l'AppBar
PreferredSizeWidget _buildAppBar() {
return AppBar(
backgroundColor: ColorTokens.primary,
foregroundColor: ColorTokens.onPrimary,
elevation: 0,
title: Text(
'Connexion Sécurisée',
style: TypographyTokens.headlineSmall.copyWith(
color: ColorTokens.onPrimary,
fontWeight: FontWeight.w600,
),
),
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: _handleCancel,
tooltip: 'Annuler',
),
actions: [
if (_authState == KeycloakWebViewAuthState.ready)
IconButton(
icon: const Icon(Icons.refresh),
onPressed: () => _webViewController.reload(),
tooltip: 'Actualiser',
appBar: AppBar(
backgroundColor: ColorTokens.primary,
foregroundColor: ColorTokens.onPrimary,
elevation: 0,
title: Text(
'Connexion Sécurisée',
style: TypographyTokens.headlineSmall.copyWith(
color: ColorTokens.onPrimary,
fontWeight: FontWeight.w600,
),
],
bottom: _buildProgressIndicator(),
),
leading: IconButton(
icon: const Icon(Icons.close),
onPressed: _handleCancel,
tooltip: 'Annuler',
),
),
body: _errorMessage != null ? _buildErrorView() : _buildLoadingView(),
);
}
/// Construit l'indicateur de progression
PreferredSizeWidget? _buildProgressIndicator() {
if (_authState == KeycloakWebViewAuthState.loading ||
_authState == KeycloakWebViewAuthState.authenticating) {
return PreferredSize(
preferredSize: const Size.fromHeight(4.0),
child: AnimatedBuilder(
animation: _progressAnimation,
builder: (context, child) {
return LinearProgressIndicator(
value: _authState == KeycloakWebViewAuthState.authenticating
? null
: _loadingProgress,
backgroundColor: ColorTokens.onPrimary.withOpacity(0.3),
valueColor: const AlwaysStoppedAnimation<Color>(ColorTokens.onPrimary),
);
},
),
);
}
return null;
}
/// Construit le corps de la page
Widget _buildBody() {
switch (_authState) {
case KeycloakWebViewAuthState.initializing:
return _buildInitializingView();
case KeycloakWebViewAuthState.loading:
case KeycloakWebViewAuthState.ready:
return _buildWebView();
case KeycloakWebViewAuthState.authenticating:
return _buildAuthenticatingView();
case KeycloakWebViewAuthState.success:
return _buildSuccessView();
case KeycloakWebViewAuthState.error:
case KeycloakWebViewAuthState.timeout:
return _buildErrorView();
}
}
/// Vue d'initialisation
Widget _buildInitializingView() {
Widget _buildLoadingView() {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
@@ -422,95 +169,14 @@ class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage>
const CircularProgressIndicator(),
const SizedBox(height: SpacingTokens.xl),
Text(
'Initialisation...',
style: TypographyTokens.bodyLarge.copyWith(
color: ColorTokens.onSurface,
),
'Connexion en cours...',
style: TypographyTokens.bodyLarge.copyWith(color: ColorTokens.onSurface),
),
],
),
);
}
/// Vue WebView
Widget _buildWebView() {
return WebViewWidget(controller: _webViewController);
}
/// Vue d'authentification en cours
Widget _buildAuthenticatingView() {
return Container(
color: ColorTokens.surface,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const CircularProgressIndicator(),
const SizedBox(height: SpacingTokens.xxxl),
Text(
'Connexion en cours...',
style: TypographyTokens.headlineSmall.copyWith(
color: ColorTokens.onSurface,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: SpacingTokens.xl),
Text(
'Veuillez patienter pendant que nous\nvérifions vos informations.',
textAlign: TextAlign.center,
style: TypographyTokens.bodyMedium.copyWith(
color: ColorTokens.onSurface.withOpacity(0.7),
),
),
],
),
),
);
}
/// Vue de succès
Widget _buildSuccessView() {
return Container(
color: ColorTokens.surface,
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 80,
height: 80,
decoration: const BoxDecoration(
color: Colors.green,
shape: BoxShape.circle,
),
child: const Icon(
Icons.check,
color: Colors.white,
size: 48,
),
),
const SizedBox(height: SpacingTokens.xxxl),
Text(
'Connexion réussie !',
style: TypographyTokens.headlineSmall.copyWith(
color: ColorTokens.onSurface,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: SpacingTokens.xl),
Text(
'Redirection vers l\'application...',
style: TypographyTokens.bodyMedium.copyWith(
color: ColorTokens.onSurface.withOpacity(0.7),
),
),
],
),
),
);
}
/// Vue d'erreur
Widget _buildErrorView() {
return Container(
color: ColorTokens.surface,
@@ -526,19 +192,11 @@ class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage>
color: ColorTokens.error,
shape: BoxShape.circle,
),
child: Icon(
_authState == KeycloakWebViewAuthState.timeout
? Icons.access_time
: Icons.error_outline,
color: ColorTokens.onError,
size: 48,
),
child: const Icon(Icons.error_outline, color: ColorTokens.onError, size: 48),
),
const SizedBox(height: SpacingTokens.xxxl),
Text(
_authState == KeycloakWebViewAuthState.timeout
? 'Délai d\'attente dépassé'
: 'Erreur de connexion',
'Erreur de connexion',
style: TypographyTokens.headlineSmall.copyWith(
color: ColorTokens.onSurface,
fontWeight: FontWeight.w600,
@@ -557,7 +215,10 @@ class _KeycloakWebViewAuthPageState extends State<KeycloakWebViewAuthPage>
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
ElevatedButton.icon(
onPressed: _initializeAuthentication,
onPressed: () {
setState(() { _loading = true; _errorMessage = null; });
_authenticate();
},
icon: const Icon(Icons.refresh),
label: const Text('Réessayer'),
style: ElevatedButton.styleFrom(

View File

@@ -4,7 +4,6 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:local_auth/local_auth.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';
import '../bloc/auth_bloc.dart';
@@ -20,16 +19,11 @@ class LoginPage extends StatefulWidget {
}
class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
final _emailController = TextEditingController();
final _passwordController = TextEditingController();
late final AnimationController _fadeController;
late final AnimationController _slideController;
late final Animation<double> _fadeAnim;
late final Animation<Offset> _slideAnim;
bool _obscurePassword = true;
bool _rememberMe = false;
bool _biometricAvailable = false;
final _localAuth = LocalAuthentication();
@@ -50,15 +44,12 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
_fadeController.forward();
_slideController.forward();
_checkBiometrics();
_loadSavedCredentials();
}
@override
void dispose() {
_fadeController.dispose();
_slideController.dispose();
_emailController.dispose();
_passwordController.dispose();
super.dispose();
}
@@ -70,17 +61,6 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
} catch (_) {}
}
Future<void> _loadSavedCredentials() async {
final prefs = await SharedPreferences.getInstance();
final remember = prefs.getBool('uf_remember_me') ?? false;
if (remember && mounted) {
setState(() {
_rememberMe = true;
_emailController.text = prefs.getString('uf_saved_email') ?? '';
});
}
}
Future<void> _authenticateBiometric() async {
try {
final ok = await _localAuth.authenticate(
@@ -88,12 +68,7 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
options: const AuthenticationOptions(stickyAuth: true, biometricOnly: false),
);
if (ok && mounted) {
final prefs = await SharedPreferences.getInstance();
final email = prefs.getString('uf_saved_email') ?? '';
final pass = prefs.getString('uf_saved_pass') ?? '';
if (email.isNotEmpty && pass.isNotEmpty) {
context.read<AuthBloc>().add(AuthLoginRequested(email, pass));
}
context.read<AuthBloc>().add(const AuthStatusChecked());
}
} catch (_) {}
}
@@ -110,24 +85,8 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
} catch (_) {}
}
Future<void> _onLogin() async {
final email = _emailController.text.trim();
final password = _passwordController.text;
if (email.isEmpty || password.isEmpty) return;
if (_rememberMe) {
final prefs = await SharedPreferences.getInstance();
await prefs.setBool('uf_remember_me', true);
await prefs.setString('uf_saved_email', email);
await prefs.setString('uf_saved_pass', password);
} else {
final prefs = await SharedPreferences.getInstance();
await prefs.remove('uf_remember_me');
await prefs.remove('uf_saved_email');
await prefs.remove('uf_saved_pass');
}
if (mounted) context.read<AuthBloc>().add(AuthLoginRequested(email, password));
void _onLogin() {
context.read<AuthBloc>().add(const AuthLoginRequested());
}
@override
@@ -267,51 +226,27 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
),
const SizedBox(height: 12),
_GlassTextField(
controller: _emailController,
hint: 'Email ou identifiant',
icon: Icons.person_outline_rounded,
keyboardType: TextInputType.emailAddress,
),
const SizedBox(height: 8),
_GlassTextField(
controller: _passwordController,
hint: 'Mot de passe',
icon: Icons.lock_outline_rounded,
isPassword: true,
obscure: _obscurePassword,
onToggleObscure: () => setState(() => _obscurePassword = !_obscurePassword),
),
const SizedBox(height: 8),
// Remember me + Forgot password
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
_RememberMeToggle(
value: _rememberMe,
onChanged: (v) => setState(() => _rememberMe = v),
// Forgot password
Align(
alignment: Alignment.centerRight,
child: TextButton(
onPressed: _openForgotPassword,
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
TextButton(
onPressed: _openForgotPassword,
style: TextButton.styleFrom(
padding: EdgeInsets.zero,
minimumSize: Size.zero,
tapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
child: Text(
'Mot de passe oublié ?',
style: GoogleFonts.roboto(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.w600,
decoration: TextDecoration.underline,
decorationColor: Colors.white.withOpacity(0.7),
),
child: Text(
'Mot de passe oublié ?',
style: GoogleFonts.roboto(
fontSize: 12,
color: Colors.white,
fontWeight: FontWeight.w600,
decoration: TextDecoration.underline,
decorationColor: Colors.white.withOpacity(0.7),
),
),
],
),
),
const SizedBox(height: 16),
@@ -361,108 +296,6 @@ class _LoginPageState extends State<LoginPage> with TickerProviderStateMixin {
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Sous-composants privés
// ─────────────────────────────────────────────────────────────────────────────
class _GlassTextField extends StatelessWidget {
const _GlassTextField({
required this.controller,
required this.hint,
required this.icon,
this.keyboardType,
this.isPassword = false,
this.obscure = false,
this.onToggleObscure,
});
final TextEditingController controller;
final String hint;
final IconData icon;
final TextInputType? keyboardType;
final bool isPassword;
final bool obscure;
final VoidCallback? onToggleObscure;
@override
Widget build(BuildContext context) {
return Container(
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.13),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: Colors.white.withOpacity(0.28), width: 1),
),
child: TextField(
controller: controller,
obscureText: isPassword && obscure,
keyboardType: keyboardType,
style: GoogleFonts.roboto(fontSize: 15, color: Colors.white),
decoration: InputDecoration(
hintText: hint,
hintStyle: GoogleFonts.roboto(fontSize: 14.5, color: Colors.white.withOpacity(0.48)),
prefixIcon: Icon(icon, color: Colors.white54, size: 20),
suffixIcon: isPassword
? IconButton(
icon: Icon(
obscure ? Icons.visibility_outlined : Icons.visibility_off_outlined,
color: Colors.white54,
size: 20,
),
onPressed: onToggleObscure,
)
: null,
border: InputBorder.none,
contentPadding: const EdgeInsets.symmetric(vertical: 10, horizontal: 4),
),
),
);
}
}
class _RememberMeToggle extends StatelessWidget {
const _RememberMeToggle({required this.value, required this.onChanged});
final bool value;
final ValueChanged<bool> onChanged;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () => onChanged(!value),
behavior: HitTestBehavior.opaque,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
SizedBox(
width: 18,
height: 18,
child: Checkbox(
value: value,
onChanged: (v) => onChanged(v ?? false),
fillColor: WidgetStateProperty.resolveWith((s) {
if (s.contains(WidgetState.selected)) return Colors.white;
return Colors.transparent;
}),
checkColor: const Color(0xFF2E7D32),
side: const BorderSide(color: Colors.white60, width: 1.5),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(4)),
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
),
),
const SizedBox(width: 7),
Text(
'Se souvenir de moi',
style: GoogleFonts.roboto(
fontSize: 12,
color: Colors.white.withOpacity(0.78),
),
),
],
),
);
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Painters
// ─────────────────────────────────────────────────────────────────────────────

View File

@@ -50,20 +50,23 @@ class DashboardBloc extends Bloc<DashboardEvent, DashboardState> {
// Écouter les events WebSocket
_webSocketEventSubscription = webSocketService.eventStream.listen(
(event) {
AppLogger.info('DashboardBloc: Event WebSocket reçu - ${event.eventType}');
try {
AppLogger.info('DashboardBloc: Event WebSocket reçu - ${event.eventType}');
// Dispatcher uniquement les events pertinents au dashboard
if (event is DashboardStatsEvent) {
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is FinanceApprovalEvent) {
// Les approbations affectent les stats, rafraîchir
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is MemberEvent) {
// Les changements de membres affectent les stats
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is ContributionEvent) {
// Les cotisations affectent les stats financières
add(RefreshDashboardFromWebSocket(event.data));
if (isClosed) return;
// Dispatcher uniquement les events pertinents au dashboard
if (event is DashboardStatsEvent) {
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is FinanceApprovalEvent) {
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is MemberEvent) {
add(RefreshDashboardFromWebSocket(event.data));
} else if (event is ContributionEvent) {
add(RefreshDashboardFromWebSocket(event.data));
}
} catch (e, s) {
AppLogger.error('DashboardBloc: erreur lors du traitement WebSocket event', error: e);
}
},
onError: (error) {

View File

@@ -1,760 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:fl_chart/fl_chart.dart';
import '../../../../shared/design_system/unionflow_design_v2.dart';
import '../../../../shared/design_system/unionflow_design_system.dart';
import '../../../contributions/presentation/pages/contributions_page_wrapper.dart';
import '../../../epargne/presentation/pages/epargne_page.dart';
import '../../../events/presentation/pages/events_page_wrapper.dart';
import '../bloc/dashboard_bloc.dart';
import '../../domain/entities/dashboard_entity.dart';
/// Page dashboard connectée au backend - Design UnionFlow Animé
class ConnectedDashboardPage extends StatefulWidget {
final String organizationId;
final String userId;
const ConnectedDashboardPage({
super.key,
required this.organizationId,
required this.userId,
});
@override
State<ConnectedDashboardPage> createState() => _ConnectedDashboardPageState();
}
class _ConnectedDashboardPageState extends State<ConnectedDashboardPage> with SingleTickerProviderStateMixin {
late TabController _tabController;
PeriodFilter _selectedPeriod = PeriodFilter.month;
int _unreadNotifications = 5;
bool _isExporting = false;
@override
void initState() {
super.initState();
_tabController = TabController(length: 3, vsync: this);
context.read<DashboardBloc>().add(LoadDashboardData(
organizationId: widget.organizationId,
userId: widget.userId,
));
}
@override
void dispose() {
_tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.lightBackground,
appBar: _buildAppBar(),
body: AfricanPatternBackground(
child: BlocBuilder<DashboardBloc, DashboardState>(
builder: (context, state) {
if (state is DashboardLoading) {
return const Center(
child: CircularProgressIndicator(color: AppColors.primaryGreen),
);
}
if (state is DashboardMemberNotRegistered) {
return _buildMemberNotRegisteredState();
}
if (state is DashboardError) {
return _buildErrorState(state.message);
}
if (state is DashboardLoaded) {
return _buildDashboardContent(state);
}
return const SizedBox.shrink();
},
),
),
);
}
PreferredSizeWidget _buildAppBar() {
return AppBar(
backgroundColor: AppColors.lightSurface,
elevation: 0,
title: Row(
children: [
Hero(
tag: 'unionflow_logo',
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: const Text(
'U',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 18,
),
),
),
),
const SizedBox(width: 12),
const Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'UnionFlow',
style: TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppColors.textPrimaryLight,
),
),
Text(
'Dashboard',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
color: AppColors.textSecondaryLight,
),
),
],
),
],
),
automaticallyImplyLeading: false,
actions: [
UnionExportButton(
isLoading: _isExporting,
onExport: (exportType) {
showDialog(
context: context,
builder: (context) => ExportConfirmDialog(
exportType: exportType,
onConfirm: () => _handleExport(exportType),
),
);
},
),
const SizedBox(width: 8),
UnionNotificationBadge(
count: _unreadNotifications,
child: IconButton(
icon: const Icon(Icons.notifications_outlined),
color: AppColors.textPrimaryLight,
onPressed: () {
setState(() => _unreadNotifications = 0);
UnionNotificationToast.show(
context,
title: 'Notifications',
message: 'Aucune nouvelle notification',
icon: Icons.notifications_active,
color: UnionFlowColors.info,
);
},
),
),
const SizedBox(width: 8),
],
bottom: TabBar(
controller: _tabController,
labelColor: AppColors.primaryGreen,
unselectedLabelColor: AppColors.textSecondaryLight,
indicatorColor: AppColors.primaryGreen,
labelStyle: const TextStyle(fontSize: 13, fontWeight: FontWeight.w700),
tabs: const [
Tab(text: 'Vue d\'ensemble'),
Tab(text: 'Analytique'),
Tab(text: 'Activités'),
],
),
);
}
Widget _buildDashboardContent(DashboardLoaded state) {
final data = state.dashboardData;
return RefreshIndicator(
onRefresh: () async {
context.read<DashboardBloc>().add(LoadDashboardData(
organizationId: widget.organizationId,
userId: widget.userId,
));
},
color: AppColors.primaryGreen,
child: TabBarView(
controller: _tabController,
children: [
_buildOverviewTab(data),
_buildAnalyticsTab(data),
_buildActivitiesTab(data),
],
),
);
}
UnionTransactionTile _activityToTile(RecentActivityEntity a) {
final amount = a.metadata != null && a.metadata!['amount'] != null
? '${a.metadata!['amount']} FCFA'
: (a.title.isNotEmpty ? a.title : '-');
return UnionTransactionTile(
name: a.userName,
amount: amount,
status: a.type.isNotEmpty ? a.type : 'Confirmé',
date: a.timeAgo,
);
}
Widget _buildOverviewTab(DashboardEntity data) {
final stats = data.stats;
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Balance principale - Animée
AnimatedSlideIn(
delay: const Duration(milliseconds: 100),
child: UnionBalanceCard(
label: 'Caisse Totale',
amount: _formatAmount(stats.totalContributionAmount),
trend: stats.monthlyGrowth > 0 ? '+${(stats.monthlyGrowth * 100).toStringAsFixed(0)}% ce mois' : 'Stable',
isTrendPositive: true,
),
),
const SizedBox(height: 24),
// Stats en grille - Animées avec délai
AnimatedSlideIn(
delay: const Duration(milliseconds: 200),
child: Row(
children: [
Expanded(
child: UnionStatWidget(
label: 'Membres',
value: stats.totalMembers.toString(),
icon: Icons.people_outline,
color: AppColors.primaryGreen,
trend: '+8%',
isTrendUp: true,
),
),
const SizedBox(width: 12),
Expanded(
child: UnionStatWidget(
label: 'Actifs',
value: stats.activeMembers.toString(),
icon: Icons.check_circle_outline,
color: UnionFlowColors.success,
trend: '+5%',
isTrendUp: true,
),
),
],
),
),
const SizedBox(height: 12),
AnimatedSlideIn(
delay: const Duration(milliseconds: 300),
child: Row(
children: [
Expanded(
child: UnionStatWidget(
label: 'Événements',
value: stats.totalEvents.toString(),
icon: Icons.event_outlined,
color: UnionFlowColors.gold,
trend: '+3',
isTrendUp: true,
),
),
const SizedBox(width: 12),
Expanded(
child: UnionStatWidget(
label: 'À venir',
value: stats.upcomingEvents.toString(),
icon: Icons.calendar_today,
color: UnionFlowColors.amber,
),
),
],
),
),
const SizedBox(height: 12),
// Progression - Animée
AnimatedFadeIn(
delay: const Duration(milliseconds: 400),
child: UnionProgressCard(
title: 'Progression des Cotisations',
progress: 0.7,
subtitle: '70% des membres ont cotisé ce mois',
),
),
const SizedBox(height: 12),
// Actions rapides - Animées
AnimatedSlideIn(
delay: const Duration(milliseconds: 500),
begin: const Offset(0, 0.2),
child: UnionActionGrid(
actions: [
UnionActionButton(
icon: Icons.payment,
label: 'Cotiser',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper()),
);
},
backgroundColor: UnionFlowColors.unionGreenPale,
iconColor: AppColors.primaryGreen,
),
UnionActionButton(
icon: Icons.send,
label: 'Envoyer',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper()),
);
},
backgroundColor: UnionFlowColors.goldPale,
iconColor: UnionFlowColors.gold,
),
UnionActionButton(
icon: Icons.download,
label: 'Retirer',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const EpargnePage()),
);
},
backgroundColor: UnionFlowColors.terracottaPale,
iconColor: UnionFlowColors.terracotta,
),
UnionActionButton(
icon: Icons.add_circle_outline,
label: 'Créer',
onTap: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const EventsPageWrapper()),
);
},
backgroundColor: UnionFlowColors.infoPale,
iconColor: UnionFlowColors.info,
),
],
),
),
const SizedBox(height: 12),
// Activité récente - Animée
AnimatedFadeIn(
delay: const Duration(milliseconds: 600),
child: UnionTransactionCard(
title: 'Activité Récente',
onSeeAll: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper()),
);
},
transactions: data.recentActivities.take(6).map((a) => _activityToTile(a)).toList(),
),
),
],
),
);
}
Widget _buildAnalyticsTab(DashboardEntity data) {
final stats = data.stats;
final entrees = stats.totalContributionAmount;
final sorties = stats.pendingRequests * 1000.0;
final benefice = entrees - sorties;
final taux = (stats.engagementRate * 100).toStringAsFixed(0);
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Filtre de période - Animé
AnimatedFadeIn(
delay: const Duration(milliseconds: 50),
child: UnionPeriodFilter(
selectedPeriod: _selectedPeriod,
onPeriodChanged: (period) {
setState(() => _selectedPeriod = period);
UnionNotificationToast.show(
context,
title: 'Période mise à jour',
message: 'Affichage pour ${period.label.toLowerCase()}',
icon: Icons.calendar_today,
color: AppColors.primaryGreen,
);
},
),
),
const SizedBox(height: 24),
// Line Chart - Animé (évolution basée sur total cotisations + croissance)
AnimatedSlideIn(
delay: const Duration(milliseconds: 100),
child: UnionLineChart(
title: 'Évolution de la Caisse',
subtitle: 'Derniers 12 mois',
spots: _buildEvolutionSpots(stats.totalContributionAmount, stats.monthlyGrowth),
),
),
const SizedBox(height: 24),
// Pie Chart - Animé
AnimatedFadeIn(
delay: const Duration(milliseconds: 300),
child: UnionPieChart(
title: 'Répartition des Cotisations',
subtitle: 'Par catégorie',
sections: [
UnionPieChartSection.create(
value: 40,
color: AppColors.primaryGreen,
title: '40%\nCotisations',
),
UnionPieChartSection.create(
value: 30,
color: UnionFlowColors.gold,
title: '30%\nÉpargne',
),
UnionPieChartSection.create(
value: 20,
color: UnionFlowColors.terracotta,
title: '20%\nSolidarité',
),
UnionPieChartSection.create(
value: 10,
color: UnionFlowColors.amber,
title: '10%\nAutres',
),
],
),
),
const SizedBox(height: 12),
// Titre
AnimatedFadeIn(
delay: const Duration(milliseconds: 400),
child: const Text(
'Métriques Financières',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: AppColors.textPrimaryLight,
),
),
),
const SizedBox(height: 8),
// Métriques - Animées (données backend)
AnimatedSlideIn(
delay: const Duration(milliseconds: 500),
begin: const Offset(0, 0.2),
child: Column(
children: [
Row(
children: [
Expanded(
child: _buildFinanceMetric(
'Entrées',
_formatFcfa(entrees),
Icons.arrow_downward,
UnionFlowColors.success,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildFinanceMetric(
'Sorties',
_formatFcfa(sorties),
Icons.arrow_upward,
UnionFlowColors.error,
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
Expanded(
child: _buildFinanceMetric(
'Bénéfice',
_formatFcfa(benefice),
Icons.trending_up,
UnionFlowColors.gold,
),
),
const SizedBox(width: 12),
Expanded(
child: _buildFinanceMetric(
'Taux',
'$taux%',
Icons.percent,
UnionFlowColors.info,
),
),
],
),
],
),
),
],
),
);
}
Widget _buildActivitiesTab(DashboardEntity data) {
final tiles = data.recentActivities.map((a) => _activityToTile(a)).toList();
return SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
AnimatedSlideIn(
delay: const Duration(milliseconds: 100),
child: UnionTransactionCard(
title: 'Toutes les Activités',
onSeeAll: () {
Navigator.of(context).push(
MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper()),
);
},
transactions: tiles,
),
),
],
),
);
}
Future<void> _handleExport(ExportType exportType) async {
setState(() => _isExporting = true);
// Simulation de l'export (dans un vrai cas, appel API ici)
await Future.delayed(const Duration(seconds: 2));
setState(() => _isExporting = false);
if (mounted) {
UnionNotificationToast.show(
context,
title: 'Export réussi',
message: 'Le rapport ${exportType.label} a été généré avec succès',
icon: Icons.check_circle,
color: UnionFlowColors.success,
);
}
}
String _formatFcfa(double value) {
if (value >= 1000000) return '${(value / 1000000).toStringAsFixed(1)}M FCFA';
if (value >= 1000) return '${(value / 1000).toStringAsFixed(0)}K FCFA';
return '${value.toStringAsFixed(0)} FCFA';
}
List<FlSpot> _buildEvolutionSpots(double totalAmount, double monthlyGrowth) {
final spots = <FlSpot>[];
var v = totalAmount * 0.5;
for (var i = 0; i < 12; i++) {
spots.add(FlSpot(i.toDouble(), v));
v = v * (1 + (monthlyGrowth > 0 ? monthlyGrowth : 0.02));
}
if (spots.isNotEmpty) spots[spots.length - 1] = FlSpot(11, totalAmount);
return spots;
}
Widget _buildFinanceMetric(String label, String value, IconData icon, Color color) {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: AppColors.lightSurface,
borderRadius: BorderRadius.circular(10),
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, size: 16, color: color),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: AppColors.textSecondaryLight,
),
),
const SizedBox(height: 4),
Text(
value,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: color,
),
),
],
),
),
],
),
);
}
Widget _buildMemberNotRegisteredState() {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
shape: BoxShape.circle,
),
child: const Icon(
Icons.person_add_alt_1_outlined,
size: 36,
color: Colors.white,
),
),
const SizedBox(height: 14),
const Text(
'Bienvenue dans UnionFlow',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: AppColors.textPrimaryLight,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
const Text(
'Votre compte est en cours de configuration par un administrateur. '
'Votre tableau de bord sera disponible dès que votre profil membre aura été activé.',
style: TextStyle(
fontSize: 12,
color: AppColors.textSecondaryLight,
height: 1.5,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 16),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: AppColors.primaryGreen.withOpacity(0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: AppColors.primaryGreen.withOpacity(0.3)),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.info_outline, size: 18, color: AppColors.primaryGreen),
SizedBox(width: 10),
Flexible(
child: Text(
'Contactez votre administrateur si ce message persiste.',
style: TextStyle(
fontSize: 13,
color: AppColors.primaryGreen,
fontWeight: FontWeight.w500,
),
),
),
],
),
),
],
),
),
);
}
Widget _buildErrorState(String message) {
return Center(
child: AnimatedFadeIn(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: UnionFlowColors.errorPale,
shape: BoxShape.circle,
),
child: const Icon(
Icons.error_outline,
size: 40,
color: UnionFlowColors.error,
),
),
const SizedBox(height: 12),
const Text(
'Erreur de chargement',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: AppColors.textPrimaryLight,
),
),
const SizedBox(height: 8),
Text(
message,
style: const TextStyle(
fontSize: 13,
color: AppColors.textSecondaryLight,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 24),
UFPrimaryButton(
onPressed: () {
context.read<DashboardBloc>().add(LoadDashboardData(
organizationId: widget.organizationId,
userId: widget.userId,
));
},
label: 'RÉESSAYER',
),
],
),
),
);
}
String _formatAmount(num amount) {
return '${amount.toStringAsFixed(0).replaceAllMapped(
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
(Match m) => '${m[1]},',
)} FCFA';
}
}

View File

@@ -2,270 +2,210 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../../shared/design_system/unionflow_design_v2.dart';
import '../../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../widgets/dashboard_drawer.dart';
/// Dashboard Visiteur - Design UnionFlow Version Publique
/// Dashboard affiché pour un compte authentifié sans rôle métier actif.
/// Cas typique : nouveau membre créé par un administrateur, en attente d'activation.
class VisitorDashboard extends StatelessWidget {
const VisitorDashboard({super.key});
@override
Widget build(BuildContext context) {
final authState = context.watch<AuthBloc>().state;
final email = authState is AuthAuthenticated ? authState.user.email : '';
final firstName = authState is AuthAuthenticated ? authState.user.firstName : '';
return Scaffold(
backgroundColor: UnionFlowColors.background,
appBar: _buildAppBar(),
drawer: DashboardDrawer(
onNavigate: (route) {
Navigator.of(context).pushNamed(route);
},
onLogout: () {
context.read<AuthBloc>().add(const AuthLogoutRequested());
},
),
body: AfricanPatternBackground(
child: SingleChildScrollView(
padding: const EdgeInsets.all(12),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Message de bienvenue
AnimatedFadeIn(
delay: const Duration(milliseconds: 100),
child: _buildWelcomeCard(),
),
const SizedBox(height: 12),
appBar: _buildAppBar(context),
body: SingleChildScrollView(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 24),
// Fonctionnalités UnionFlow
AnimatedSlideIn(
delay: const Duration(milliseconds: 200),
child: const Text(
'Découvrez UnionFlow',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
// Icône centrale
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: UnionFlowColors.gold.withOpacity(0.12),
shape: BoxShape.circle,
),
child: const Icon(
Icons.hourglass_empty_rounded,
size: 40,
color: UnionFlowColors.gold,
),
),
const SizedBox(height: 20),
// Titre
Text(
firstName.isNotEmpty ? 'Bonjour $firstName,' : 'Bienvenue,',
style: const TextStyle(
fontSize: 20,
fontWeight: FontWeight.w800,
color: UnionFlowColors.textPrimary,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
const Text(
'Votre compte est en attente d\'activation',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: UnionFlowColors.textPrimary,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
// Email
if (email.isNotEmpty)
Container(
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: UnionFlowColors.border),
),
),
const SizedBox(height: 8),
AnimatedFadeIn(
delay: const Duration(milliseconds: 300),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Expanded(
child: UnionStatWidget(
label: 'Organisations',
value: '500+',
icon: Icons.business_outlined,
color: UnionFlowColors.unionGreen,
),
),
const SizedBox(width: 12),
Expanded(
child: UnionStatWidget(
label: 'Utilisateurs',
value: '10K+',
icon: Icons.people_outlined,
color: UnionFlowColors.gold,
const Icon(Icons.email_outlined, size: 14, color: UnionFlowColors.textSecondary),
const SizedBox(width: 6),
Text(
email,
style: const TextStyle(
fontSize: 13,
color: UnionFlowColors.textSecondary,
),
),
],
),
),
const SizedBox(height: 12),
const SizedBox(height: 28),
AnimatedFadeIn(
delay: const Duration(milliseconds: 400),
child: Row(
children: [
Expanded(
child: UnionStatWidget(
label: 'Transactions',
value: '1M+',
icon: Icons.payment_outlined,
color: UnionFlowColors.indigo,
),
// Message explicatif
Container(
width: double.infinity,
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(12),
border: const Border(
left: BorderSide(color: UnionFlowColors.gold, width: 3),
),
boxShadow: UnionFlowColors.softShadow,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Que se passe-t-il ?',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
const SizedBox(width: 12),
Expanded(
child: UnionStatWidget(
label: 'Confiance',
value: '99%',
icon: Icons.verified_outlined,
color: UnionFlowColors.success,
),
),
],
),
),
const SizedBox(height: 12),
// Avantages
AnimatedSlideIn(
delay: const Duration(milliseconds: 500),
child: const Text(
'Nos Avantages',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
),
),
const SizedBox(height: 8),
AnimatedFadeIn(
delay: const Duration(milliseconds: 600),
child: _buildFeature(
'Gestion Simplifiée',
'Gérez vos cotisations, épargnes et crédits en un seul endroit',
Icons.dashboard_customize,
UnionFlowColors.unionGreen,
),
),
const SizedBox(height: 12),
AnimatedFadeIn(
delay: const Duration(milliseconds: 700),
child: _buildFeature(
'Sécurité Optimale',
'Vos données sont protégées avec un chiffrement de niveau bancaire',
Icons.security,
UnionFlowColors.indigo,
),
),
const SizedBox(height: 12),
AnimatedFadeIn(
delay: const Duration(milliseconds: 800),
child: _buildFeature(
'Solidarité Africaine',
'Entraide, tontines, mutuelles et coopératives à votre portée',
Icons.favorite_outline,
UnionFlowColors.terracotta,
),
),
const SizedBox(height: 12),
AnimatedFadeIn(
delay: const Duration(milliseconds: 900),
child: _buildFeature(
'Rapports Détaillés',
'Suivi en temps réel avec exports PDF, Excel et CSV',
Icons.analytics_outlined,
UnionFlowColors.gold,
),
),
const SizedBox(height: 16),
// Call to Action
AnimatedSlideIn(
delay: const Duration(milliseconds: 1000),
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(12),
const SizedBox(height: 8),
_buildStep(
'1',
'Votre compte a été créé par l\'administrateur de votre organisation.',
UnionFlowColors.unionGreen,
),
child: Column(
children: [
const Icon(
Icons.rocket_launch,
size: 24,
color: Colors.white,
),
const SizedBox(height: 8),
const Text(
'Prêt à Commencer ?',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w800,
color: Colors.white,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 4),
Text(
'Rejoignez des milliers d\'organisations qui nous font confiance',
style: TextStyle(
fontSize: 11,
color: Colors.white.withOpacity(0.9),
),
textAlign: TextAlign.center,
),
const SizedBox(height: 10),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () {
Navigator.of(context).pushNamed('/login');
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.white,
foregroundColor: UnionFlowColors.unionGreen,
padding: const EdgeInsets.symmetric(vertical: 10),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
),
elevation: 0,
),
child: const Text(
'Créer un Compte',
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w800,
),
),
),
),
const SizedBox(height: 6),
TextButton(
onPressed: () {
Navigator.of(context).pushNamed('/login');
},
child: Text(
'Déjà membre ? Se connecter',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: Colors.white.withOpacity(0.9),
),
),
),
],
const SizedBox(height: 8),
_buildStep(
'2',
'Il doit être activé par un administrateur avant que vous puissiez accéder à la plateforme.',
UnionFlowColors.gold,
),
const SizedBox(height: 8),
_buildStep(
'3',
'Une fois activé, reconnectez-vous pour accéder à votre espace.',
UnionFlowColors.indigo,
),
],
),
),
const SizedBox(height: 20),
// Bouton actualiser
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
context.read<AuthBloc>().add(const AuthStatusChecked());
},
icon: const Icon(Icons.refresh_rounded, size: 18),
label: const Text(
'Vérifier l\'état de mon compte',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
elevation: 0,
),
),
],
),
),
const SizedBox(height: 12),
// Bouton déconnexion
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
context.read<AuthBloc>().add(const AuthLogoutRequested());
},
icon: const Icon(Icons.logout_rounded, size: 18),
label: const Text(
'Se déconnecter',
style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600),
),
style: OutlinedButton.styleFrom(
foregroundColor: UnionFlowColors.textSecondary,
side: const BorderSide(color: UnionFlowColors.border),
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
),
const SizedBox(height: 32),
],
),
),
);
}
PreferredSizeWidget _buildAppBar() {
PreferredSizeWidget _buildAppBar(BuildContext context) {
return AppBar(
backgroundColor: UnionFlowColors.surface,
elevation: 0,
automaticallyImplyLeading: false,
title: Row(
children: [
Hero(
tag: 'unionflow_logo',
child: Container(
width: 32,
height: 32,
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: const Text(
'U',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 18,
),
Container(
width: 32,
height: 32,
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(8),
),
alignment: Alignment.center,
child: const Text(
'U',
style: TextStyle(
color: Colors.white,
fontWeight: FontWeight.w900,
fontSize: 18,
),
),
),
@@ -282,7 +222,7 @@ class VisitorDashboard extends StatelessWidget {
),
),
Text(
'Découverte',
'Compte en attente',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w400,
@@ -297,120 +237,39 @@ class VisitorDashboard extends StatelessWidget {
);
}
Widget _buildWelcomeCard() {
return Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
gradient: UnionFlowColors.subtleGradient,
borderRadius: BorderRadius.circular(10),
border: const Border(
top: BorderSide(color: UnionFlowColors.unionGreen, width: 3),
),
boxShadow: UnionFlowColors.mediumShadow,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(8),
),
child: const Icon(
Icons.waving_hand,
color: Colors.white,
size: 16,
),
),
const SizedBox(width: 16),
const Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Bienvenue sur UnionFlow',
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w800,
color: UnionFlowColors.textPrimary,
),
),
SizedBox(height: 4),
Text(
'Votre plateforme de gestion mutualiste et associative',
style: TextStyle(
fontSize: 11,
color: UnionFlowColors.textSecondary,
),
),
],
),
),
],
Widget _buildStep(String number, String text, Color color) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Container(
width: 22,
height: 22,
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
),
const SizedBox(height: 8),
Text(
'Gérez vos mutuelles, tontines, coopératives et associations en toute simplicité. UnionFlow est la solution complète pour la solidarité africaine.',
style: TextStyle(
alignment: Alignment.center,
child: Text(
number,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w800,
color: Colors.white,
),
),
),
const SizedBox(width: 10),
Expanded(
child: Text(
text,
style: const TextStyle(
fontSize: 12,
height: 1.5,
color: UnionFlowColors.textPrimary.withOpacity(0.8),
color: UnionFlowColors.textSecondary,
),
),
],
),
);
}
Widget _buildFeature(String title, String description, IconData icon, Color color) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(8),
border: Border(
left: BorderSide(color: color, width: 3),
),
),
child: Row(
children: [
Container(
padding: const EdgeInsets.all(7),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: color, size: 15),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
),
const SizedBox(height: 4),
Text(
description,
style: const TextStyle(
fontSize: 12,
color: UnionFlowColors.textSecondary,
),
),
],
),
),
],
),
],
);
}
}

View File

@@ -1,416 +0,0 @@
import 'package:flutter/material.dart';
import '../../../../../shared/design_system/unionflow_design_system.dart';
import '../../pages/connected_dashboard_page.dart';
import '../../pages/advanced_dashboard_page.dart';
import '../../../../settings/presentation/pages/language_settings_page.dart';
import '../../../../settings/presentation/pages/system_settings_page.dart';
import '../../../../reports/presentation/pages/reports_page_wrapper.dart';
import '../../../../members/presentation/pages/members_page_wrapper.dart';
import '../../../../events/presentation/pages/events_page_wrapper.dart';
import '../../../../contributions/presentation/pages/contributions_page_wrapper.dart';
/// Widget de navigation pour les différents types de dashboard
class DashboardNavigation extends StatefulWidget {
final String organizationId;
final String userId;
const DashboardNavigation({
super.key,
required this.organizationId,
required this.userId,
});
@override
State<DashboardNavigation> createState() => _DashboardNavigationState();
}
class _DashboardNavigationState extends State<DashboardNavigation> {
int _currentIndex = 0;
final List<DashboardTab> _tabs = [
const DashboardTab(
title: 'Accueil',
icon: Icons.home,
activeIcon: Icons.home,
type: DashboardType.home,
),
const DashboardTab(
title: 'Analytics',
icon: Icons.analytics_outlined,
activeIcon: Icons.analytics,
type: DashboardType.analytics,
),
const DashboardTab(
title: 'Rapports',
icon: Icons.assessment_outlined,
activeIcon: Icons.assessment,
type: DashboardType.reports,
),
const DashboardTab(
title: 'Paramètres',
icon: Icons.settings_outlined,
activeIcon: Icons.settings,
type: DashboardType.settings,
),
];
@override
Widget build(BuildContext context) {
return Scaffold(
body: _buildCurrentPage(),
bottomNavigationBar: _buildBottomNavigationBar(),
floatingActionButton: _buildFloatingActionButton(),
floatingActionButtonLocation: FloatingActionButtonLocation.centerDocked,
);
}
Widget _buildCurrentPage() {
switch (_tabs[_currentIndex].type) {
case DashboardType.home:
return ConnectedDashboardPage(
organizationId: widget.organizationId,
userId: widget.userId,
);
case DashboardType.analytics:
return AdvancedDashboardPage(
organizationId: widget.organizationId,
userId: widget.userId,
);
case DashboardType.reports:
return _buildReportsPage();
case DashboardType.settings:
return _buildSettingsPage();
}
}
Widget _buildBottomNavigationBar() {
return Container(
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.05),
blurRadius: 10,
offset: const Offset(0, -2),
),
],
),
child: BottomAppBar(
shape: const CircularNotchedRectangle(),
notchMargin: 8,
color: Theme.of(context).cardColor,
elevation: 0,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: _tabs.asMap().entries.map((entry) {
final index = entry.key;
final tab = entry.value;
final isActive = index == _currentIndex;
// Skip the middle item for FAB space
if (index == 2) {
return const SizedBox(width: 40);
}
return _buildNavItem(tab, isActive, index);
}).toList(),
),
),
),
);
}
Widget _buildNavItem(DashboardTab tab, bool isActive, int index) {
return GestureDetector(
onTap: () => setState(() => _currentIndex = index),
child: Container(
padding: const EdgeInsets.symmetric(
vertical: 8,
horizontal: 16,
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
isActive ? tab.activeIcon : tab.icon,
color: isActive ? AppColors.primaryGreen : AppColors.textSecondaryLight,
size: 20,
),
const SizedBox(height: 4),
Text(
tab.title,
style: AppTypography.badgeText.copyWith(
color: isActive ? AppColors.primaryGreen : AppColors.textSecondaryLight,
fontWeight: isActive ? FontWeight.bold : FontWeight.normal,
fontSize: 9,
),
),
],
),
),
);
}
Widget _buildFloatingActionButton() {
return FloatingActionButton(
onPressed: _showQuickActions,
backgroundColor: AppColors.primaryGreen,
elevation: 4,
child: const Icon(
Icons.add_outlined,
color: Colors.white,
size: 28,
),
);
}
Widget _buildReportsPage() {
return Scaffold(
appBar: AppBar(
title: Text('Rapports'.toUpperCase(), style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, color: Colors.white, letterSpacing: 1.1)),
backgroundColor: AppColors.primaryGreen,
foregroundColor: Colors.white,
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(
Icons.assessment_outlined,
size: 48,
color: AppColors.textSecondaryLight,
),
const SizedBox(height: 16),
Text(
'Page Rapports'.toUpperCase(),
style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
'En cours de développement',
style: AppTypography.bodyTextSmall.copyWith(
color: AppColors.textSecondaryLight,
),
),
],
),
),
);
}
Widget _buildSettingsPage() {
return Scaffold(
appBar: AppBar(
title: Text('Paramètres'.toUpperCase(), style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, color: Colors.white, letterSpacing: 1.1)),
backgroundColor: AppColors.primaryGreen,
foregroundColor: Colors.white,
automaticallyImplyLeading: false,
),
body: ListView(
padding: const EdgeInsets.all(16),
children: [
_buildSettingsSection(
'Apparence',
[
_buildSettingsTile(
'Thème',
'Design System UnionFlow',
Icons.palette_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())),
),
_buildSettingsTile(
'Langue',
'Français',
Icons.language_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const LanguageSettingsPage())),
),
],
),
const SizedBox(height: 24),
_buildSettingsSection(
'Notifications',
[
_buildSettingsTile(
'Notifications push',
'Activées',
Icons.notifications_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())),
),
_buildSettingsTile(
'Emails',
'Quotidien',
Icons.email_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())),
),
],
),
const SizedBox(height: 24),
_buildSettingsSection(
'Données',
[
_buildSettingsTile(
'Synchronisation',
'Automatique',
Icons.sync_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())),
),
_buildSettingsTile(
'Cache',
'Vider le cache',
Icons.storage_outlined,
() => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage())),
),
],
),
],
),
);
}
Widget _buildSettingsSection(String title, List<Widget> children) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title.toUpperCase(),
style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, color: AppColors.primaryGreen, fontSize: 10),
),
const SizedBox(height: 12),
Container(
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: AppColors.lightBorder),
),
child: Column(children: children),
),
],
);
}
Widget _buildSettingsTile(
String title,
String subtitle,
IconData icon,
VoidCallback onTap,
) {
return ListTile(
leading: Icon(icon, color: AppColors.primaryGreen, size: 20),
title: Text(title, style: AppTypography.actionText.copyWith(fontSize: 13)),
subtitle: Text(subtitle, style: AppTypography.subtitleSmall.copyWith(fontSize: 10)),
trailing: const Icon(
Icons.chevron_right_outlined,
color: AppColors.textSecondaryLight,
size: 16,
),
onTap: onTap,
);
}
void _showQuickActions() {
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) => Container(
decoration: BoxDecoration(
color: Theme.of(context).cardColor,
borderRadius: const BorderRadius.only(
topLeft: Radius.circular(16),
topRight: Radius.circular(16),
),
),
padding: const EdgeInsets.all(20),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 40,
height: 4,
decoration: BoxDecoration(
color: AppColors.lightBorder,
borderRadius: BorderRadius.circular(2),
),
),
const SizedBox(height: 20),
Text(
'ACTIONS RAPIDES',
style: AppTypography.subtitleSmall.copyWith(fontWeight: FontWeight.bold, letterSpacing: 1.1),
),
const SizedBox(height: 20),
GridView.count(
crossAxisCount: 3,
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
crossAxisSpacing: 12,
mainAxisSpacing: 12,
children: [
_buildQuickActionItem(context, 'Nouveau\nMembre', Icons.person_add_outlined, AppColors.success, () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const MembersPageWrapper()))),
_buildQuickActionItem(context, 'Créer\nÉvénement', Icons.event_available_outlined, AppColors.primaryGreen, () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const EventsPageWrapper()))),
_buildQuickActionItem(context, 'Ajouter\nContribution', Icons.account_balance_wallet_outlined, AppColors.brandGreen, () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ContributionsPageWrapper()))),
_buildQuickActionItem(context, 'Générer\nRapport', Icons.assessment_outlined, AppColors.info, () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const ReportsPageWrapper()))),
_buildQuickActionItem(context, 'Paramètres', Icons.settings_outlined, AppColors.textSecondaryLight, () => Navigator.of(context).push(MaterialPageRoute<void>(builder: (_) => const SystemSettingsPage()))),
],
),
const SizedBox(height: 20),
],
),
),
);
}
Widget _buildQuickActionItem(BuildContext context, String title, IconData icon, Color color, VoidCallback onNavigate) {
return GestureDetector(
onTap: () {
Navigator.pop(context);
onNavigate();
},
child: Container(
decoration: BoxDecoration(
color: color.withOpacity(0.1),
borderRadius: BorderRadius.circular(12),
),
padding: const EdgeInsets.all(12),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(icon, color: color, size: 20),
const SizedBox(height: 8),
Text(
title,
style: AppTypography.subtitleSmall.copyWith(
color: AppColors.textPrimaryLight,
fontSize: 9,
fontWeight: FontWeight.w500,
),
textAlign: TextAlign.center,
),
],
),
),
);
}
}
class DashboardTab {
final String title;
final IconData icon;
final IconData activeIcon;
final DashboardType type;
const DashboardTab({
required this.title,
required this.icon,
required this.activeIcon,
required this.type,
});
}
enum DashboardType {
home,
analytics,
reports,
settings,
}

View File

@@ -81,12 +81,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
totalPages: result.totalPages,
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -115,12 +110,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
));
}
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -151,11 +141,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
code: '400',
));
} else {
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
}
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
@@ -187,11 +173,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
code: '400',
));
} else {
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
}
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
@@ -214,12 +196,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
emit(EvenementDeleted(event.id));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -250,12 +227,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
totalPages: result.totalPages,
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -286,12 +258,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
totalPages: result.totalPages,
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -322,12 +289,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
totalPages: result.totalPages,
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -349,12 +311,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
emit(EvenementInscrit(event.evenementId));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -376,12 +333,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
emit(EvenementDesinscrit(event.evenementId));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -406,12 +358,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
participants: participants,
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -433,12 +380,7 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
emit(EvenementsStatsLoaded(stats));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
_emitDioError(e, emit);
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(EvenementsError(
@@ -493,5 +435,24 @@ class EvenementsBloc extends Bloc<EvenementsEvent, EvenementsState> {
return 'Erreur réseau inattendue.';
}
}
/// Émet le bon état selon le type d'erreur :
/// 401/403 → EvenementsError (autorisation), autres → EvenementsNetworkError (réseau).
void _emitDioError(DioException e, Emitter<EvenementsState> emit) {
if (e.type == DioExceptionType.cancel) return;
final statusCode = e.response?.statusCode;
if (statusCode == 401 || statusCode == 403) {
emit(EvenementsError(
message: _getNetworkErrorMessage(e),
error: e,
));
} else {
emit(EvenementsNetworkError(
message: _getNetworkErrorMessage(e),
code: statusCode?.toString(),
error: e,
));
}
}
}

View File

@@ -1,6 +1,7 @@
/// BLoC pour la gestion des membres
library membres_bloc;
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
@@ -16,6 +17,8 @@ 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';
import '../../../core/websocket/websocket_service.dart';
import '../../../core/utils/logger.dart';
/// BLoC pour la gestion des membres (Clean Architecture)
@injectable
@@ -27,7 +30,10 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
final uc.DeleteMember _deleteMember;
final SearchMembers _searchMembers;
final GetMemberStats _getMemberStats;
final IMembreRepository _repository; // Pour méthodes non-couvertes par use cases
final IMembreRepository _repository;
final WebSocketService _webSocketService;
StreamSubscription<WebSocketEvent>? _webSocketSubscription;
MembresBloc(
this._getMembers,
@@ -38,6 +44,7 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
this._searchMembers,
this._getMemberStats,
this._repository,
this._webSocketService,
) : super(const MembresInitial()) {
on<LoadMembres>(_onLoadMembres);
on<LoadMembreById>(_onLoadMembreById);
@@ -50,6 +57,44 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
on<LoadActiveMembres>(_onLoadActiveMembres);
on<LoadBureauMembres>(_onLoadBureauMembres);
on<LoadMembresStats>(_onLoadMembresStats);
on<ResetMotDePasse>(_onResetMotDePasse);
on<AffecterOrganisation>(_onAffecterOrganisation);
on<InviterMembre>(_onInviterMembre);
on<ActiverAdhesion>(_onActiverAdhesion);
on<SuspendrAdhesion>(_onSuspendrAdhesion);
on<RadierAdhesion>(_onRadierAdhesion);
_initWebSocketListener();
}
void _initWebSocketListener() {
_webSocketSubscription = _webSocketService.eventStream.listen(
(event) {
try {
if (event is MemberEvent) {
AppLogger.info('MembresBloc: MemberEvent reçu (${event.eventType}), refresh liste');
final currentState = state;
if (currentState is MembresLoaded && !isClosed) {
add(LoadMembres(
refresh: true,
organisationId: currentState.organisationId,
page: currentState.currentPage,
size: currentState.pageSize,
));
}
}
} catch (e, s) {
AppLogger.error('MembresBloc: erreur lors du traitement WebSocket event', error: e);
}
},
onError: (error) => AppLogger.error('MembresBloc: WebSocket stream error', error: error),
);
}
@override
Future<void> close() {
_webSocketSubscription?.cancel();
return super.close();
}
/// Charge la liste des membres
@@ -68,11 +113,14 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
final MembreSearchResult result;
if (event.organisationId != null) {
// OrgAdmin : scope la requête à son organisation via la recherche avancée
// OrgAdmin : scope la requête à son organisation via la recherche avancée.
// includeInactifs=true pour récupérer aussi les membres "En attente"
// (actif=false) — le filtrage par statut est géré côté UI.
result = await _searchMembers(
criteria: MembreSearchCriteria(
organisationIds: [event.organisationId!],
query: event.recherche?.isNotEmpty == true ? event.recherche : null,
includeInactifs: true,
),
page: event.page,
size: event.size,
@@ -298,6 +346,60 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
}
}
/// Réinitialise le mot de passe d'un membre
Future<void> _onResetMotDePasse(
ResetMotDePasse event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final membre = await _repository.resetMotDePasse(event.id);
emit(MotDePasseReinitialise(membre));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(MembresError(
message: 'Erreur lors de la réinitialisation du mot de passe. Veuillez réessayer.',
error: e,
));
}
}
/// Affecte un membre à une organisation (superadmin)
Future<void> _onAffecterOrganisation(
AffecterOrganisation event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final membre = await _repository.affecterOrganisation(event.membreId, event.organisationId);
emit(MembreAffecte(membre));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
if (e is DioException && e.type == DioExceptionType.cancel) return;
emit(MembresError(
message: 'Erreur lors de l\'affectation à l\'organisation. Veuillez réessayer.',
error: e,
));
}
}
/// Recherche avancée de membres
Future<void> _onSearchMembres(
SearchMembres event,
@@ -479,5 +581,116 @@ class MembresBloc extends Bloc<MembresEvent, MembresState> {
return 'Erreur réseau inattendue.';
}
}
// ── Handlers cycle de vie des adhésions ──────────────────────────────────
Future<void> _onInviterMembre(
InviterMembre event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final result = await _repository.inviterMembre(
event.membreId,
event.organisationId,
roleOrg: event.roleOrg,
);
emit(MembreInvite(
membreId: event.membreId,
organisationId: event.organisationId,
nouveauStatut: result['statut']?.toString() ?? 'INVITE',
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
emit(MembresError(message: 'Erreur lors de l\'invitation du membre.', error: e));
}
}
Future<void> _onActiverAdhesion(
ActiverAdhesion event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final result = await _repository.activerAdhesion(
event.membreId,
event.organisationId,
motif: event.motif,
);
emit(AdhesionActivee(
membreId: event.membreId,
nouveauStatut: result['statut']?.toString() ?? 'ACTIF',
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
emit(MembresError(message: 'Erreur lors de l\'activation de l\'adhésion.', error: e));
}
}
Future<void> _onSuspendrAdhesion(
SuspendrAdhesion event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final result = await _repository.suspendrAdhesion(
event.membreId,
event.organisationId,
motif: event.motif,
);
emit(AdhesionSuspendue(
membreId: event.membreId,
nouveauStatut: result['statut']?.toString() ?? 'SUSPENDU',
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
emit(MembresError(message: 'Erreur lors de la suspension de l\'adhésion.', error: e));
}
}
Future<void> _onRadierAdhesion(
RadierAdhesion event,
Emitter<MembresState> emit,
) async {
try {
emit(const MembresLoading());
final result = await _repository.radierAdhesion(
event.membreId,
event.organisationId,
motif: event.motif,
);
emit(MembreRadie(
membreId: event.membreId,
nouveauStatut: result['statut']?.toString() ?? 'RADIE',
));
} on DioException catch (e) {
if (e.type == DioExceptionType.cancel) return;
emit(MembresNetworkError(
message: _getNetworkErrorMessage(e),
code: e.response?.statusCode.toString(),
error: e,
));
} catch (e) {
emit(MembresError(message: 'Erreur lors de la radiation du membre.', error: e));
}
}
}

View File

@@ -143,3 +143,90 @@ class LoadMembresStats extends MembresEvent {
const LoadMembresStats();
}
/// Événement pour réinitialiser le mot de passe d'un membre existant
class ResetMotDePasse extends MembresEvent {
final String id;
const ResetMotDePasse(this.id);
@override
List<Object?> get props => [id];
}
/// Événement pour affecter un membre à une organisation (superadmin)
class AffecterOrganisation extends MembresEvent {
final String membreId;
final String organisationId;
const AffecterOrganisation(this.membreId, this.organisationId);
@override
List<Object?> get props => [membreId, organisationId];
}
// ── Cycle de vie des adhésions ────────────────────────────────────────────
/// Inviter un membre dans une organisation (admin)
class InviterMembre extends MembresEvent {
final String membreId;
final String organisationId;
final String? roleOrg;
const InviterMembre({
required this.membreId,
required this.organisationId,
this.roleOrg,
});
@override
List<Object?> get props => [membreId, organisationId, roleOrg];
}
/// Activer l'adhésion d'un membre dans l'organisation courante
class ActiverAdhesion extends MembresEvent {
final String membreId;
final String organisationId;
final String? motif;
const ActiverAdhesion({
required this.membreId,
required this.organisationId,
this.motif,
});
@override
List<Object?> get props => [membreId, organisationId, motif];
}
/// Suspendre l'adhésion d'un membre
class SuspendrAdhesion extends MembresEvent {
final String membreId;
final String organisationId;
final String? motif;
const SuspendrAdhesion({
required this.membreId,
required this.organisationId,
this.motif,
});
@override
List<Object?> get props => [membreId, organisationId, motif];
}
/// Radier un membre d'une organisation
class RadierAdhesion extends MembresEvent {
final String membreId;
final String organisationId;
final String? motif;
const RadierAdhesion({
required this.membreId,
required this.organisationId,
this.motif,
});
@override
List<Object?> get props => [membreId, organisationId, motif];
}

View File

@@ -141,6 +141,78 @@ class MembreDeactivated extends MembresState {
List<Object?> get props => [membre];
}
/// État de succès après affectation à une organisation
class MembreAffecte extends MembresState {
final MembreCompletModel membre;
const MembreAffecte(this.membre);
@override
List<Object?> get props => [membre];
}
/// État de succès après réinitialisation du mot de passe
/// [membre] contient motDePasseTemporaire renseigné (retourné une seule fois)
class MotDePasseReinitialise extends MembresState {
final MembreCompletModel membre;
const MotDePasseReinitialise(this.membre);
@override
List<Object?> get props => [membre];
}
// ── États cycle de vie adhésion ──────────────────────────────────────────
/// Invitation envoyée avec succès
class MembreInvite extends MembresState {
final String membreId;
final String organisationId;
final String nouveauStatut;
const MembreInvite({
required this.membreId,
required this.organisationId,
required this.nouveauStatut,
});
@override
List<Object?> get props => [membreId, organisationId, nouveauStatut];
}
/// Adhésion activée
class AdhesionActivee extends MembresState {
final String membreId;
final String nouveauStatut;
const AdhesionActivee({required this.membreId, required this.nouveauStatut});
@override
List<Object?> get props => [membreId, nouveauStatut];
}
/// Adhésion suspendue
class AdhesionSuspendue extends MembresState {
final String membreId;
final String nouveauStatut;
const AdhesionSuspendue({required this.membreId, required this.nouveauStatut});
@override
List<Object?> get props => [membreId, nouveauStatut];
}
/// Membre radié
class MembreRadie extends MembresState {
final String membreId;
final String nouveauStatut;
const MembreRadie({required this.membreId, required this.nouveauStatut});
@override
List<Object?> get props => [membreId, nouveauStatut];
}
/// État avec statistiques
class MembresStatsLoaded extends MembresState {
final Map<String, dynamic> stats;

View File

@@ -25,7 +25,7 @@ enum StatutMembre {
inactif,
@JsonValue('SUSPENDU')
suspendu,
@JsonValue('EN_ATTENTE')
@JsonValue('EN_ATTENTE_VALIDATION')
enAttente,
}
@@ -67,6 +67,10 @@ class MembreCompletModel extends Equatable {
/// Téléphone
final String? telephone;
/// Téléphone Wave (mobile money)
@JsonKey(name: 'telephoneWave')
final String? telephoneWave;
/// Date de naissance
@JsonKey(name: 'dateNaissance')
final DateTime? dateNaissance;
@@ -100,6 +104,7 @@ class MembreCompletModel extends Equatable {
final String? photo;
/// Statut du membre
@JsonKey(name: 'statutCompte')
final StatutMembre statut;
/// Rôle dans l'organisation
@@ -148,6 +153,18 @@ class MembreCompletModel extends Equatable {
@JsonKey(name: 'derniereActivite')
final DateTime? derniereActivite;
/// Statut matrimonial (CELIBATAIRE, MARIE, DIVORCE, VEUF)
@JsonKey(name: 'statutMatrimonial')
final String? statutMatrimonial;
/// Type de pièce d'identité (CNI, PASSEPORT, PERMIS_CONDUIRE, TITRE_SEJOUR)
@JsonKey(name: 'typeIdentite')
final String? typeIdentite;
/// Numéro de pièce d'identité
@JsonKey(name: 'numeroIdentite')
final String? numeroIdentite;
/// Notes internes
final String? notes;
@@ -184,6 +201,7 @@ class MembreCompletModel extends Equatable {
required this.prenom,
required this.email,
this.telephone,
this.telephoneWave,
this.dateNaissance,
this.genre,
this.adresse,
@@ -207,6 +225,9 @@ class MembreCompletModel extends Equatable {
this.cotisationAJour = false,
this.nombreEvenementsParticipes = 0,
this.derniereActivite,
this.statutMatrimonial,
this.typeIdentite,
this.numeroIdentite,
this.notes,
this.dateCreation,
this.dateModification,
@@ -231,6 +252,7 @@ class MembreCompletModel extends Equatable {
String? prenom,
String? email,
String? telephone,
String? telephoneWave,
DateTime? dateNaissance,
Genre? genre,
String? adresse,
@@ -254,6 +276,9 @@ class MembreCompletModel extends Equatable {
bool? cotisationAJour,
int? nombreEvenementsParticipes,
DateTime? derniereActivite,
String? statutMatrimonial,
String? typeIdentite,
String? numeroIdentite,
String? notes,
DateTime? dateCreation,
DateTime? dateModification,
@@ -269,6 +294,7 @@ class MembreCompletModel extends Equatable {
prenom: prenom ?? this.prenom,
email: email ?? this.email,
telephone: telephone ?? this.telephone,
telephoneWave: telephoneWave ?? this.telephoneWave,
dateNaissance: dateNaissance ?? this.dateNaissance,
genre: genre ?? this.genre,
adresse: adresse ?? this.adresse,
@@ -292,6 +318,9 @@ class MembreCompletModel extends Equatable {
cotisationAJour: cotisationAJour ?? this.cotisationAJour,
nombreEvenementsParticipes: nombreEvenementsParticipes ?? this.nombreEvenementsParticipes,
derniereActivite: derniereActivite ?? this.derniereActivite,
statutMatrimonial: statutMatrimonial ?? this.statutMatrimonial,
typeIdentite: typeIdentite ?? this.typeIdentite,
numeroIdentite: numeroIdentite ?? this.numeroIdentite,
notes: notes ?? this.notes,
dateCreation: dateCreation ?? this.dateCreation,
dateModification: dateModification ?? this.dateModification,
@@ -341,6 +370,7 @@ class MembreCompletModel extends Equatable {
prenom,
email,
telephone,
telephoneWave,
dateNaissance,
genre,
adresse,
@@ -364,6 +394,9 @@ class MembreCompletModel extends Equatable {
cotisationAJour,
nombreEvenementsParticipes,
derniereActivite,
statutMatrimonial,
typeIdentite,
numeroIdentite,
notes,
dateCreation,
dateModification,

View File

@@ -13,6 +13,7 @@ MembreCompletModel _$MembreCompletModelFromJson(Map<String, dynamic> json) =>
prenom: json['prenom'] as String,
email: json['email'] as String,
telephone: json['telephone'] as String?,
telephoneWave: json['telephoneWave'] as String?,
dateNaissance: json['dateNaissance'] == null
? null
: DateTime.parse(json['dateNaissance'] as String),
@@ -25,7 +26,7 @@ MembreCompletModel _$MembreCompletModelFromJson(Map<String, dynamic> json) =>
profession: json['profession'] as String?,
nationalite: json['nationalite'] as String?,
photo: json['photo'] as String?,
statut: $enumDecodeNullable(_$StatutMembreEnumMap, json['statut']) ??
statut: $enumDecodeNullable(_$StatutMembreEnumMap, json['statutCompte']) ??
StatutMembre.actif,
role: json['role'] as String?,
organisationId: json['organisationId'] as String?,
@@ -46,6 +47,9 @@ MembreCompletModel _$MembreCompletModelFromJson(Map<String, dynamic> json) =>
derniereActivite: json['derniereActivite'] == null
? null
: DateTime.parse(json['derniereActivite'] as String),
statutMatrimonial: json['statutMatrimonial'] as String?,
typeIdentite: json['typeIdentite'] as String?,
numeroIdentite: json['numeroIdentite'] as String?,
notes: json['notes'] as String?,
dateCreation: json['dateCreation'] == null
? null
@@ -70,6 +74,7 @@ Map<String, dynamic> _$MembreCompletModelToJson(MembreCompletModel instance) =>
'prenom': instance.prenom,
'email': instance.email,
'telephone': instance.telephone,
'telephoneWave': instance.telephoneWave,
'dateNaissance': instance.dateNaissance?.toIso8601String(),
'genre': _$GenreEnumMap[instance.genre],
'adresse': instance.adresse,
@@ -80,7 +85,7 @@ Map<String, dynamic> _$MembreCompletModelToJson(MembreCompletModel instance) =>
'profession': instance.profession,
'nationalite': instance.nationalite,
'photo': instance.photo,
'statut': _$StatutMembreEnumMap[instance.statut]!,
'statutCompte': _$StatutMembreEnumMap[instance.statut]!,
'role': instance.role,
'organisationId': instance.organisationId,
'organisationNom': instance.organisationNom,
@@ -93,6 +98,9 @@ Map<String, dynamic> _$MembreCompletModelToJson(MembreCompletModel instance) =>
'cotisationAJour': instance.cotisationAJour,
'nombreEvenementsParticipes': instance.nombreEvenementsParticipes,
'derniereActivite': instance.derniereActivite?.toIso8601String(),
'statutMatrimonial': instance.statutMatrimonial,
'typeIdentite': instance.typeIdentite,
'numeroIdentite': instance.numeroIdentite,
'notes': instance.notes,
'dateCreation': instance.dateCreation?.toIso8601String(),
'dateModification': instance.dateModification?.toIso8601String(),
@@ -115,7 +123,7 @@ const _$StatutMembreEnumMap = {
StatutMembre.actif: 'ACTIF',
StatutMembre.inactif: 'INACTIF',
StatutMembre.suspendu: 'SUSPENDU',
StatutMembre.enAttente: 'EN_ATTENTE',
StatutMembre.enAttente: 'EN_ATTENTE_VALIDATION',
};
const _$NiveauVigilanceKycEnumMap = {

View File

@@ -240,7 +240,7 @@ class MembreRepositoryImpl implements IMembreRepository {
@override
Future<MembreCompletModel> activateMembre(String id) async {
try {
final response = await _apiClient.post('$_baseUrl/$id/activer');
final response = await _apiClient.put('$_baseUrl/$id/activer');
if (response.statusCode == 200) {
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
@@ -257,7 +257,7 @@ class MembreRepositoryImpl implements IMembreRepository {
@override
Future<MembreCompletModel> deactivateMembre(String id) async {
try {
final response = await _apiClient.post('$_baseUrl/$id/desactiver');
final response = await _apiClient.put('$_baseUrl/$id/desactiver');
if (response.statusCode == 200) {
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
@@ -339,5 +339,114 @@ class MembreRepositoryImpl implements IMembreRepository {
rethrow;
}
}
@override
Future<MembreCompletModel> resetMotDePasse(String id) async {
try {
final response = await _apiClient.put('$_baseUrl/$id/reinitialiser-mot-de-passe');
if (response.statusCode == 200) {
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
} else {
throw Exception('Erreur lors de la réinitialisation du mot de passe: ${response.statusCode}');
}
} on DioException {
rethrow;
} catch (e) {
rethrow;
}
}
@override
Future<MembreCompletModel> affecterOrganisation(String membreId, String organisationId) async {
try {
final response = await _apiClient.put(
'$_baseUrl/$membreId/affecter-organisation',
queryParameters: {'organisationId': organisationId},
);
if (response.statusCode == 200) {
return MembreCompletModel.fromJson(response.data as Map<String, dynamic>);
} else {
throw Exception('Erreur lors de l\'affectation à l\'organisation: ${response.statusCode}');
}
} on DioException {
rethrow;
} catch (e) {
rethrow;
}
}
// ── Cycle de vie des adhésions ────────────────────────────────────────────
@override
Future<Map<String, dynamic>> inviterMembre(
String membreId,
String organisationId, {
String? roleOrg,
}) async {
final response = await _apiClient.put(
'$_baseUrl/$membreId/inviter-organisation',
queryParameters: {
'organisationId': organisationId,
if (roleOrg != null) 'roleOrg': roleOrg,
},
);
if (response.statusCode == 200) {
return Map<String, dynamic>.from(response.data as Map);
}
throw Exception('Invitation échouée: ${response.statusCode}');
}
@override
Future<Map<String, dynamic>> activerAdhesion(
String membreId,
String organisationId, {
String? motif,
}) async {
final response = await _apiClient.put(
'$_baseUrl/$membreId/adhesion/activer',
queryParameters: {'organisationId': organisationId},
data: motif != null ? {'motif': motif} : <String, dynamic>{},
);
if (response.statusCode == 200) {
return Map<String, dynamic>.from(response.data as Map);
}
throw Exception('Activation échouée: ${response.statusCode}');
}
@override
Future<Map<String, dynamic>> suspendrAdhesion(
String membreId,
String organisationId, {
String? motif,
}) async {
final response = await _apiClient.put(
'$_baseUrl/$membreId/adhesion/suspendre',
queryParameters: {'organisationId': organisationId},
data: motif != null ? {'motif': motif} : <String, dynamic>{},
);
if (response.statusCode == 200) {
return Map<String, dynamic>.from(response.data as Map);
}
throw Exception('Suspension échouée: ${response.statusCode}');
}
@override
Future<Map<String, dynamic>> radierAdhesion(
String membreId,
String organisationId, {
String? motif,
}) async {
final response = await _apiClient.put(
'$_baseUrl/$membreId/adhesion/radier',
queryParameters: {'organisationId': organisationId},
data: motif != null ? {'motif': motif} : <String, dynamic>{},
);
if (response.statusCode == 200) {
return Map<String, dynamic>.from(response.data as Map);
}
throw Exception('Radiation échouée: ${response.statusCode}');
}
}

View File

@@ -48,4 +48,24 @@ abstract class IMembreRepository {
/// Récupère les statistiques des membres
Future<Map<String, dynamic>> getMembresStats();
/// Réinitialise le mot de passe d'un membre — retourne le membre avec motDePasseTemporaire
Future<MembreCompletModel> resetMotDePasse(String id);
/// Affecte un membre à une organisation (superadmin uniquement)
Future<MembreCompletModel> affecterOrganisation(String membreId, String organisationId);
// ── Cycle de vie des adhésions ───────────────────────────────────────────
/// Invite un membre dans une organisation (statut INVITE, token 7j)
Future<Map<String, dynamic>> inviterMembre(String membreId, String organisationId, {String? roleOrg});
/// Active l'adhésion d'un membre (EN_ATTENTE/INVITE/SUSPENDU → ACTIF)
Future<Map<String, dynamic>> activerAdhesion(String membreId, String organisationId, {String? motif});
/// Suspend l'adhésion d'un membre (ACTIF → SUSPENDU)
Future<Map<String, dynamic>> suspendrAdhesion(String membreId, String organisationId, {String? motif});
/// Radie un membre d'une organisation
Future<Map<String, dynamic>> radierAdhesion(String membreId, String organisationId, {String? motif});
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,8 +1,10 @@
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get_it/get_it.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 '../../../../features/organizations/domain/repositories/organization_repository.dart';
/// Annuaire des Membres - Design UnionFlow
class MembersPageWithDataAndPagination extends StatefulWidget {
@@ -14,6 +16,16 @@ class MembersPageWithDataAndPagination extends StatefulWidget {
final VoidCallback onRefresh;
final void Function(String? query)? onSearch;
final VoidCallback? onAddMember;
/// null = SUPER_ADMIN (vue globale, affiche l'organisation sur chaque carte)
final String? organisationId;
/// Callback déclenché quand l'admin active un membre en attente
final void Function(String memberId)? onActivateMember;
/// Callback déclenché quand l'admin réinitialise le mot de passe d'un membre
final void Function(String memberId)? onResetPassword;
/// Callback déclenché quand le superadmin affecte un membre à une organisation
final void Function(String memberId, String organisationId)? onAffecterOrganisation;
/// Callback pour les actions de cycle de vie adhésion (admin org)
final void Function(String memberId, String action, String? motif)? onLifecycleAction;
const MembersPageWithDataAndPagination({
super.key,
@@ -25,6 +37,11 @@ class MembersPageWithDataAndPagination extends StatefulWidget {
required this.onRefresh,
this.onSearch,
this.onAddMember,
this.organisationId,
this.onActivateMember,
this.onResetPassword,
this.onAffecterOrganisation,
this.onLifecycleAction,
});
@override
@@ -37,6 +54,11 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
String _filterStatus = 'Tous';
Timer? _searchDebounce;
// Organisations pour le picker d'affectation (superadmin)
List<Map<String, String>> _organisationsPicker = [];
bool get _isSuperAdmin => widget.organisationId == null;
@override
void dispose() {
_searchDebounce?.cancel();
@@ -74,51 +96,55 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
);
}
// ── Header ────────────────────────────────────────────────────────────────
Widget _buildHeader() {
final activeCount = widget.members.where((m) => m['status'] == 'Actif').length;
final pendingCount = widget.members.where((m) => m['status'] == 'En attente').length;
final pageMembers = widget.members;
final activeCount = pageMembers.where((m) => m['status'] == 'Actif').length;
final pendingCount = pageMembers.where((m) => m['status'] == 'En attente').length;
return Container(
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
border: Border(
bottom: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1),
),
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)),
Expanded(child: _buildStatBadge('Total', widget.totalCount.toString(), UnionFlowColors.unionGreen, subtitle: 'global')),
const SizedBox(width: 8),
Expanded(child: _buildStatBadge('Actifs', activeCount.toString(), UnionFlowColors.success, subtitle: 'cette page')),
const SizedBox(width: 8),
Expanded(child: _buildStatBadge('Attente', pendingCount.toString(), UnionFlowColors.warning, subtitle: 'cette page')),
],
),
);
}
Widget _buildStatBadge(String label, String value, Color color) {
Widget _buildStatBadge(String label, String value, Color color, {String? subtitle}) {
return Container(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 8),
padding: const EdgeInsets.symmetric(vertical: 7, horizontal: 6),
decoration: BoxDecoration(
color: color.withOpacity(0.1),
color: color.withOpacity(0.08),
borderRadius: BorderRadius.circular(8),
border: Border.all(color: color.withOpacity(0.3), width: 1),
border: Border.all(color: color.withOpacity(0.25), width: 1),
),
child: Column(
children: [
Text(value, style: TextStyle(fontSize: 20, fontWeight: FontWeight.w700, color: color)),
const SizedBox(height: 2),
Text(value, style: TextStyle(fontSize: 18, fontWeight: FontWeight.w800, color: color)),
Text(label, style: TextStyle(fontSize: 10, fontWeight: FontWeight.w600, color: color)),
if (subtitle != null)
Text(subtitle, style: TextStyle(fontSize: 9, color: color.withOpacity(0.6))),
],
),
);
}
// ── Recherche + Filtres ────────────────────────────────────────────────────
Widget _buildSearchAndFilters() {
return Container(
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.fromLTRB(12, 10, 12, 10),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
border: Border(bottom: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1)),
@@ -136,7 +162,7 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
},
style: const TextStyle(fontSize: 14, color: UnionFlowColors.textPrimary),
decoration: InputDecoration(
hintText: 'Rechercher un membre...',
hintText: 'Nom, email, numéro membre...',
hintStyle: const TextStyle(fontSize: 13, color: UnionFlowColors.textTertiary),
prefixIcon: const Icon(Icons.search, size: 20, color: UnionFlowColors.textSecondary),
suffixIcon: _searchQuery.isNotEmpty
@@ -150,24 +176,15 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
},
)
: 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),
),
contentPadding: const EdgeInsets.symmetric(vertical: 11, horizontal: 14),
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),
const SizedBox(height: 10),
SingleChildScrollView(
scrollDirection: Axis.horizontal,
child: Row(
@@ -191,11 +208,12 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
final isSelected = _filterStatus == label;
return GestureDetector(
onTap: () => setState(() => _filterStatus = label),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
child: AnimatedContainer(
duration: const Duration(milliseconds: 150),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
decoration: BoxDecoration(
color: isSelected ? UnionFlowColors.unionGreen : UnionFlowColors.surface,
borderRadius: BorderRadius.circular(12),
color: isSelected ? UnionFlowColors.unionGreen : Colors.transparent,
borderRadius: BorderRadius.circular(20),
border: Border.all(color: isSelected ? UnionFlowColors.unionGreen : UnionFlowColors.border, width: 1),
),
child: Text(
@@ -210,11 +228,14 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
);
}
// ── Liste ─────────────────────────────────────────────────────────────────
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);
(m['name'] as String? ?? '').toLowerCase().contains(_searchQuery.toLowerCase()) ||
(m['email'] as String? ?? '').toLowerCase().contains(_searchQuery.toLowerCase()) ||
(m['numeroMembre'] as String? ?? '').toLowerCase().contains(_searchQuery.toLowerCase());
final matchesStatus = _filterStatus == 'Tous' || m['status'] == _filterStatus;
return matchesSearch && matchesStatus;
}).toList();
@@ -225,7 +246,7 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
onRefresh: () async => widget.onRefresh(),
color: UnionFlowColors.unionGreen,
child: ListView.separated(
padding: const EdgeInsets.all(12),
padding: const EdgeInsets.fromLTRB(12, 12, 12, 12),
itemCount: filtered.length,
separatorBuilder: (_, __) => const SizedBox(height: 6),
itemBuilder: (context, index) => _buildMemberCard(filtered[index]),
@@ -233,11 +254,17 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
);
}
// ── Carte membre ──────────────────────────────────────────────────────────
Widget _buildMemberCard(Map<String, dynamic> member) {
final String? orgName = member['organisationNom'] as String?;
final String? numero = member['numeroMembre'] as String?;
final String status = member['status'] as String? ?? '?';
return GestureDetector(
onTap: () => _showMemberDetails(member),
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 7),
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(10),
@@ -245,104 +272,183 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
),
child: Row(
children: [
// Avatar
Container(
width: 32,
height: 32,
width: 38,
height: 38,
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: 13),
member['initiales'] as String? ?? '??',
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w700, fontSize: 14),
),
),
const SizedBox(width: 12),
// Infos principales
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
member['name'] ?? 'Inconnu',
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: UnionFlowColors.textPrimary),
// Nom + numéro
Row(
children: [
Expanded(
child: Text(
member['name'] as String? ?? 'Inconnu',
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600, color: UnionFlowColors.textPrimary),
overflow: TextOverflow.ellipsis,
),
),
if (numero != null && numero.isNotEmpty) ...[
const SizedBox(width: 6),
Text(
numero,
style: const TextStyle(fontSize: 10, fontWeight: FontWeight.w500, color: UnionFlowColors.textTertiary),
),
],
],
),
const SizedBox(height: 2),
// Rôle
Text(
member['role'] ?? 'Membre',
member['role'] as String? ?? 'Membre',
style: const TextStyle(fontSize: 12, color: UnionFlowColors.textSecondary),
),
if (member['email'] != null) ...[
const SizedBox(height: 4),
// Organisation (SUPER_ADMIN uniquement)
if (_isSuperAdmin && orgName != null && orgName.isNotEmpty) ...[
const SizedBox(height: 3),
Row(
children: [
const Icon(Icons.email_outlined, size: 12, color: UnionFlowColors.textTertiary),
const Icon(Icons.business_outlined, size: 11, color: UnionFlowColors.unionGreen),
const SizedBox(width: 4),
Text(member['email']!, style: const TextStyle(fontSize: 11, color: UnionFlowColors.textTertiary)),
Expanded(
child: Text(
orgName,
style: const TextStyle(fontSize: 11, color: UnionFlowColors.unionGreen, fontWeight: FontWeight.w500),
overflow: TextOverflow.ellipsis,
),
),
],
),
],
// Email
if (member['email'] != null) ...[
const SizedBox(height: 3),
Row(
children: [
const Icon(Icons.email_outlined, size: 11, color: UnionFlowColors.textTertiary),
const SizedBox(width: 4),
Expanded(
child: Text(
member['email'] as String,
style: const TextStyle(fontSize: 11, color: UnionFlowColors.textTertiary),
overflow: TextOverflow.ellipsis,
),
),
],
),
],
],
),
),
_buildStatusBadge(member['status']),
const SizedBox(width: 8),
_buildStatusBadge(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;
}
Widget _buildStatusBadge(String status) {
final (Color color, IconData icon) = switch (status) {
'Actif' => (UnionFlowColors.success, Icons.check_circle_outline),
'Inactif' => (UnionFlowColors.error, Icons.cancel_outlined),
'En attente' => (UnionFlowColors.warning, Icons.schedule_outlined),
'Suspendu' => (const Color(0xFF9E9E9E), Icons.block_outlined),
_ => (UnionFlowColors.textSecondary, Icons.help_outline),
};
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4),
padding: const EdgeInsets.symmetric(horizontal: 8, 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,
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(color: UnionFlowColors.unionGreenPale, shape: BoxShape.circle),
child: const Icon(Icons.people_outline, size: 40, color: UnionFlowColors.unionGreen),
),
const SizedBox(height: 12),
const Text(
'Aucun membre trouvé',
style: TextStyle(fontSize: 14, 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),
),
Icon(icon, size: 11, color: color),
const SizedBox(width: 4),
Text(status, style: TextStyle(fontSize: 11, fontWeight: FontWeight.w600, color: color)),
],
),
);
}
// ── État vide ─────────────────────────────────────────────────────────────
Widget _buildEmptyState() {
final hasActiveFilters = _filterStatus != 'Tous' || _searchQuery.isNotEmpty;
return Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
padding: const EdgeInsets.all(18),
decoration: const BoxDecoration(color: UnionFlowColors.unionGreenPale, shape: BoxShape.circle),
child: Icon(
hasActiveFilters ? Icons.filter_list_off : Icons.people_outline,
size: 40,
color: UnionFlowColors.unionGreen,
),
),
const SizedBox(height: 16),
Text(
hasActiveFilters ? 'Aucun résultat' : 'Aucun membre',
style: const TextStyle(fontSize: 15, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
),
const SizedBox(height: 8),
Text(
hasActiveFilters
? 'Modifiez la recherche ou le filtre de statut'
: 'Aucun membre enregistré pour le moment',
textAlign: TextAlign.center,
style: const TextStyle(fontSize: 13, color: UnionFlowColors.textSecondary),
),
if (hasActiveFilters) ...[
const SizedBox(height: 16),
GestureDetector(
onTap: () {
setState(() {
_filterStatus = 'Tous';
_searchQuery = '';
_searchController.clear();
});
widget.onSearch?.call(null);
},
child: Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
decoration: BoxDecoration(
border: Border.all(color: UnionFlowColors.unionGreen),
borderRadius: BorderRadius.circular(20),
),
child: const Text('Effacer les filtres', style: TextStyle(fontSize: 13, color: UnionFlowColors.unionGreen, fontWeight: FontWeight.w600)),
),
),
],
],
),
),
);
}
// ── Pagination ────────────────────────────────────────────────────────────
Widget _buildPagination() {
return Container(
padding: const EdgeInsets.symmetric(vertical: 12),
padding: const EdgeInsets.symmetric(vertical: 10),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
border: Border(top: BorderSide(color: UnionFlowColors.border.withOpacity(0.5), width: 1)),
@@ -354,10 +460,7 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
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,
)
? () => widget.onPageChanged(widget.currentPage - 1, _searchQuery.isEmpty ? null : _searchQuery)
: null,
),
Container(
@@ -372,10 +475,7 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
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,
)
? () => widget.onPageChanged(widget.currentPage + 1, _searchQuery.isEmpty ? null : _searchQuery)
: null,
),
],
@@ -383,61 +483,434 @@ class _MembersPageWithDataAndPaginationState extends State<MembersPageWithDataAn
);
}
// ── Sheet détail membre ───────────────────────────────────────────────────
void _showMemberDetails(Map<String, dynamic> member) {
showModalBottomSheet(
context: context,
backgroundColor: Colors.transparent,
builder: (context) => Container(
padding: const EdgeInsets.all(16),
decoration: const BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.vertical(top: Radius.circular(16)),
),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 56,
height: 56,
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: 22),
isScrollControlled: true,
builder: (context) => DraggableScrollableSheet(
initialChildSize: 0.55,
minChildSize: 0.4,
maxChildSize: 0.85,
expand: false,
builder: (context, scrollController) => Container(
decoration: const BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
child: Column(
children: [
// Drag handle
Container(
margin: const EdgeInsets.only(top: 10),
width: 36,
height: 4,
decoration: BoxDecoration(color: UnionFlowColors.border, borderRadius: BorderRadius.circular(2)),
),
Expanded(
child: SingleChildScrollView(
controller: scrollController,
padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// En-tête avatar + nom + statut
Row(
children: [
Container(
width: 56,
height: 56,
decoration: const BoxDecoration(gradient: UnionFlowColors.primaryGradient, shape: BoxShape.circle),
alignment: Alignment.center,
child: Text(
member['initiales'] as String? ?? '??',
style: const TextStyle(color: Colors.white, fontWeight: FontWeight.w900, fontSize: 22),
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
member['name'] as String? ?? '',
style: const TextStyle(fontSize: 16, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
),
const SizedBox(height: 3),
Text(
member['role'] as String? ?? 'Membre',
style: const TextStyle(fontSize: 13, color: UnionFlowColors.textSecondary),
),
if (member['numeroMembre'] != null) ...[
const SizedBox(height: 3),
Text(
member['numeroMembre'] as String,
style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w500, color: UnionFlowColors.textTertiary),
),
],
],
),
),
_buildStatusBadge(member['status'] as String? ?? '?'),
],
),
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 12),
// Infos contact
_buildSectionTitle('Contact'),
_buildDetailRow(Icons.email_outlined, 'Email', member['email'] as String? ?? ''),
if ((member['phone'] as String? ?? '').isNotEmpty)
_buildDetailRow(Icons.phone_outlined, 'Téléphone', member['phone'] as String),
const SizedBox(height: 12),
// Infos organisation
if (member['organisationNom'] != null || member['organisationId'] != null) ...[
_buildSectionTitle('Organisation'),
if (member['organisationNom'] != null)
_buildDetailRow(Icons.business_outlined, 'Organisation', member['organisationNom'] as String),
if (member['dateAdhesion'] != null)
_buildDetailRow(Icons.calendar_today_outlined, 'Adhésion', _formatDate(member['dateAdhesion'])),
const SizedBox(height: 12),
],
// Infos pro
if ((member['department'] as String? ?? '').isNotEmpty) ...[
_buildSectionTitle('Profil'),
_buildDetailRow(Icons.work_outline, 'Profession', member['department'] as String),
if ((member['nationalite'] as String? ?? '').isNotEmpty)
_buildDetailRow(Icons.flag_outlined, 'Nationalité', member['nationalite'] as String),
if ((member['location'] as String? ?? ', ').trim() != ',')
_buildDetailRow(Icons.location_on_outlined, 'Localisation', member['location'] as String),
],
// Bouton d'activation (ADMIN_ORGANISATION uniquement, membre en attente)
if (member['status'] == 'En attente' && widget.onActivateMember != null) ...[
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () {
Navigator.pop(context);
widget.onActivateMember!(member['id'] as String);
},
icon: const Icon(Icons.check_circle_outline, size: 18),
label: const Text('Activer le membre', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.success,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
),
],
// Bouton reset mot de passe (tous membres avec compte Keycloak)
if (widget.onResetPassword != null) ...[
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () {
Navigator.pop(context);
widget.onResetPassword!(member['id'] as String);
},
icon: const Icon(Icons.lock_reset_outlined, size: 18),
label: const Text('Réinitialiser le mot de passe', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
style: OutlinedButton.styleFrom(
foregroundColor: UnionFlowColors.warning,
side: const BorderSide(color: UnionFlowColors.warning),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
),
],
// Bouton affectation organisation (superadmin, membre sans organisation)
if (_isSuperAdmin &&
widget.onAffecterOrganisation != null &&
(member['organisationId'] == null || (member['organisationId'] as String).isEmpty)) ...[
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 16),
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
onPressed: () => _showAffecterOrganisationDialog(context, member),
icon: const Icon(Icons.business_outlined, size: 18),
label: const Text('Affecter à une organisation', style: TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
style: OutlinedButton.styleFrom(
foregroundColor: UnionFlowColors.unionGreen,
side: const BorderSide(color: UnionFlowColors.unionGreen),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
),
],
// ── Boutons cycle de vie adhésion (ADMIN_ORGANISATION) ──
if (!_isSuperAdmin && widget.onLifecycleAction != null) ...[
const SizedBox(height: 16),
const Divider(height: 1),
const SizedBox(height: 8),
_buildLifecycleActionsSection(context, member),
],
],
),
),
),
],
),
),
),
);
}
Widget _buildLifecycleActionsSection(BuildContext context, Map<String, dynamic> member) {
final memberId = member['id'] as String? ?? '';
final statut = member['statutMembre'] as String? ?? member['status'] as String? ?? '';
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Padding(
padding: EdgeInsets.only(bottom: 8),
child: Text('Actions adhésion', style: TextStyle(fontSize: 13, fontWeight: FontWeight.w600, color: Colors.grey)),
),
// Activer (INVITE ou EN_ATTENTE_VALIDATION)
if (statut == 'INVITE' || statut == 'EN_ATTENTE_VALIDATION' || statut == 'En attente')
_lifecycleButton(
context: context,
label: 'Activer l\'adhésion',
icon: Icons.check_circle_outline,
color: Colors.green,
onPressed: () {
Navigator.pop(context);
widget.onLifecycleAction!(memberId, 'activer', null);
},
),
// Suspendre (ACTIF)
if (statut == 'ACTIF' || statut == 'Actif')
_lifecycleButton(
context: context,
label: 'Suspendre l\'adhésion',
icon: Icons.pause_circle_outline,
color: Colors.orange,
outlined: true,
onPressed: () => _showMotifDialog(
context,
'Suspendre l\'adhésion',
onConfirm: (motif) => widget.onLifecycleAction!(memberId, 'suspendre', motif),
),
const SizedBox(height: 10),
Text(
member['name'] ?? '',
style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w700, color: UnionFlowColors.textPrimary),
),
// Réactiver (SUSPENDU)
if (statut == 'SUSPENDU' || statut == 'Suspendu')
_lifecycleButton(
context: context,
label: 'Réactiver l\'adhésion',
icon: Icons.play_circle_outline,
color: Colors.blue,
onPressed: () {
Navigator.pop(context);
widget.onLifecycleAction!(memberId, 'activer', null);
},
),
// Radier (tout statut actif)
if (statut != 'RADIE' && statut != 'ARCHIVE' && statut.isNotEmpty)
_lifecycleButton(
context: context,
label: 'Radier de l\'organisation',
icon: Icons.block_outlined,
color: Colors.red,
outlined: true,
onPressed: () => _showMotifDialog(
context,
'Radier le membre',
onConfirm: (motif) => widget.onLifecycleAction!(memberId, 'radier', motif),
),
const SizedBox(height: 4),
Text(
member['role'] ?? '',
style: const TextStyle(fontSize: 13, color: UnionFlowColors.textSecondary),
),
],
);
}
Widget _lifecycleButton({
required BuildContext context,
required String label,
required IconData icon,
required Color color,
bool outlined = false,
required VoidCallback onPressed,
}) {
return Padding(
padding: const EdgeInsets.only(bottom: 8),
child: SizedBox(
width: double.infinity,
child: outlined
? OutlinedButton.icon(
onPressed: onPressed,
icon: Icon(icon, size: 18),
label: Text(label, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
style: OutlinedButton.styleFrom(
foregroundColor: color,
side: BorderSide(color: color),
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
)
: ElevatedButton.icon(
onPressed: onPressed,
icon: Icon(icon, size: 18),
label: Text(label, style: const TextStyle(fontSize: 14, fontWeight: FontWeight.w600)),
style: ElevatedButton.styleFrom(
backgroundColor: color,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 12),
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
),
),
),
);
}
void _showMotifDialog(
BuildContext context,
String titre, {
required void Function(String? motif) onConfirm,
}) {
final motifCtrl = TextEditingController();
showDialog<void>(
context: context,
builder: (ctx) => AlertDialog(
title: Text(titre),
content: TextField(
controller: motifCtrl,
decoration: const InputDecoration(
labelText: 'Motif (optionnel)',
border: OutlineInputBorder(),
),
maxLines: 3,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(ctx),
child: const Text('Annuler'),
),
ElevatedButton(
onPressed: () {
Navigator.pop(ctx); // ferme dialog motif
Navigator.pop(context); // ferme bottom sheet
onConfirm(motifCtrl.text.isNotEmpty ? motifCtrl.text : null);
},
child: const Text('Confirmer'),
),
],
),
);
}
Future<void> _showAffecterOrganisationDialog(
BuildContext ctx,
Map<String, dynamic> member,
) async {
// Charger les organisations si pas encore fait
if (_organisationsPicker.isEmpty) {
try {
final repo = GetIt.instance<IOrganizationRepository>();
final orgs = await repo.getOrganizations(page: 0, size: 100);
if (mounted) {
setState(() {
_organisationsPicker = orgs
.where((o) => o.id != null && o.id!.isNotEmpty)
.map((o) => {'id': o.id!, 'nom': o.nomAffichage})
.toList();
});
}
} catch (_) {}
}
if (!mounted) return;
String? selectedOrgId;
await showDialog<void>(
context: ctx,
builder: (dialogCtx) => StatefulBuilder(
builder: (dialogCtx, setDialogState) => AlertDialog(
title: const Text('Affecter à une organisation'),
content: _organisationsPicker.isEmpty
? const Text('Aucune organisation disponible.')
: DropdownButtonFormField<String>(
decoration: const InputDecoration(labelText: 'Organisation'),
items: _organisationsPicker
.map((o) => DropdownMenuItem<String>(
value: o['id'],
child: Text(o['nom']!),
))
.toList(),
onChanged: (v) => setDialogState(() => selectedOrgId = v),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogCtx),
child: const Text('Annuler'),
),
ElevatedButton(
onPressed: selectedOrgId == null
? null
: () {
Navigator.pop(dialogCtx);
Navigator.pop(ctx); // ferme le bottom sheet
widget.onAffecterOrganisation!(
member['id'] as String,
selectedOrgId!,
);
},
child: const Text('Confirmer'),
),
const SizedBox(height: 12),
_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: 12),
],
),
),
);
}
Widget _buildInfoRow(IconData icon, String text) {
Widget _buildSectionTitle(String title) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8),
padding: const EdgeInsets.only(bottom: 8),
child: Text(
title.toUpperCase(),
style: const TextStyle(fontSize: 11, fontWeight: FontWeight.w700, color: UnionFlowColors.textTertiary, letterSpacing: 0.8),
),
);
}
Widget _buildDetailRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: UnionFlowColors.unionGreen),
const SizedBox(width: 12),
Expanded(child: Text(text, style: const TextStyle(fontSize: 13, color: UnionFlowColors.textPrimary))),
Icon(icon, size: 16, color: UnionFlowColors.unionGreen),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label, style: const TextStyle(fontSize: 11, color: UnionFlowColors.textTertiary)),
const SizedBox(height: 1),
Text(value, style: const TextStyle(fontSize: 13, color: UnionFlowColors.textPrimary, fontWeight: FontWeight.w500)),
],
),
),
],
),
);
}
String _formatDate(dynamic date) {
if (date == null) return '';
if (date is DateTime) return '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}';
return date.toString();
}
}

View File

@@ -15,7 +15,7 @@ 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 '../widgets/add_member_dialog.dart' show showAddMemberSheet, showCredentialsDialog;
import 'members_page_connected.dart';
final _getIt = GetIt.instance;
@@ -55,55 +55,14 @@ class MembersPageConnected extends StatelessWidget {
Widget build(BuildContext context) {
return BlocListener<MembresBloc, MembresState>(
listener: (context, state) {
// Après création : afficher le mot de passe temporaire si disponible, puis recharger
// Après création : recharger la liste (la dialog mot de passe est gérée dans AddMemberDialog)
if (state is MembreCreated) {
final motDePasse = state.membre.motDePasseTemporaire;
if (motDePasse != null && motDePasse.isNotEmpty) {
showDialog<void>(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: const Text('Compte créé avec succès'),
content: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text('Le membre ${state.membre.nomComplet} a été créé.'),
const SizedBox(height: 12),
const Text(
'Mot de passe temporaire :',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
SelectableText(
motDePasse,
style: const TextStyle(
fontSize: 18,
fontFamily: 'monospace',
letterSpacing: 2,
),
),
const SizedBox(height: 12),
const Text(
'Communiquez ce mot de passe au membre. Il devra le changer à sa première connexion.',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
],
),
actions: [
ElevatedButton(
onPressed: () => Navigator.of(_).pop(),
child: const Text('OK'),
),
],
),
);
}
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
// Gestion des erreurs avec SnackBar
if (state is MembresError) {
final bloc = context.read<MembresBloc>();
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(state.message),
@@ -113,12 +72,67 @@ class MembersPageConnected extends StatelessWidget {
label: 'Réessayer',
textColor: Colors.white,
onPressed: () {
context.read<MembresBloc>().add(LoadMembres(organisationId: organisationId));
bloc.add(LoadMembres(organisationId: organisationId));
},
),
),
);
}
// Après activation : succès + rechargement
if (state is MembreActivated) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Membre activé avec succès'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
// Après reset mot de passe : afficher le dialog credentials
if (state is MotDePasseReinitialise) {
showCredentialsDialog(context, state.membre);
}
// Après affectation à une organisation : succès + rechargement
if (state is MembreAffecte) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Membre affecté à l\'organisation avec succès'),
backgroundColor: Colors.green,
duration: Duration(seconds: 3),
),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
// Lifecycle adhésion : succès + rechargement
if (state is MembreInvite) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Invitation envoyée'), backgroundColor: Colors.blue, duration: Duration(seconds: 3)),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
if (state is AdhesionActivee) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Adhésion activée'), backgroundColor: Colors.green, duration: Duration(seconds: 3)),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
if (state is AdhesionSuspendue) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Adhésion suspendue'), backgroundColor: Colors.orange, duration: Duration(seconds: 3)),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
if (state is MembreRadie) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(content: Text('Membre radié de l\'organisation'), backgroundColor: Colors.red, duration: Duration(seconds: 3)),
);
context.read<MembresBloc>().add(LoadMembres(refresh: true, organisationId: organisationId));
}
},
child: BlocBuilder<MembresBloc, MembresState>(
builder: (context, state) {
@@ -178,6 +192,7 @@ class MembersPageConnected extends StatelessWidget {
totalCount: state.totalElements,
currentPage: state.currentPage,
totalPages: state.totalPages,
organisationId: organisationId,
onPageChanged: (newPage, recherche) {
AppLogger.userAction('Load page', data: {'page': newPage});
context.read<MembresBloc>().add(LoadMembres(page: newPage, recherche: recherche, organisationId: organisationId));
@@ -189,16 +204,37 @@ class MembersPageConnected extends StatelessWidget {
onSearch: (query) {
context.read<MembresBloc>().add(LoadMembres(page: 0, recherche: query, organisationId: organisationId));
},
onAddMember: () async {
final bloc = context.read<MembresBloc>();
await showDialog<void>(
context: context,
builder: (_) => BlocProvider.value(
value: bloc,
child: const AddMemberDialog(),
),
);
onAddMember: () => showAddMemberSheet(context),
onActivateMember: (memberId) {
context.read<MembresBloc>().add(ActivateMembre(memberId));
},
onResetPassword: (memberId) {
context.read<MembresBloc>().add(ResetMotDePasse(memberId));
},
onAffecterOrganisation: organisationId == null
? (memberId, orgId) {
context.read<MembresBloc>().add(AffecterOrganisation(memberId, orgId));
}
: null,
onLifecycleAction: organisationId != null
? (memberId, action, motif) {
final bloc = context.read<MembresBloc>();
switch (action) {
case 'inviter':
bloc.add(InviterMembre(membreId: memberId, organisationId: organisationId!));
break;
case 'activer':
bloc.add(ActiverAdhesion(membreId: memberId, organisationId: organisationId!, motif: motif));
break;
case 'suspendre':
bloc.add(SuspendrAdhesion(membreId: memberId, organisationId: organisationId!, motif: motif));
break;
case 'radier':
bloc.add(RadierAdhesion(membreId: memberId, organisationId: organisationId!, motif: motif));
break;
}
}
: null,
);
}

View File

@@ -18,9 +18,16 @@ abstract class OnboardingEvent extends Equatable {
class OnboardingStarted extends OnboardingEvent {
final String? existingSouscriptionId;
final String initialState; // NO_SUBSCRIPTION | AWAITING_PAYMENT | PAYMENT_INITIATED | AWAITING_VALIDATION
const OnboardingStarted({required this.initialState, this.existingSouscriptionId});
final String? typeOrganisation;
final String? organisationId;
const OnboardingStarted({
required this.initialState,
this.existingSouscriptionId,
this.typeOrganisation,
this.organisationId,
});
@override
List<Object?> get props => [initialState, existingSouscriptionId];
List<Object?> get props => [initialState, existingSouscriptionId, typeOrganisation, organisationId];
}
/// L'utilisateur a sélectionné une formule et une plage
@@ -51,6 +58,11 @@ class OnboardingDemandeConfirmee extends OnboardingEvent {
const OnboardingDemandeConfirmee();
}
/// Ouvre l'écran de choix du moyen de paiement (depuis le récapitulatif)
class OnboardingChoixPaiementOuvert extends OnboardingEvent {
const OnboardingChoixPaiementOuvert();
}
/// Initie le paiement Wave
class OnboardingPaiementInitie extends OnboardingEvent {
const OnboardingPaiementInitie();
@@ -109,6 +121,14 @@ class OnboardingStepSummary extends OnboardingState {
List<Object?> get props => [souscription];
}
/// Étape 3b : choix du moyen de paiement (Wave, Orange Money, etc.)
class OnboardingStepChoixPaiement extends OnboardingState {
final SouscriptionStatusModel souscription;
const OnboardingStepChoixPaiement(this.souscription);
@override
List<Object?> get props => [souscription];
}
/// Étape 4 : paiement Wave — URL à ouvrir dans le navigateur
class OnboardingStepPaiement extends OnboardingState {
final SouscriptionStatusModel souscription;
@@ -118,6 +138,9 @@ class OnboardingStepPaiement extends OnboardingState {
List<Object?> get props => [souscription, waveLaunchUrl];
}
/// Paiement confirmé — déclenche un re-check du statut du compte
class OnboardingPaiementConfirme extends OnboardingState {}
/// Étape 5 : en attente de validation SuperAdmin
class OnboardingStepAttente extends OnboardingState {
final SouscriptionStatusModel? souscription;
@@ -145,7 +168,7 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
String? _codeFormule;
String? _plage;
String? _typePeriode;
String? _typeOrganisation;
String _typeOrganisation = '';
String? _organisationId;
SouscriptionStatusModel? _souscription;
@@ -154,12 +177,19 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
on<OnboardingFormuleSelected>(_onFormuleSelected);
on<OnboardingPeriodeSelected>(_onPeriodeSelected);
on<OnboardingDemandeConfirmee>(_onDemandeConfirmee);
on<OnboardingChoixPaiementOuvert>(_onChoixPaiementOuvert);
on<OnboardingPaiementInitie>(_onPaiementInitie);
on<OnboardingRetourDepuisWave>(_onRetourDepuisWave);
}
Future<void> _onStarted(OnboardingStarted event, Emitter<OnboardingState> emit) async {
emit(OnboardingLoading());
if (event.typeOrganisation != null && event.typeOrganisation!.isNotEmpty) {
_typeOrganisation = event.typeOrganisation!;
}
if (event.organisationId != null && event.organisationId!.isNotEmpty) {
_organisationId = event.organisationId;
}
try {
_formules = await _datasource.getFormules();
@@ -189,6 +219,7 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
}
case 'AWAITING_VALIDATION':
case 'VALIDATED': // Paiement confirmé mais activation compte non encore effective
final sosc = await _datasource.getMaSouscription();
_souscription = sosc;
emit(OnboardingStepAttente(souscription: sosc));
@@ -218,14 +249,23 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
void _onPeriodeSelected(OnboardingPeriodeSelected event, Emitter<OnboardingState> emit) {
_typePeriode = event.typePeriode;
_typeOrganisation = event.typeOrganisation;
// typeOrganisation already set from OnboardingStarted; override only if event provides one
if (event.typeOrganisation.isNotEmpty) {
_typeOrganisation = event.typeOrganisation;
}
_organisationId = event.organisationId;
}
void _onChoixPaiementOuvert(OnboardingChoixPaiementOuvert event, Emitter<OnboardingState> emit) {
if (_souscription != null) {
emit(OnboardingStepChoixPaiement(_souscription!));
}
}
Future<void> _onDemandeConfirmee(
OnboardingDemandeConfirmee event, Emitter<OnboardingState> emit) async {
if (_codeFormule == null || _plage == null || _typePeriode == null ||
_typeOrganisation == null || _organisationId == null) {
_organisationId == null) {
emit(const OnboardingError('Données manquantes. Recommencez depuis le début.'));
return;
}
@@ -235,7 +275,7 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
typeFormule: _codeFormule!,
plageMembres: _plage!,
typePeriode: _typePeriode!,
typeOrganisation: _typeOrganisation!,
typeOrganisation: _typeOrganisation.isNotEmpty ? _typeOrganisation : null,
organisationId: _organisationId!,
);
if (sosc != null) {
@@ -281,12 +321,11 @@ class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
if (souscId != null) {
await _datasource.confirmerPaiement(souscId);
}
final sosc = await _datasource.getMaSouscription();
_souscription = sosc;
emit(OnboardingStepAttente(souscription: sosc));
// Émettre OnboardingPaiementConfirme pour déclencher re-check du compte
// Si le backend auto-active le compte, AuthStatusChecked redirigera vers dashboard
emit(OnboardingPaiementConfirme());
} catch (e) {
// En cas d'erreur, on affiche quand même l'écran d'attente
emit(OnboardingStepAttente(souscription: _souscription));
emit(OnboardingPaiementConfirme());
}
}
}

View File

@@ -58,26 +58,32 @@ class SouscriptionDatasource {
required String typeFormule,
required String plageMembres,
required String typePeriode,
required String typeOrganisation,
String? typeOrganisation,
required String organisationId,
}) async {
try {
final opts = await _authOptions();
final body = <String, dynamic>{
'typeFormule': typeFormule,
'plageMembres': plageMembres,
'typePeriode': typePeriode,
'organisationId': organisationId,
};
if (typeOrganisation != null && typeOrganisation.isNotEmpty) {
body['typeOrganisation'] = typeOrganisation;
}
final response = await _dio.post(
'$_base/api/souscriptions/demande',
data: {
'typeFormule': typeFormule,
'plageMembres': plageMembres,
'typePeriode': typePeriode,
'typeOrganisation': typeOrganisation,
'organisationId': organisationId,
},
data: body,
options: opts,
);
if ((response.statusCode == 200 || response.statusCode == 201) && response.data is Map) {
return SouscriptionStatusModel.fromJson(response.data as Map);
}
AppLogger.warning('SouscriptionDatasource.creerDemande: HTTP ${response.statusCode}');
final errMsg = response.data is Map
? (response.data as Map)['message'] ?? response.data.toString()
: response.data?.toString() ?? '(vide)';
AppLogger.warning('SouscriptionDatasource.creerDemande: HTTP ${response.statusCode} — erreur="$errMsg" — sentBody=$body');
} catch (e) {
AppLogger.error('SouscriptionDatasource.creerDemande: $e');
}
@@ -106,7 +112,8 @@ class SouscriptionDatasource {
try {
final opts = await _authOptions();
final response = await _dio.post(
'$_base/api/souscriptions/$souscriptionId/confirmer-paiement',
'$_base/api/souscriptions/confirmer-paiement',
queryParameters: {'id': souscriptionId},
options: opts,
);
return response.statusCode == 200;

View File

@@ -14,6 +14,8 @@ class SouscriptionStatusModel {
final String? waveLaunchUrl;
final String organisationId;
final String? organisationNom;
final DateTime? dateDebut;
final DateTime? dateFin;
const SouscriptionStatusModel({
required this.souscriptionId,
@@ -30,6 +32,8 @@ class SouscriptionStatusModel {
this.waveLaunchUrl,
required this.organisationId,
this.organisationNom,
this.dateDebut,
this.dateFin,
});
factory SouscriptionStatusModel.fromJson(Map<dynamic, dynamic> json) {
@@ -48,6 +52,12 @@ class SouscriptionStatusModel {
waveLaunchUrl: json['waveLaunchUrl'] as String?,
organisationId: json['organisationId'] as String,
organisationNom: json['organisationNom'] as String?,
dateDebut: json['dateDebut'] != null
? DateTime.tryParse(json['dateDebut'] as String)
: null,
dateFin: json['dateFin'] != null
? DateTime.tryParse(json['dateFin'] as String)
: null,
);
}
}

View File

@@ -2,9 +2,11 @@ import 'dart:async';
import 'package:flutter/material.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
/// Étape 5 — En attente de validation SuperAdmin
/// Page de secours — affichée si l'auto-activation échoue après paiement.
/// Normalement jamais vue : confirmerPaiement() active le compte côté backend.
class AwaitingValidationPage extends StatefulWidget {
final SouscriptionStatusModel? souscription;
@@ -19,6 +21,7 @@ class _AwaitingValidationPageState extends State<AwaitingValidationPage>
late AnimationController _pulseController;
late Animation<double> _pulseAnimation;
Timer? _refreshTimer;
int _checkCount = 0;
@override
void initState() {
@@ -27,13 +30,14 @@ class _AwaitingValidationPageState extends State<AwaitingValidationPage>
vsync: this,
duration: const Duration(seconds: 2),
)..repeat(reverse: true);
_pulseAnimation = Tween(begin: 0.85, end: 1.0).animate(
_pulseAnimation = Tween(begin: 0.88, end: 1.0).animate(
CurvedAnimation(parent: _pulseController, curve: Curves.easeInOut),
);
// Vérification périodique toutes les 30 secondes (re-check le statut)
_refreshTimer = Timer.periodic(const Duration(seconds: 30), (_) {
// Vérification périodique toutes les 15 secondes
_refreshTimer = Timer.periodic(const Duration(seconds: 15), (_) {
if (mounted) {
setState(() => _checkCount++);
context.read<AuthBloc>().add(const AuthStatusChecked());
}
});
@@ -49,71 +53,169 @@ class _AwaitingValidationPageState extends State<AwaitingValidationPage>
@override
Widget build(BuildContext context) {
final sosc = widget.souscription;
return Scaffold(
backgroundColor: UnionFlowColors.background,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: SingleChildScrollView(
padding: const EdgeInsets.all(28),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Animation d'attente
const SizedBox(height: 32),
// Animation pulsante
ScaleTransition(
scale: _pulseAnimation,
child: Container(
width: 120,
height: 120,
width: 130,
height: 130,
decoration: BoxDecoration(
color: const Color(0xFFFFF3E0),
shape: BoxShape.circle,
border: Border.all(color: const Color(0xFFF57C00), width: 3),
color: UnionFlowColors.goldPale,
border: Border.all(
color: UnionFlowColors.gold.withOpacity(0.5), width: 3),
boxShadow: UnionFlowColors.goldGlowShadow,
),
child: const Icon(
Icons.hourglass_top_rounded,
size: 60,
color: Color(0xFFF57C00),
size: 64,
color: UnionFlowColors.gold,
),
),
),
const SizedBox(height: 32),
const Text(
'Demande soumise !',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
'Paiement reçu !',
style: TextStyle(
fontSize: 26,
fontWeight: FontWeight.w800,
color: UnionFlowColors.textPrimary,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
const SizedBox(height: 10),
const Text(
'Votre souscription est en cours de vérification par notre équipe. '
'Vous recevrez une notification dès que votre compte sera activé.',
style: TextStyle(fontSize: 15, color: Colors.grey, height: 1.5),
'Votre paiement a bien été reçu. Votre compte\nest en cours d\'activation.',
style: TextStyle(
fontSize: 15,
color: UnionFlowColors.textSecondary,
height: 1.5,
),
textAlign: TextAlign.center,
),
if (sosc != null) ...[
const SizedBox(height: 32),
_SummaryCard(souscription: sosc),
],
const SizedBox(height: 32),
const Text(
'Cette vérification prend généralement 24 à 48 heures ouvrables.',
style: TextStyle(fontSize: 13, color: Colors.grey),
textAlign: TextAlign.center,
),
// Souscription recap card
if (sosc != null) _RecapCard(souscription: sosc),
const SizedBox(height: 24),
OutlinedButton.icon(
onPressed: () =>
context.read<AuthBloc>().add(const AuthStatusChecked()),
icon: const Icon(Icons.refresh),
label: const Text('Vérifier l\'état de mon compte'),
// État de vérification
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(14),
boxShadow: UnionFlowColors.softShadow,
),
child: Row(
children: [
SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2.5,
color: UnionFlowColors.unionGreen,
value: _checkCount > 0 ? null : null,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Vérification automatique en cours',
style: TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13,
color: UnionFlowColors.textPrimary,
),
),
Text(
'Vérifié $_checkCount fois · prochaine dans 15s',
style: const TextStyle(
fontSize: 11,
color: UnionFlowColors.textSecondary,
),
),
],
),
),
],
),
),
const SizedBox(height: 20),
// Note d'information
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: UnionFlowColors.infoPale,
borderRadius: BorderRadius.circular(12),
border:
Border.all(color: UnionFlowColors.info.withOpacity(0.2)),
),
child: const Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.info_outline_rounded,
color: UnionFlowColors.info, size: 18),
SizedBox(width: 10),
Expanded(
child: Text(
'L\'activation est généralement immédiate. Si votre compte n\'est pas activé dans les 5 minutes, contactez notre support.',
style: TextStyle(
fontSize: 12,
color: UnionFlowColors.info,
height: 1.45),
),
),
],
),
),
const SizedBox(height: 28),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () =>
context.read<AuthBloc>().add(const AuthStatusChecked()),
icon: const Icon(Icons.refresh_rounded),
label: const Text(
'Vérifier maintenant',
style: TextStyle(fontSize: 15, fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
shadowColor: UnionFlowColors.unionGreen.withOpacity(0.3),
elevation: 2,
),
),
),
const SizedBox(height: 12),
TextButton(
onPressed: () =>
context.read<AuthBloc>().add(const AuthLogoutRequested()),
child: const Text('Se déconnecter'),
child: const Text(
'Se déconnecter',
style: TextStyle(color: UnionFlowColors.textSecondary),
),
),
],
),
@@ -123,26 +225,49 @@ class _AwaitingValidationPageState extends State<AwaitingValidationPage>
}
}
class _SummaryCard extends StatelessWidget {
class _RecapCard extends StatelessWidget {
final SouscriptionStatusModel souscription;
const _SummaryCard({required this.souscription});
const _RecapCard({required this.souscription});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: Colors.grey[50],
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.grey[200]!),
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(14),
boxShadow: UnionFlowColors.softShadow,
border: Border.all(color: UnionFlowColors.border),
),
child: Column(
children: [
_Row('Organisation', souscription.organisationNom ?? ''),
_Row('Formule', souscription.typeFormule),
_Row('Période', souscription.typePeriode),
if (souscription.montantTotal != null)
_Row('Montant payé', '${souscription.montantTotal!.toStringAsFixed(0)} FCFA'),
_Row(
icon: Icons.business_rounded,
label: 'Organisation',
value: souscription.organisationNom ?? '',
),
const Divider(height: 16, color: UnionFlowColors.border),
_Row(
icon: Icons.workspace_premium_rounded,
label: 'Formule',
value: souscription.typeFormule,
),
const SizedBox(height: 8),
_Row(
icon: Icons.calendar_today_rounded,
label: 'Période',
value: souscription.typePeriode,
),
if (souscription.montantTotal != null) ...[
const SizedBox(height: 8),
_Row(
icon: Icons.payments_rounded,
label: 'Montant payé',
value: '${souscription.montantTotal!.toStringAsFixed(0)} FCFA',
valueColor: UnionFlowColors.unionGreen,
valueBold: true,
),
],
],
),
);
@@ -150,22 +275,41 @@ class _SummaryCard extends StatelessWidget {
}
class _Row extends StatelessWidget {
final IconData icon;
final String label;
final String value;
const _Row(this.label, this.value);
final Color valueColor;
final bool valueBold;
const _Row({
required this.icon,
required this.label,
required this.value,
this.valueColor = UnionFlowColors.textPrimary,
this.valueBold = false,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 4),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(label, style: const TextStyle(color: Colors.grey, fontSize: 13)),
Text(value,
style: const TextStyle(fontWeight: FontWeight.w500, fontSize: 13)),
],
),
return Row(
children: [
Icon(icon, size: 16, color: UnionFlowColors.textTertiary),
const SizedBox(width: 8),
Text(
label,
style: const TextStyle(
color: UnionFlowColors.textSecondary, fontSize: 13),
),
const Spacer(),
Text(
value,
style: TextStyle(
color: valueColor,
fontSize: 13,
fontWeight: valueBold ? FontWeight.w700 : FontWeight.w500,
),
),
],
);
}
}

View File

@@ -2,9 +2,12 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../../../core/di/injection.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
import 'plan_selection_page.dart';
import 'period_selection_page.dart';
import 'subscription_summary_page.dart';
import 'payment_method_page.dart';
import 'wave_payment_page.dart';
import 'awaiting_validation_page.dart';
@@ -14,11 +17,13 @@ class OnboardingFlowPage extends StatelessWidget {
final String onboardingState;
final String? souscriptionId;
final String organisationId;
final String? typeOrganisation;
const OnboardingFlowPage({
super.key,
required this.onboardingState,
required this.organisationId,
this.typeOrganisation,
this.souscriptionId,
});
@@ -29,6 +34,8 @@ class OnboardingFlowPage extends StatelessWidget {
..add(OnboardingStarted(
initialState: onboardingState,
existingSouscriptionId: souscriptionId,
typeOrganisation: typeOrganisation,
organisationId: organisationId.isNotEmpty ? organisationId : null,
)),
child: const _OnboardingFlowView(),
);
@@ -40,30 +47,76 @@ class _OnboardingFlowView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return BlocBuilder<OnboardingBloc, OnboardingState>(
return BlocConsumer<OnboardingBloc, OnboardingState>(
listener: (context, state) {
// Paiement confirmé → re-check du statut (auto-activation backend)
if (state is OnboardingPaiementConfirme) {
context.read<AuthBloc>().add(const AuthStatusChecked());
}
},
builder: (context, state) {
if (state is OnboardingLoading || state is OnboardingInitial) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
if (state is OnboardingLoading || state is OnboardingInitial || state is OnboardingPaiementConfirme) {
return Scaffold(
backgroundColor: UnionFlowColors.background,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const CircularProgressIndicator(
color: UnionFlowColors.unionGreen,
),
const SizedBox(height: 16),
Text(
state is OnboardingPaiementConfirme
? 'Activation de votre compte…'
: 'Chargement…',
style: const TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 15,
),
),
],
),
),
);
}
if (state is OnboardingError) {
return Scaffold(
backgroundColor: UnionFlowColors.background,
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error_outline, size: 64, color: Colors.red),
const SizedBox(height: 16),
Text(state.message, textAlign: TextAlign.center),
Container(
width: 80,
height: 80,
decoration: BoxDecoration(
color: UnionFlowColors.errorPale,
shape: BoxShape.circle,
),
child: const Icon(Icons.error_outline,
size: 40, color: UnionFlowColors.error),
),
const SizedBox(height: 20),
Text(
state.message,
textAlign: TextAlign.center,
style: const TextStyle(
color: UnionFlowColors.textPrimary, fontSize: 15),
),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingStarted(initialState: 'NO_SUBSCRIPTION'),
const OnboardingStarted(
initialState: 'NO_SUBSCRIPTION'),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
),
child: const Text('Réessayer'),
),
],
@@ -89,6 +142,10 @@ class _OnboardingFlowView extends StatelessWidget {
return SubscriptionSummaryPage(souscription: state.souscription);
}
if (state is OnboardingStepChoixPaiement) {
return PaymentMethodPage(souscription: state.souscription);
}
if (state is OnboardingStepPaiement) {
return WavePaymentPage(
souscription: state.souscription,
@@ -104,7 +161,9 @@ class _OnboardingFlowView extends StatelessWidget {
return _RejectedPage(commentaire: state.commentaire);
}
return const Scaffold(body: Center(child: CircularProgressIndicator()));
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
},
);
}
@@ -117,28 +176,93 @@ class _RejectedPage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
backgroundColor: UnionFlowColors.background,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Icon(Icons.cancel_outlined, size: 72, color: Colors.red),
const SizedBox(height: 24),
const Text(
'Souscription rejetée',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: UnionFlowColors.errorPale,
shape: BoxShape.circle,
),
child: const Icon(Icons.cancel_outlined,
size: 52, color: UnionFlowColors.error),
),
if (commentaire != null) ...[
const SizedBox(height: 12),
Text(commentaire!, textAlign: TextAlign.center),
const SizedBox(height: 28),
const Text(
'Demande rejetée',
style: TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
color: UnionFlowColors.textPrimary,
),
),
const SizedBox(height: 12),
const Text(
'Votre demande de souscription a été refusée.',
textAlign: TextAlign.center,
style: TextStyle(color: UnionFlowColors.textSecondary),
),
if (commentaire != null && commentaire!.isNotEmpty) ...[
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: UnionFlowColors.errorPale,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: UnionFlowColors.error.withOpacity(0.3)),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.comment_outlined,
color: UnionFlowColors.error, size: 18),
const SizedBox(width: 10),
Expanded(
child: Text(
commentaire!,
style: const TextStyle(
color: UnionFlowColors.textPrimary,
fontSize: 14,
height: 1.5),
),
),
],
),
),
],
const SizedBox(height: 32),
ElevatedButton(
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingStarted(initialState: 'NO_SUBSCRIPTION'),
),
child: const Text('Nouvelle souscription'),
const SizedBox(height: 36),
SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: () => context.read<OnboardingBloc>().add(
const OnboardingStarted(
initialState: 'NO_SUBSCRIPTION'),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12)),
),
child: const Text('Soumettre une nouvelle demande',
style: TextStyle(fontSize: 15)),
),
),
const SizedBox(height: 12),
TextButton(
onPressed: () =>
context.read<AuthBloc>().add(const AuthLogoutRequested()),
child: const Text('Se déconnecter',
style:
TextStyle(color: UnionFlowColors.textSecondary)),
),
],
),

View File

@@ -0,0 +1,169 @@
import 'package:flutter/material.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
/// Header commun à toutes les étapes d'onboarding
class OnboardingStepHeader extends StatelessWidget {
final int step;
final int total;
final String title;
final String subtitle;
const OnboardingStepHeader({
super.key,
required this.step,
required this.total,
required this.title,
required this.subtitle,
});
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
),
child: SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: List.generate(total, (i) {
final done = i < step;
return Expanded(
child: Container(
height: 4,
margin: EdgeInsets.only(right: i < total - 1 ? 6 : 0),
decoration: BoxDecoration(
color: done
? Colors.white
: Colors.white.withOpacity(0.3),
borderRadius: BorderRadius.circular(2),
),
),
);
}),
),
const SizedBox(height: 6),
Text(
'Étape $step sur $total',
style: TextStyle(
color: Colors.white.withOpacity(0.75),
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
const SizedBox(height: 12),
Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 4),
Text(
subtitle,
style: TextStyle(
color: Colors.white.withOpacity(0.8),
fontSize: 13,
height: 1.4,
),
),
],
),
),
),
);
}
}
/// Titre de section avec icône
class OnboardingSectionTitle extends StatelessWidget {
final IconData icon;
final String title;
const OnboardingSectionTitle({
super.key,
required this.icon,
required this.title,
});
@override
Widget build(BuildContext context) {
return Row(
children: [
Icon(icon, color: UnionFlowColors.unionGreen, size: 20),
const SizedBox(width: 8),
Text(
title,
style: const TextStyle(
color: UnionFlowColors.textPrimary,
fontWeight: FontWeight.w700,
fontSize: 16,
),
),
],
);
}
}
/// Barre de bouton principale en bas de page
class OnboardingBottomBar extends StatelessWidget {
final bool enabled;
final String label;
final VoidCallback onPressed;
const OnboardingBottomBar({
super.key,
required this.enabled,
required this.label,
required this.onPressed,
});
@override
Widget build(BuildContext context) {
return Container(
padding: EdgeInsets.fromLTRB(
20, 12, 20, MediaQuery.of(context).padding.bottom + 12),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 12,
offset: const Offset(0, -4),
),
],
),
child: SizedBox(
width: double.infinity,
child: ElevatedButton(
onPressed: enabled ? onPressed : null,
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
disabledBackgroundColor: UnionFlowColors.border,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14),
),
elevation: enabled ? 2 : 0,
shadowColor: UnionFlowColors.unionGreen.withOpacity(0.4),
),
child: Text(
label,
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
letterSpacing: 0.3,
),
),
),
),
);
}
}

View File

@@ -0,0 +1,428 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
/// Écran de sélection du moyen de paiement
class PaymentMethodPage extends StatefulWidget {
final SouscriptionStatusModel souscription;
const PaymentMethodPage({super.key, required this.souscription});
@override
State<PaymentMethodPage> createState() => _PaymentMethodPageState();
}
class _PaymentMethodPageState extends State<PaymentMethodPage> {
String? _selected;
static const _methods = [
_PayMethod(
id: 'WAVE',
name: 'Wave Mobile Money',
description: 'Paiement rapide via votre compte Wave',
logoAsset: 'assets/images/payment_methods/wave/logo.png',
color: Color(0xFF00B9F1),
available: true,
badge: 'Recommandé',
),
_PayMethod(
id: 'ORANGE_MONEY',
name: 'Orange Money',
description: 'Paiement via Orange Money',
logoAsset: 'assets/images/payment_methods/orange_money/logo-black.png',
color: Color(0xFFFF6600),
available: false,
badge: 'Prochainement',
),
];
@override
Widget build(BuildContext context) {
final montant = widget.souscription.montantTotal ?? 0;
return Scaffold(
backgroundColor: UnionFlowColors.background,
body: Column(
children: [
// Header
Container(
decoration: const BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
),
child: SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 16, 20, 24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
IconButton(
onPressed: () => Navigator.of(context).maybePop(),
icon: const Icon(Icons.arrow_back_rounded,
color: Colors.white),
padding: EdgeInsets.zero,
constraints: const BoxConstraints(),
),
const SizedBox(height: 12),
const Text(
'Moyen de paiement',
style: TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.w800,
),
),
const SizedBox(height: 4),
Text(
'Choisissez comment régler votre souscription',
style: TextStyle(
color: Colors.white.withOpacity(0.8), fontSize: 13),
),
],
),
),
),
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 24, 20, 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Montant rappel
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(14),
boxShadow: UnionFlowColors.softShadow,
),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
gradient: UnionFlowColors.goldGradient,
borderRadius: BorderRadius.circular(10),
),
child: const Icon(Icons.receipt_rounded,
color: Colors.white, size: 22),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Montant total',
style: TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 12),
),
Text(
'${_formatPrix(montant)} FCFA',
style: const TextStyle(
color: UnionFlowColors.textPrimary,
fontSize: 20,
fontWeight: FontWeight.w900,
),
),
],
),
),
if (widget.souscription.organisationNom != null)
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
const Text(
'Organisation',
style: TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 11),
),
Text(
widget.souscription.organisationNom!,
style: const TextStyle(
color: UnionFlowColors.textPrimary,
fontSize: 12,
fontWeight: FontWeight.w600),
),
],
),
],
),
),
const SizedBox(height: 24),
const Text(
'Sélectionnez un moyen de paiement',
style: TextStyle(
color: UnionFlowColors.textPrimary,
fontWeight: FontWeight.w700,
fontSize: 15,
),
),
const SizedBox(height: 12),
..._methods.map((m) => _MethodCard(
method: m,
selected: _selected == m.id,
onTap: m.available
? () => setState(() => _selected = m.id)
: null,
)),
const SizedBox(height: 20),
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: UnionFlowColors.unionGreenPale,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color:
UnionFlowColors.unionGreen.withOpacity(0.25)),
),
child: const Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.lock_rounded,
color: UnionFlowColors.unionGreen, size: 18),
SizedBox(width: 10),
Expanded(
child: Text(
'Vos informations de paiement sont sécurisées et ne sont jamais stockées sur nos serveurs. La transaction est traitée directement par Wave.',
style: TextStyle(
fontSize: 12,
color: UnionFlowColors.unionGreen,
height: 1.4),
),
),
],
),
),
],
),
),
),
],
),
bottomNavigationBar: Container(
padding: EdgeInsets.fromLTRB(
20, 12, 20, MediaQuery.of(context).padding.bottom + 12),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 12,
offset: const Offset(0, -4),
),
],
),
child: SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _selected == 'WAVE'
? () => context
.read<OnboardingBloc>()
.add(const OnboardingPaiementInitie())
: null,
icon: const Icon(Icons.open_in_new_rounded),
label: Text(
_selected == 'WAVE'
? 'Payer avec Wave'
: 'Sélectionnez un moyen de paiement',
style:
const TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: const Color(0xFF00B9F1),
disabledBackgroundColor: UnionFlowColors.border,
foregroundColor: Colors.white,
disabledForegroundColor: UnionFlowColors.textSecondary,
padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
elevation: _selected == 'WAVE' ? 3 : 0,
shadowColor: const Color(0xFF00B9F1).withOpacity(0.4),
),
),
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) return '${(prix / 1000000).toStringAsFixed(1)} M';
final s = prix.toStringAsFixed(0);
if (s.length > 3) {
return '${s.substring(0, s.length - 3)} ${s.substring(s.length - 3)}';
}
return s;
}
}
class _PayMethod {
final String id, name, description, logoAsset;
final Color color;
final bool available;
final String badge;
const _PayMethod({
required this.id,
required this.name,
required this.description,
required this.logoAsset,
required this.color,
required this.available,
required this.badge,
});
}
class _MethodCard extends StatelessWidget {
final _PayMethod method;
final bool selected;
final VoidCallback? onTap;
const _MethodCard({
required this.method,
required this.selected,
this.onTap,
});
@override
Widget build(BuildContext context) {
final disabled = onTap == null;
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: disabled
? UnionFlowColors.surfaceVariant
: selected
? method.color.withOpacity(0.06)
: UnionFlowColors.surface,
border: Border.all(
color: selected ? method.color : UnionFlowColors.border,
width: selected ? 2 : 1,
),
borderRadius: BorderRadius.circular(14),
boxShadow: disabled
? []
: selected
? [
BoxShadow(
color: method.color.withOpacity(0.15),
blurRadius: 16,
offset: const Offset(0, 6),
)
]
: UnionFlowColors.softShadow,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
// Logo image
Container(
width: 56,
height: 48,
decoration: BoxDecoration(
color: disabled
? UnionFlowColors.border
: Colors.white,
borderRadius: BorderRadius.circular(10),
border: Border.all(color: UnionFlowColors.border),
),
padding: const EdgeInsets.all(6),
child: Image.asset(
method.logoAsset,
fit: BoxFit.contain,
color: disabled ? UnionFlowColors.textTertiary : null,
colorBlendMode: disabled ? BlendMode.srcIn : null,
errorBuilder: (_, __, ___) => Icon(
Icons.account_balance_wallet_rounded,
color: disabled ? UnionFlowColors.textTertiary : method.color,
size: 24,
),
),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
method.name,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 14,
color: disabled
? UnionFlowColors.textTertiary
: UnionFlowColors.textPrimary,
),
),
Text(
method.description,
style: TextStyle(
fontSize: 12,
color: disabled
? UnionFlowColors.textTertiary
: UnionFlowColors.textSecondary,
),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 3),
decoration: BoxDecoration(
color: disabled
? UnionFlowColors.border
: method.available
? method.color.withOpacity(0.1)
: UnionFlowColors.surfaceVariant,
borderRadius: BorderRadius.circular(20),
),
child: Text(
method.badge,
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w700,
color: disabled
? UnionFlowColors.textTertiary
: method.available
? method.color
: UnionFlowColors.textSecondary,
),
),
),
if (!disabled) ...[
const SizedBox(height: 6),
Icon(
selected
? Icons.check_circle_rounded
: Icons.radio_button_unchecked,
color: selected ? method.color : UnionFlowColors.border,
size: 20,
),
],
],
),
],
),
),
),
);
}
}

View File

@@ -3,8 +3,11 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/formule_model.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
import 'onboarding_shared_widgets.dart';
/// Étape 2 — Choix de la période de facturation et du type d'organisation
/// Étape 2 — Choix de la période de facturation
/// Le type d'organisation est récupéré automatiquement depuis le backend.
class PeriodSelectionPage extends StatefulWidget {
final String codeFormule;
final String plage;
@@ -23,35 +26,23 @@ class PeriodSelectionPage extends StatefulWidget {
class _PeriodSelectionPageState extends State<PeriodSelectionPage> {
String _selectedPeriode = 'MENSUEL';
String _selectedTypeOrg = 'ASSOCIATION';
static const _periodes = [
('MENSUEL', 'Mensuel', 'Aucune remise', 1.00),
('TRIMESTRIEL', 'Trimestriel', '5% de remise', 0.95),
('SEMESTRIEL', 'Semestriel', '10% de remise', 0.90),
('ANNUEL', 'Annuel', '20% de remise', 0.80),
];
static const _typesOrg = [
('ASSOCIATION', 'Association / ONG locale', '×1.0'),
('MUTUELLE', 'Mutuelle (santé, fonctionnaires…)', '×1.2'),
('COOPERATIVE', 'Coopérative / Microfinance', '×1.3'),
('FEDERATION', 'Fédération / Grande ONG', '×1.0 ou ×1.5 Premium'),
_Periode('MENSUEL', 'Mensuel', '1 mois', null, 1, 1.00),
_Periode('TRIMESTRIEL', 'Trimestriel', '3 mois', '5%', 3, 0.95),
_Periode('SEMESTRIEL', 'Semestriel', '6 mois', '10%', 6, 0.90),
_Periode('ANNUEL', 'Annuel', '12 mois', '20%', 12, 0.80),
];
FormuleModel? get _formule => widget.formules
.where((f) => f.code == widget.codeFormule && f.plage == widget.plage)
.firstOrNull;
double get _prixEstime {
double _estimerPrix(String periodeCode) {
final f = _formule;
if (f == null) return 0;
final coefPeriode =
_periodes.firstWhere((p) => p.$1 == _selectedPeriode).$4;
final coefOrg =
_selectedTypeOrg == 'COOPERATIVE' ? 1.3 : _selectedTypeOrg == 'MUTUELLE' ? 1.2 : 1.0;
final nbMois = {'MENSUEL': 1, 'TRIMESTRIEL': 3, 'SEMESTRIEL': 6, 'ANNUEL': 12}[_selectedPeriode]!;
return f.prixMensuel * coefOrg * coefPeriode * nbMois;
final p = _periodes.firstWhere((x) => x.code == periodeCode);
return f.prixMensuel * p.coef * p.nbMois;
}
String get _organisationId {
@@ -69,156 +60,363 @@ class _PeriodSelectionPageState extends State<PeriodSelectionPage> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final prixSelected = _estimerPrix(_selectedPeriode);
return Scaffold(
appBar: AppBar(
title: const Text('Période & type d\'organisation'),
leading: BackButton(
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingStarted(initialState: 'NO_SUBSCRIPTION'),
),
),
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
_StepIndicator(current: 2, total: 3),
const SizedBox(height: 24),
// Période
Text('Période de facturation', style: theme.textTheme.titleMedium),
const SizedBox(height: 8),
..._periodes.map((p) {
final (code, label, remise, _) = p;
final selected = _selectedPeriode == code;
return RadioListTile<String>(
value: code,
groupValue: _selectedPeriode,
onChanged: (v) => setState(() => _selectedPeriode = v!),
title: Text(label,
style: TextStyle(
fontWeight:
selected ? FontWeight.bold : FontWeight.normal)),
subtitle: Text(remise,
style: TextStyle(
color: code != 'MENSUEL' ? Colors.green[700] : null)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(
color: selected
? theme.primaryColor
: Colors.grey[300]!,
),
),
tileColor:
selected ? theme.primaryColor.withOpacity(0.05) : null,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
);
}),
const SizedBox(height: 24),
Text('Type de votre organisation', style: theme.textTheme.titleMedium),
const SizedBox(height: 4),
Text(
'Détermine le coefficient tarifaire applicable.',
style:
theme.textTheme.bodySmall?.copyWith(color: Colors.grey[600]),
),
const SizedBox(height: 8),
..._typesOrg.map((t) {
final (code, label, coef) = t;
final selected = _selectedTypeOrg == code;
return RadioListTile<String>(
value: code,
groupValue: _selectedTypeOrg,
onChanged: (v) => setState(() => _selectedTypeOrg = v!),
title: Text(label),
subtitle: Text('Coefficient : $coef',
style: const TextStyle(fontSize: 12)),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(8),
side: BorderSide(
color: selected ? theme.primaryColor : Colors.grey[300]!,
),
),
tileColor:
selected ? theme.primaryColor.withOpacity(0.05) : null,
contentPadding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
);
}),
const SizedBox(height: 24),
// Estimation du prix
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.primaryColor.withOpacity(0.08),
borderRadius: BorderRadius.circular(12),
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
backgroundColor: UnionFlowColors.background,
body: Column(
children: [
OnboardingStepHeader(
step: 2,
total: 3,
title: 'Période de facturation',
subtitle: 'Choisissez votre rythme de paiement.\nPlus la période est longue, plus vous économisez.',
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Estimation', style: TextStyle(fontWeight: FontWeight.bold)),
Text(
'${_prixEstime.toStringAsFixed(0)} FCFA',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: theme.primaryColor,
// Rappel formule sélectionnée
_FormulaRecap(
codeFormule: widget.codeFormule,
plage: widget.plage,
prixMensuel: _formule?.prixMensuel ?? 0,
),
const SizedBox(height: 24),
OnboardingSectionTitle(
icon: Icons.calendar_month_outlined,
title: 'Choisissez votre période',
),
const SizedBox(height: 12),
..._periodes.map((p) => _PeriodeCard(
periode: p,
selected: _selectedPeriode == p.code,
prixTotal: _estimerPrix(p.code),
onTap: () => setState(() => _selectedPeriode = p.code),
)),
const SizedBox(height: 24),
// Total estimé
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
borderRadius: BorderRadius.circular(16),
boxShadow: UnionFlowColors.greenGlowShadow,
),
child: Row(
children: [
const Icon(Icons.calculate_outlined,
color: Colors.white70, size: 22),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Estimation indicative',
style: TextStyle(
color: Colors.white.withOpacity(0.8),
fontSize: 12,
),
),
const SizedBox(height: 2),
const Text(
'Le montant exact est calculé par le système.',
style: TextStyle(
color: Colors.white70, fontSize: 11),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
_formatPrix(prixSelected),
style: const TextStyle(
color: Colors.white,
fontSize: 22,
fontWeight: FontWeight.w900,
),
),
const Text(
'FCFA',
style:
TextStyle(color: Colors.white70, fontSize: 12),
),
],
),
],
),
),
const SizedBox(height: 16),
// Note info
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: UnionFlowColors.infoPale,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: UnionFlowColors.info.withOpacity(0.2)),
),
child: const Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(Icons.info_outline,
color: UnionFlowColors.info, size: 18),
SizedBox(width: 10),
Expanded(
child: Text(
'Le type de votre organisation et le coefficient tarifaire exact sont déterminés lors de la création de votre compte. Le récapitulatif final vous montrera le montant précis.',
style: TextStyle(
fontSize: 12,
color: UnionFlowColors.info,
height: 1.4),
),
),
],
),
),
],
),
),
const SizedBox(height: 32),
],
),
),
],
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton(
onPressed: () {
context.read<OnboardingBloc>()
..add(OnboardingPeriodeSelected(
typePeriode: _selectedPeriode,
typeOrganisation: _selectedTypeOrg,
organisationId: _organisationId,
))
..add(const OnboardingDemandeConfirmee());
},
style: ElevatedButton.styleFrom(minimumSize: const Size.fromHeight(48)),
child: const Text('Voir le récapitulatif'),
),
bottomNavigationBar: OnboardingBottomBar(
enabled: true,
label: 'Voir le récapitulatif',
onPressed: () {
context.read<OnboardingBloc>()
..add(OnboardingPeriodeSelected(
typePeriode: _selectedPeriode,
typeOrganisation: '',
organisationId: _organisationId,
))
..add(const OnboardingDemandeConfirmee());
},
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) return '${(prix / 1000000).toStringAsFixed(1)} M';
if (prix >= 1000) {
final parts = prix.toStringAsFixed(0);
if (parts.length > 3) {
return '${parts.substring(0, parts.length - 3)} ${parts.substring(parts.length - 3)}';
}
}
return prix.toStringAsFixed(0);
}
}
class _StepIndicator extends StatelessWidget {
final int current;
final int total;
const _StepIndicator({required this.current, required this.total});
class _Periode {
final String code, label, duree;
final String? badge;
final int nbMois;
final double coef;
const _Periode(this.code, this.label, this.duree, this.badge, this.nbMois, this.coef);
}
class _FormulaRecap extends StatelessWidget {
final String codeFormule;
final String plage;
final double prixMensuel;
const _FormulaRecap({
required this.codeFormule,
required this.plage,
required this.prixMensuel,
});
static const _plageLabels = {
'PETITE': '1100 membres',
'MOYENNE': '101500 membres',
'GRANDE': '5012 000 membres',
'TRES_GRANDE': '2 000+ membres',
};
@override
Widget build(BuildContext context) {
return Row(
children: List.generate(total, (i) {
final active = i + 1 <= current;
return Expanded(
child: Container(
height: 4,
margin: EdgeInsets.only(right: i < total - 1 ? 4 : 0),
decoration: BoxDecoration(
color: active ? Theme.of(context).primaryColor : Colors.grey[300],
borderRadius: BorderRadius.circular(2),
return Container(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
decoration: BoxDecoration(
color: UnionFlowColors.unionGreenPale,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: UnionFlowColors.unionGreen.withOpacity(0.25)),
),
child: Row(
children: [
const Icon(Icons.check_circle_rounded,
color: UnionFlowColors.unionGreen, size: 20),
const SizedBox(width: 10),
Expanded(
child: RichText(
text: TextSpan(
style: const TextStyle(
color: UnionFlowColors.textPrimary, fontSize: 13),
children: [
TextSpan(
text: 'Formule $codeFormule',
style: const TextStyle(fontWeight: FontWeight.w700),
),
const TextSpan(text: ' · '),
TextSpan(
text: _plageLabels[plage] ?? plage,
style: const TextStyle(
color: UnionFlowColors.textSecondary),
),
],
),
),
),
);
}),
Text(
'${_formatPrix(prixMensuel)} FCFA/mois',
style: const TextStyle(
color: UnionFlowColors.unionGreen,
fontWeight: FontWeight.w700,
fontSize: 13,
),
),
],
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000) {
final k = (prix / 1000).toStringAsFixed(0);
return '$k 000';
}
return prix.toStringAsFixed(0);
}
}
class _PeriodeCard extends StatelessWidget {
final _Periode periode;
final bool selected;
final double prixTotal;
final VoidCallback onTap;
const _PeriodeCard({
required this.periode,
required this.selected,
required this.prixTotal,
required this.onTap,
});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: selected ? UnionFlowColors.unionGreenPale : UnionFlowColors.surface,
border: Border.all(
color: selected ? UnionFlowColors.unionGreen : UnionFlowColors.border,
width: selected ? 2 : 1,
),
borderRadius: BorderRadius.circular(14),
boxShadow: selected ? UnionFlowColors.greenGlowShadow : UnionFlowColors.softShadow,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
Icon(
selected ? Icons.check_circle_rounded : Icons.radio_button_unchecked,
color: selected ? UnionFlowColors.unionGreen : UnionFlowColors.border,
size: 22,
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
periode.label,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 15,
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.textPrimary,
),
),
if (periode.badge != null) ...[
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: UnionFlowColors.successPale,
borderRadius: BorderRadius.circular(20),
),
child: Text(
periode.badge!,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w700,
color: UnionFlowColors.success,
),
),
),
],
],
),
Text(
periode.duree,
style: const TextStyle(
fontSize: 12,
color: UnionFlowColors.textSecondary),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'~ ${_formatPrix(prixTotal)}',
style: TextStyle(
fontWeight: FontWeight.w800,
fontSize: 15,
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.textPrimary,
),
),
const Text(
'FCFA',
style: TextStyle(
fontSize: 11,
color: UnionFlowColors.textSecondary),
),
],
),
],
),
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) return '${(prix / 1000000).toStringAsFixed(1)} M';
if (prix >= 1000) {
final s = prix.toStringAsFixed(0);
if (s.length > 3) {
return '${s.substring(0, s.length - 3)} ${s.substring(s.length - 3)}';
}
}
return prix.toStringAsFixed(0);
}
}

View File

@@ -2,8 +2,10 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/formule_model.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
import 'onboarding_shared_widgets.dart';
/// Étape 1 — Choix de la formule (BASIC / STANDARD / PREMIUM) et de la plage de membres
/// Étape 1 — Choix de la taille de l'organisation et du niveau de formule
class PlanSelectionPage extends StatefulWidget {
final List<FormuleModel> formules;
const PlanSelectionPage({super.key, required this.formules});
@@ -17,121 +19,214 @@ class _PlanSelectionPageState extends State<PlanSelectionPage> {
String? _selectedFormule;
static const _plages = [
('PETITE', 'Petite', '1100 membres'),
('MOYENNE', 'Moyenne', '101500 membres'),
('GRANDE', 'Grande', '5012 000 membres'),
('TRES_GRANDE', 'Très grande', '2 000+ membres'),
_Plage('PETITE', 'Petite', '1 100 membres', Icons.group_outlined, 'Associations naissantes et petites structures'),
_Plage('MOYENNE', 'Moyenne', '101 500 membres', Icons.groups_outlined, 'Associations établies en croissance'),
_Plage('GRANDE', 'Grande', '501 2 000 membres', Icons.corporate_fare_outlined, 'Grandes organisations régionales'),
_Plage('TRES_GRANDE', 'Très grande', '2 000+ membres', Icons.account_balance_outlined, 'Fédérations et réseaux nationaux'),
];
static const _formules = [
('BASIC', 'Basic', Icons.star_outline, Color(0xFF1976D2)),
('STANDARD', 'Standard', Icons.star_half, Color(0xFF388E3C)),
('PREMIUM', 'Premium', Icons.star, Color(0xFFF57C00)),
];
static const _formuleColors = {
'BASIC': UnionFlowColors.unionGreen,
'STANDARD': UnionFlowColors.gold,
'PREMIUM': UnionFlowColors.indigo,
};
static const _formuleIcons = {
'BASIC': Icons.star_border_rounded,
'STANDARD': Icons.star_half_rounded,
'PREMIUM': Icons.star_rounded,
};
static const _formuleFeatures = {
'BASIC': ['Gestion des membres', 'Cotisations de base', 'Rapports mensuels', 'Support email'],
'STANDARD': ['Tout Basic +', 'Événements & solidarité', 'Communication interne', 'Tableaux de bord avancés', 'Support prioritaire'],
'PREMIUM': ['Tout Standard +', 'Multi-organisations', 'Analytics temps réel', 'API ouverte', 'Support dédié 24/7'],
};
List<FormuleModel> get _filteredFormules => widget.formules
.where((f) => _selectedPlage == null || f.plage == _selectedPlage)
.toList()
..sort((a, b) => a.ordreAffichage.compareTo(b.ordreAffichage));
FormuleModel? get _selectedFormuleModel => _filteredFormules
.where((f) => f.code == _selectedFormule && f.plage == _selectedPlage)
.firstOrNull;
bool get _canProceed => _selectedPlage != null && _selectedFormule != null;
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const Text('Choisir votre formule'),
automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Indicateur d'étapes
_StepIndicator(current: 1, total: 3),
const SizedBox(height: 24),
Text('Taille de votre organisation',
style: theme.textTheme.titleMedium),
const SizedBox(height: 8),
// Sélecteur de plage
Wrap(
spacing: 8,
runSpacing: 8,
children: _plages.map((p) {
final (code, label, sublabel) = p;
final selected = _selectedPlage == code;
return ChoiceChip(
label: Column(
children: [
Text(label,
style: TextStyle(
fontWeight: FontWeight.bold,
color: selected ? Colors.white : null)),
Text(sublabel,
style: TextStyle(
fontSize: 11,
color: selected
? Colors.white70
: Colors.grey[600])),
],
backgroundColor: UnionFlowColors.background,
body: Column(
children: [
OnboardingStepHeader(
step: 1,
total: 3,
title: 'Choisissez votre formule',
subtitle: 'Sélectionnez la taille de votre organisation\npuis le niveau d\'abonnement adapté.',
),
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 8, 20, 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// Step 1a: Taille de l'organisation
OnboardingSectionTitle(
icon: Icons.people_alt_outlined,
title: 'Taille de votre organisation',
),
selected: selected,
onSelected: (_) => setState(() {
_selectedPlage = code;
_selectedFormule = null;
}),
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
);
}).toList(),
),
const SizedBox(height: 12),
...(_plages.map((p) => _PlageCard(
plage: p,
selected: _selectedPlage == p.code,
onTap: () => setState(() {
_selectedPlage = p.code;
_selectedFormule = null;
}),
))),
if (_selectedPlage != null) ...[
const SizedBox(height: 24),
Text('Niveau de formule', style: theme.textTheme.titleMedium),
const SizedBox(height: 8),
// Cartes de formules
..._formules.map((f) {
final (code, label, icon, color) = f;
final formule = _filteredFormules
.where((fm) => fm.code == code)
.firstOrNull;
if (formule == null) return const SizedBox.shrink();
final selected = _selectedFormule == code;
return _FormuleCard(
formule: formule,
label: label,
icon: icon,
color: color,
selected: selected,
onTap: () => setState(() => _selectedFormule = code),
);
}),
],
const SizedBox(height: 32),
],
if (_selectedPlage != null) ...[
const SizedBox(height: 28),
OnboardingSectionTitle(
icon: Icons.workspace_premium_outlined,
title: 'Niveau d\'abonnement',
),
const SizedBox(height: 12),
..._filteredFormules.map((f) => _FormuleCard(
formule: f,
color: _formuleColors[f.code] ?? UnionFlowColors.unionGreen,
icon: _formuleIcons[f.code] ?? Icons.star_border_rounded,
features: _formuleFeatures[f.code] ?? [],
selected: _selectedFormule == f.code,
onTap: () => setState(() => _selectedFormule = f.code),
)),
],
],
),
),
),
],
),
bottomNavigationBar: OnboardingBottomBar(
enabled: _canProceed,
label: 'Choisir la période',
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingFormuleSelected(
codeFormule: _selectedFormule!,
plage: _selectedPlage!,
),
),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton(
onPressed: _selectedPlage != null && _selectedFormule != null
? () => context.read<OnboardingBloc>().add(
OnboardingFormuleSelected(
codeFormule: _selectedFormule!,
plage: _selectedPlage!,
),
)
: null,
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(48),
);
}
}
// ─── Widgets locaux ──────────────────────────────────────────────────────────
class _Plage {
final String code, label, sublabel, description;
final IconData icon;
const _Plage(this.code, this.label, this.sublabel, this.icon, this.description);
}
class _PlageCard extends StatelessWidget {
final _Plage plage;
final bool selected;
final VoidCallback onTap;
const _PlageCard({required this.plage, required this.selected, required this.onTap});
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
margin: const EdgeInsets.only(bottom: 10),
decoration: BoxDecoration(
color: selected ? UnionFlowColors.unionGreenPale : UnionFlowColors.surface,
border: Border.all(
color: selected ? UnionFlowColors.unionGreen : UnionFlowColors.border,
width: selected ? 2 : 1,
),
borderRadius: BorderRadius.circular(14),
boxShadow: selected ? UnionFlowColors.greenGlowShadow : UnionFlowColors.softShadow,
),
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: BoxDecoration(
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.unionGreenPale,
borderRadius: BorderRadius.circular(10),
),
child: Icon(plage.icon,
color: selected ? Colors.white : UnionFlowColors.unionGreen,
size: 22),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
plage.label,
style: TextStyle(
fontWeight: FontWeight.w700,
fontSize: 15,
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.textPrimary,
),
),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: selected
? UnionFlowColors.unionGreen.withOpacity(0.15)
: UnionFlowColors.surfaceVariant,
borderRadius: BorderRadius.circular(20),
),
child: Text(
plage.sublabel,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.textSecondary,
),
),
),
],
),
const SizedBox(height: 2),
Text(
plage.description,
style: const TextStyle(
fontSize: 12,
color: UnionFlowColors.textSecondary),
),
],
),
),
Icon(
selected
? Icons.check_circle_rounded
: Icons.radio_button_unchecked,
color: selected
? UnionFlowColors.unionGreen
: UnionFlowColors.border,
size: 22,
),
],
),
child: const Text('Continuer'),
),
),
);
@@ -140,17 +235,17 @@ class _PlanSelectionPageState extends State<PlanSelectionPage> {
class _FormuleCard extends StatelessWidget {
final FormuleModel formule;
final String label;
final IconData icon;
final Color color;
final IconData icon;
final List<String> features;
final bool selected;
final VoidCallback onTap;
const _FormuleCard({
required this.formule,
required this.label,
required this.icon,
required this.color,
required this.icon,
required this.features,
required this.selected,
required this.onTap,
});
@@ -161,92 +256,125 @@ class _FormuleCard extends StatelessWidget {
onTap: onTap,
child: AnimatedContainer(
duration: const Duration(milliseconds: 200),
margin: const EdgeInsets.only(bottom: 8),
margin: const EdgeInsets.only(bottom: 12),
decoration: BoxDecoration(
color: selected ? color.withOpacity(0.1) : Colors.white,
color: UnionFlowColors.surface,
border: Border.all(
color: selected ? color : Colors.grey[300]!,
width: selected ? 2 : 1,
color: selected ? color : UnionFlowColors.border,
width: selected ? 2.5 : 1,
),
borderRadius: BorderRadius.circular(12),
borderRadius: BorderRadius.circular(16),
boxShadow: selected
? [
BoxShadow(
color: color.withOpacity(0.2),
blurRadius: 20,
offset: const Offset(0, 8),
)
]
: UnionFlowColors.softShadow,
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
Icon(icon, color: color, size: 28),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(label,
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: selected ? color : null)),
if (formule.description != null)
Text(formule.description!,
style: const TextStyle(fontSize: 12, color: Colors.grey)),
],
),
child: Column(
children: [
// Header
Container(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 14),
decoration: BoxDecoration(
color: selected ? color : color.withOpacity(0.06),
borderRadius: const BorderRadius.vertical(top: Radius.circular(14)),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
child: Row(
children: [
Text(
'${_formatPrix(formule.prixMensuel)} FCFA',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: color),
Icon(icon,
color: selected ? Colors.white : color, size: 24),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
formule.libelle,
style: TextStyle(
color: selected ? Colors.white : color,
fontWeight: FontWeight.w800,
fontSize: 16,
),
),
if (formule.description != null)
Text(
formule.description!,
style: TextStyle(
color: selected
? Colors.white70
: UnionFlowColors.textSecondary,
fontSize: 12,
),
),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
_formatPrix(formule.prixMensuel),
style: TextStyle(
color: selected ? Colors.white : color,
fontWeight: FontWeight.w900,
fontSize: 20,
),
),
Text(
'FCFA / mois',
style: TextStyle(
color: selected
? Colors.white70
: UnionFlowColors.textSecondary,
fontSize: 11,
),
),
],
),
const Text('/mois', style: TextStyle(fontSize: 11, color: Colors.grey)),
],
),
const SizedBox(width: 8),
Icon(
selected ? Icons.check_circle : Icons.radio_button_unchecked,
color: selected ? color : Colors.grey,
),
// Features
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 14),
child: Column(
children: features
.map((f) => Padding(
padding: const EdgeInsets.only(bottom: 6),
child: Row(
children: [
Icon(Icons.check_circle_outline_rounded,
size: 16, color: color),
const SizedBox(width: 8),
Text(f,
style: const TextStyle(
fontSize: 13,
color: UnionFlowColors.textPrimary)),
],
),
))
.toList(),
),
],
),
),
],
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) {
return '${(prix / 1000000).toStringAsFixed(1)} M';
}
if (prix >= 1000) {
return '${(prix / 1000).toStringAsFixed(0)} 000';
final k = (prix / 1000).toStringAsFixed(0);
return '$k 000';
}
return prix.toStringAsFixed(0);
}
}
class _StepIndicator extends StatelessWidget {
final int current;
final int total;
const _StepIndicator({required this.current, required this.total});
@override
Widget build(BuildContext context) {
return Row(
children: List.generate(total, (i) {
final active = i + 1 <= current;
return Expanded(
child: Container(
height: 4,
margin: EdgeInsets.only(right: i < total - 1 ? 4 : 0),
decoration: BoxDecoration(
color: active
? Theme.of(context).primaryColor
: Colors.grey[300],
borderRadius: BorderRadius.circular(2),
),
),
);
}),
);
}
}

View File

@@ -2,8 +2,9 @@ import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
/// Étape 3 — Récapitulatif avant paiement
/// Étape 3 — Récapitulatif détaillé avant paiement
class SubscriptionSummaryPage extends StatelessWidget {
final SouscriptionStatusModel souscription;
@@ -11,160 +12,507 @@ class SubscriptionSummaryPage extends StatelessWidget {
static const _periodeLabels = {
'MENSUEL': 'Mensuel',
'TRIMESTRIEL': 'Trimestriel (5%)',
'SEMESTRIEL': 'Semestriel (10%)',
'ANNUEL': 'Annuel (20%)',
'TRIMESTRIEL': 'Trimestriel',
'SEMESTRIEL': 'Semestriel',
'ANNUEL': 'Annuel',
};
static const _periodeRemises = {
'MENSUEL': null,
'TRIMESTRIEL': '5% de remise',
'SEMESTRIEL': '10% de remise',
'ANNUEL': '20% de remise',
};
static const _orgLabels = {
'ASSOCIATION': 'Association / ONG locale',
'MUTUELLE': 'Mutuelle',
'MUTUELLE': 'Mutuelle (santé, fonctionnaires…)',
'COOPERATIVE': 'Coopérative / Microfinance',
'FEDERATION': 'Fédération / Grande ONG',
};
static const _plageLabels = {
'PETITE': '1100 membres',
'MOYENNE': '101500 membres',
'GRANDE': '5012 000 membres',
'TRES_GRANDE': '2 000+ membres',
};
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final montant = souscription.montantTotal ?? 0;
final remise = _periodeRemises[souscription.typePeriode];
return Scaffold(
appBar: AppBar(
title: const Text('Récapitulatif de la souscription'),
automaticallyImplyLeading: false,
),
body: SingleChildScrollView(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
// En-tête
Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [theme.primaryColor, theme.primaryColor.withOpacity(0.7)],
backgroundColor: UnionFlowColors.background,
body: Column(
children: [
// Header hero
Container(
decoration: const BoxDecoration(
gradient: UnionFlowColors.primaryGradient,
),
child: SafeArea(
bottom: false,
child: Padding(
padding: const EdgeInsets.fromLTRB(20, 12, 20, 32),
child: Column(
children: [
// Step bar
Row(
children: List.generate(3, (i) => Expanded(
child: Container(
height: 4,
margin: EdgeInsets.only(right: i < 2 ? 6 : 0),
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(2),
),
),
)),
),
const SizedBox(height: 6),
Align(
alignment: Alignment.centerLeft,
child: Text(
'Étape 3 sur 3',
style: TextStyle(
color: Colors.white.withOpacity(0.75),
fontSize: 12,
fontWeight: FontWeight.w500,
),
),
),
const SizedBox(height: 20),
// Montant principal
Container(
width: 90,
height: 90,
decoration: BoxDecoration(
color: Colors.white.withOpacity(0.15),
shape: BoxShape.circle,
border: Border.all(
color: Colors.white.withOpacity(0.4), width: 2),
),
child: const Icon(Icons.receipt_long_rounded,
color: Colors.white, size: 44),
),
const SizedBox(height: 14),
Text(
_formatPrix(montant),
style: const TextStyle(
color: Colors.white,
fontSize: 40,
fontWeight: FontWeight.w900,
letterSpacing: -1,
),
),
const Text(
'FCFA à régler',
style: TextStyle(
color: Colors.white70,
fontSize: 14,
fontWeight: FontWeight.w500),
),
if (remise != null) ...[
const SizedBox(height: 8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: UnionFlowColors.gold.withOpacity(0.3),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: UnionFlowColors.goldLight.withOpacity(0.5)),
),
child: Text(
remise,
style: const TextStyle(
color: UnionFlowColors.goldLight,
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
],
],
),
borderRadius: BorderRadius.circular(16),
),
),
),
// Content
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(20, 20, 20, 100),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.receipt_long, color: Colors.white, size: 40),
const SizedBox(height: 8),
Text(
'${montant.toStringAsFixed(0)} FCFA',
style: const TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.bold,
// Organisation
if (souscription.organisationNom != null) ...[
_DetailCard(
title: 'Organisation',
icon: Icons.business_rounded,
iconColor: UnionFlowColors.indigo,
items: [
_DetailItem(
label: 'Nom',
value: souscription.organisationNom!,
bold: true),
_DetailItem(
label: 'Type',
value: _orgLabels[souscription.typeOrganisation] ??
souscription.typeOrganisation),
],
),
const SizedBox(height: 14),
],
// Formule
_DetailCard(
title: 'Formule souscrite',
icon: Icons.workspace_premium_rounded,
iconColor: UnionFlowColors.gold,
items: [
_DetailItem(
label: 'Niveau',
value: souscription.typeFormule,
bold: true),
_DetailItem(
label: 'Taille',
value: _plageLabels[souscription.plageMembres] ??
souscription.plageLibelle),
if (souscription.montantMensuelBase != null)
_DetailItem(
label: 'Prix de base',
value:
'${_formatPrix(souscription.montantMensuelBase!)} FCFA/mois'),
],
),
const SizedBox(height: 14),
// Facturation
_DetailCard(
title: 'Facturation',
icon: Icons.calendar_today_rounded,
iconColor: UnionFlowColors.unionGreen,
items: [
_DetailItem(
label: 'Période',
value:
_periodeLabels[souscription.typePeriode] ??
souscription.typePeriode),
if (souscription.coefficientApplique != null)
_DetailItem(
label: 'Coefficient',
value:
'×${souscription.coefficientApplique!.toStringAsFixed(4)}'),
if (souscription.dateDebut != null &&
souscription.dateFin != null) ...[
_DetailItem(
label: 'Début',
value: _formatDate(souscription.dateDebut!)),
_DetailItem(
label: 'Fin',
value: _formatDate(souscription.dateFin!)),
],
],
),
const SizedBox(height: 14),
// Montant total
Container(
padding: const EdgeInsets.all(18),
decoration: BoxDecoration(
color: UnionFlowColors.goldPale,
borderRadius: BorderRadius.circular(16),
border: Border.all(
color: UnionFlowColors.gold.withOpacity(0.4)),
boxShadow: UnionFlowColors.goldGlowShadow,
),
child: Row(
children: [
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
gradient: UnionFlowColors.goldGradient,
borderRadius: BorderRadius.circular(12),
),
child: const Icon(Icons.monetization_on_rounded,
color: Colors.white, size: 26),
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Total à payer',
style: TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 13),
),
Text(
'${_formatPrix(montant)} FCFA',
style: const TextStyle(
color: UnionFlowColors.textPrimary,
fontSize: 22,
fontWeight: FontWeight.w900,
),
),
],
),
),
],
),
),
Text(
'à régler par Wave Mobile Money',
style: TextStyle(color: Colors.white.withOpacity(0.85)),
const SizedBox(height: 20),
// Notes importantes
_NoteBox(
icon: Icons.security_rounded,
iconColor: UnionFlowColors.unionGreen,
backgroundColor: UnionFlowColors.unionGreenPale,
borderColor: UnionFlowColors.unionGreen.withOpacity(0.25),
title: 'Paiement sécurisé',
message:
'Votre paiement est traité de manière sécurisée via Wave Mobile Money. Une fois le paiement effectué, votre compte sera activé automatiquement.',
),
const SizedBox(height: 10),
_NoteBox(
icon: Icons.bolt_rounded,
iconColor: UnionFlowColors.amber,
backgroundColor: const Color(0xFFFFFBF0),
borderColor: UnionFlowColors.amber.withOpacity(0.3),
title: 'Activation immédiate',
message:
'Dès que le paiement est confirmé par Wave, votre compte d\'administrateur est activé et vous pouvez accéder à toutes les fonctionnalités de votre formule.',
),
const SizedBox(height: 10),
_NoteBox(
icon: Icons.support_agent_rounded,
iconColor: UnionFlowColors.info,
backgroundColor: UnionFlowColors.infoPale,
borderColor: UnionFlowColors.info.withOpacity(0.2),
title: 'Besoin d\'aide ?',
message:
'En cas de problème lors du paiement, contactez notre support à support@unionflow.app — nous vous répondrons sous 24h.',
),
],
),
),
const SizedBox(height: 24),
Text('Détails de votre souscription', style: theme.textTheme.titleMedium),
const SizedBox(height: 12),
_InfoRow(label: 'Organisation', value: souscription.organisationNom ?? ''),
_InfoRow(label: 'Formule', value: souscription.typeFormule),
_InfoRow(label: 'Plage de membres', value: souscription.plageLibelle),
_InfoRow(
label: 'Période',
value: _periodeLabels[souscription.typePeriode] ?? souscription.typePeriode,
),
],
),
bottomNavigationBar: Container(
padding: EdgeInsets.fromLTRB(
20, 12, 20, MediaQuery.of(context).padding.bottom + 12),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
boxShadow: [
BoxShadow(
color: Colors.black.withOpacity(0.08),
blurRadius: 12,
offset: const Offset(0, -4),
),
_InfoRow(
label: 'Type d\'organisation',
value: _orgLabels[souscription.typeOrganisation] ?? souscription.typeOrganisation,
),
if (souscription.coefficientApplique != null)
_InfoRow(
label: 'Coefficient appliqué',
value: '×${souscription.coefficientApplique!.toStringAsFixed(2)}',
),
const Divider(height: 32),
_InfoRow(
label: 'Total à payer',
value: '${montant.toStringAsFixed(0)} FCFA',
bold: true,
),
const SizedBox(height: 24),
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue[50],
borderRadius: BorderRadius.circular(8),
),
child: const Row(
children: [
Icon(Icons.info_outline, color: Colors.blue, size: 20),
SizedBox(width: 8),
Expanded(
child: Text(
'Vous allez être redirigé vers Wave pour effectuer le paiement. '
'Votre accès sera activé après validation par un administrateur.',
style: TextStyle(fontSize: 13, color: Colors.blue),
),
),
],
),
),
const SizedBox(height: 32),
],
),
),
bottomNavigationBar: Padding(
padding: const EdgeInsets.all(16),
child: ElevatedButton.icon(
onPressed: () =>
context.read<OnboardingBloc>().add(const OnboardingPaiementInitie()),
icon: const Icon(Icons.payment),
label: const Text('Payer avec Wave'),
style: ElevatedButton.styleFrom(
minimumSize: const Size.fromHeight(52),
backgroundColor: const Color(0xFF00B9F1), // Couleur Wave
foregroundColor: Colors.white,
child: SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () => context
.read<OnboardingBloc>()
.add(const OnboardingChoixPaiementOuvert()),
icon: const Icon(Icons.payment_rounded),
label: const Text(
'Choisir le moyen de paiement',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
shadowColor: UnionFlowColors.unionGreen.withOpacity(0.4),
elevation: 3,
),
),
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) return '${(prix / 1000000).toStringAsFixed(1)} M';
final s = prix.toStringAsFixed(0);
if (s.length > 6) {
return '${s.substring(0, s.length - 6)} ${s.substring(s.length - 6, s.length - 3)} ${s.substring(s.length - 3)}';
}
if (s.length > 3) {
return '${s.substring(0, s.length - 3)} ${s.substring(s.length - 3)}';
}
return s;
}
String _formatDate(DateTime date) {
return '${date.day.toString().padLeft(2, '0')}/${date.month.toString().padLeft(2, '0')}/${date.year}';
}
}
class _InfoRow extends StatelessWidget {
// ─── Widgets locaux ──────────────────────────────────────────────────────────
class _DetailItem {
final String label;
final String value;
final bool bold;
const _DetailItem(
{required this.label, required this.value, this.bold = false});
}
const _InfoRow({required this.label, required this.value, this.bold = false});
class _DetailCard extends StatelessWidget {
final String title;
final IconData icon;
final Color iconColor;
final List<_DetailItem> items;
const _DetailCard({
required this.title,
required this.icon,
required this.iconColor,
required this.items,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
return Container(
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(16),
boxShadow: UnionFlowColors.softShadow,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 160,
child: Text(label,
style: const TextStyle(color: Colors.grey, fontSize: 14)),
Padding(
padding: const EdgeInsets.fromLTRB(16, 14, 16, 10),
child: Row(
children: [
Container(
width: 34,
height: 34,
decoration: BoxDecoration(
color: iconColor.withOpacity(0.1),
borderRadius: BorderRadius.circular(8),
),
child: Icon(icon, color: iconColor, size: 18),
),
const SizedBox(width: 10),
Text(
title,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 14,
color: UnionFlowColors.textPrimary,
),
),
],
),
),
Expanded(
child: Text(
value,
style: TextStyle(
fontWeight: bold ? FontWeight.bold : FontWeight.normal,
fontSize: bold ? 16 : 14,
),
const Divider(height: 1, color: UnionFlowColors.border),
Padding(
padding: const EdgeInsets.fromLTRB(16, 12, 16, 14),
child: Column(
children: items.map((item) => Padding(
padding: const EdgeInsets.only(bottom: 8),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 120,
child: Text(
item.label,
style: const TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 13),
),
),
Expanded(
child: Text(
item.value,
style: TextStyle(
color: UnionFlowColors.textPrimary,
fontSize: 13,
fontWeight: item.bold
? FontWeight.w700
: FontWeight.w500,
),
),
),
],
),
)).toList(),
),
),
],
),
);
}
}
class _NoteBox extends StatelessWidget {
final IconData icon;
final Color iconColor;
final Color backgroundColor;
final Color borderColor;
final String title;
final String message;
const _NoteBox({
required this.icon,
required this.iconColor,
required this.backgroundColor,
required this.borderColor,
required this.title,
required this.message,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: backgroundColor,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: borderColor),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, color: iconColor, size: 20),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: TextStyle(
color: iconColor,
fontWeight: FontWeight.w700,
fontSize: 13,
),
),
const SizedBox(height: 3),
Text(
message,
style: const TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 12,
height: 1.5),
),
],
),
),
],

View File

@@ -3,6 +3,8 @@ import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../shared/design_system/tokens/unionflow_colors.dart';
import '../../../../core/config/environment.dart';
/// Étape 4 — Lancement du paiement Wave + attente du retour
class WavePaymentPage extends StatefulWidget {
@@ -23,6 +25,13 @@ class _WavePaymentPageState extends State<WavePaymentPage>
with WidgetsBindingObserver {
bool _paymentLaunched = false;
bool _appResumed = false;
bool _simulating = false;
/// En dev/mock, la session Wave ne peut pas s'ouvrir — on simule directement.
bool get _isMock =>
widget.waveLaunchUrl.contains('mock') ||
widget.waveLaunchUrl.contains('localhost') ||
!AppConfig.isProd;
@override
void initState() {
@@ -38,14 +47,24 @@ class _WavePaymentPageState extends State<WavePaymentPage>
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
// Quand l'utilisateur revient dans l'app après Wave
if (state == AppLifecycleState.resumed && _paymentLaunched && !_appResumed) {
_appResumed = true;
context.read<OnboardingBloc>().add(const OnboardingRetourDepuisWave());
}
}
Future<void> _lancerWave() async {
Future<void> _lancerOuSimuler() async {
if (_isMock) {
// Mode dev/mock : simuler le paiement directement
setState(() => _simulating = true);
await Future.delayed(const Duration(milliseconds: 800));
if (mounted) {
context.read<OnboardingBloc>().add(const OnboardingRetourDepuisWave());
}
return;
}
// Mode prod : ouvrir Wave
final uri = Uri.parse(widget.waveLaunchUrl);
if (await canLaunchUrl(uri)) {
setState(() => _paymentLaunched = true);
@@ -54,8 +73,10 @@ class _WavePaymentPageState extends State<WavePaymentPage>
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Impossible d\'ouvrir Wave. Vérifiez que l\'application est installée.'),
backgroundColor: Colors.red,
content: Text(
'Impossible d\'ouvrir Wave. Vérifiez que l\'application est installée.'),
backgroundColor: UnionFlowColors.error,
behavior: SnackBarBehavior.floating,
),
);
}
@@ -65,81 +86,344 @@ class _WavePaymentPageState extends State<WavePaymentPage>
@override
Widget build(BuildContext context) {
final montant = widget.souscription.montantTotal ?? 0;
const waveBlue = Color(0xFF00B9F1);
return Scaffold(
appBar: AppBar(
title: const Text('Paiement Wave'),
automaticallyImplyLeading: false,
),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Logo Wave stylisé
Container(
width: 100,
height: 100,
decoration: BoxDecoration(
color: const Color(0xFF00B9F1),
borderRadius: BorderRadius.circular(24),
backgroundColor: UnionFlowColors.background,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Row(
children: [
if (!_paymentLaunched && !_simulating)
IconButton(
onPressed: () => Navigator.of(context).maybePop(),
icon: const Icon(Icons.arrow_back_rounded),
color: UnionFlowColors.textSecondary,
),
const Spacer(),
if (_isMock)
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10, vertical: 4),
decoration: BoxDecoration(
color: UnionFlowColors.warningPale,
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: UnionFlowColors.warning.withOpacity(0.4)),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.science_rounded,
size: 13, color: UnionFlowColors.warning),
SizedBox(width: 4),
Text(
'Mode dev',
style: TextStyle(
color: UnionFlowColors.warning,
fontSize: 11,
fontWeight: FontWeight.w700,
),
),
],
),
)
else
Container(
padding: const EdgeInsets.symmetric(
horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: waveBlue.withOpacity(0.1),
borderRadius: BorderRadius.circular(20),
),
child: const Text(
'Wave Mobile Money',
style: TextStyle(
color: waveBlue,
fontSize: 12,
fontWeight: FontWeight.w700,
),
),
),
],
),
child: const Icon(Icons.waves, color: Colors.white, size: 52),
),
const SizedBox(height: 32),
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
if (_simulating) ...[
// Animation de simulation
Container(
width: 110,
height: 110,
decoration: BoxDecoration(
gradient: const LinearGradient(
colors: [Color(0xFF00B9F1), Color(0xFF0096C7)],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(28),
boxShadow: [
BoxShadow(
color: waveBlue.withOpacity(0.35),
blurRadius: 24,
offset: const Offset(0, 10),
),
],
),
child: const Center(
child: SizedBox(
width: 48,
height: 48,
child: CircularProgressIndicator(
color: Colors.white,
strokeWidth: 3,
),
),
),
),
const SizedBox(height: 28),
const Text(
'Simulation du paiement…',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
),
const SizedBox(height: 8),
const Text(
'Confirmation en cours',
style: TextStyle(
color: UnionFlowColors.textSecondary, fontSize: 14),
),
] else ...[
// Logo Wave
Container(
width: 110,
height: 110,
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.circular(28),
border: Border.all(color: UnionFlowColors.border),
boxShadow: [
BoxShadow(
color: waveBlue.withOpacity(0.2),
blurRadius: 24,
offset: const Offset(0, 10),
),
],
),
padding: const EdgeInsets.all(16),
child: Image.asset(
'assets/images/payment_methods/wave/logo.png',
fit: BoxFit.contain,
errorBuilder: (_, __, ___) => const Icon(
Icons.waves_rounded,
color: waveBlue,
size: 52,
),
),
),
const SizedBox(height: 28),
const Text(
'Paiement par Wave',
style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
Text(
'Montant : ${montant.toStringAsFixed(0)} FCFA',
style: const TextStyle(fontSize: 18, color: Colors.grey),
),
const SizedBox(height: 32),
Text(
_paymentLaunched
? 'Paiement en cours…'
: _isMock
? 'Simuler le paiement'
: 'Prêt à payer',
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w800,
color: UnionFlowColors.textPrimary,
),
),
const SizedBox(height: 8),
if (!_paymentLaunched) ...[
const Text(
'Cliquez sur le bouton ci-dessous pour ouvrir Wave et effectuer votre paiement.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
ElevatedButton.icon(
onPressed: _lancerWave,
icon: const Icon(Icons.open_in_new),
label: const Text('Ouvrir Wave'),
style: ElevatedButton.styleFrom(
minimumSize: const Size(200, 52),
backgroundColor: const Color(0xFF00B9F1),
foregroundColor: Colors.white,
// Montant
RichText(
text: TextSpan(
children: [
TextSpan(
text: '${_formatPrix(montant)} ',
style: const TextStyle(
fontSize: 32,
fontWeight: FontWeight.w900,
color: waveBlue,
letterSpacing: -0.5,
),
),
const TextSpan(
text: 'FCFA',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.w700,
color: UnionFlowColors.textSecondary,
),
),
],
),
),
if (widget.souscription.organisationNom != null) ...[
const SizedBox(height: 4),
Text(
widget.souscription.organisationNom!,
style: const TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 13),
),
],
const SizedBox(height: 32),
if (!_paymentLaunched) ...[
if (_isMock)
Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: UnionFlowColors.warningPale,
borderRadius: BorderRadius.circular(10),
border: Border.all(
color:
UnionFlowColors.warning.withOpacity(0.3)),
),
child: const Row(
children: [
Icon(Icons.science_outlined,
color: UnionFlowColors.warning, size: 16),
SizedBox(width: 8),
Expanded(
child: Text(
'Environnement de développement — le paiement sera simulé automatiquement.',
style: TextStyle(
fontSize: 12,
color: UnionFlowColors.warning,
height: 1.4),
),
),
],
),
),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: _lancerOuSimuler,
icon: Icon(_isMock
? Icons.play_circle_rounded
: Icons.open_in_new_rounded),
label: Text(
_isMock
? 'Simuler le paiement Wave'
: 'Ouvrir Wave',
style: const TextStyle(
fontSize: 16, fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: waveBlue,
foregroundColor: Colors.white,
padding:
const EdgeInsets.symmetric(vertical: 15),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
shadowColor: waveBlue.withOpacity(0.4),
elevation: 3,
),
),
),
] else ...[
// Paiement lancé en prod
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: UnionFlowColors.surface,
borderRadius: BorderRadius.circular(16),
boxShadow: UnionFlowColors.softShadow,
),
child: Column(
children: [
const SizedBox(
width: 40,
height: 40,
child: CircularProgressIndicator(
color: waveBlue,
strokeWidth: 3,
),
),
const SizedBox(height: 16),
const Text(
'Paiement en cours dans Wave',
style: TextStyle(
fontWeight: FontWeight.w700,
color: UnionFlowColors.textPrimary,
),
),
const SizedBox(height: 6),
const Text(
'Revenez dans l\'app une fois\nvotre paiement confirmé.',
textAlign: TextAlign.center,
style: TextStyle(
color: UnionFlowColors.textSecondary,
fontSize: 13,
height: 1.4),
),
],
),
),
const SizedBox(height: 20),
SizedBox(
width: double.infinity,
child: ElevatedButton.icon(
onPressed: () => context
.read<OnboardingBloc>()
.add(const OnboardingRetourDepuisWave()),
icon: const Icon(
Icons.check_circle_outline_rounded),
label: const Text(
'J\'ai effectué le paiement',
style: TextStyle(
fontSize: 15,
fontWeight: FontWeight.w700),
),
style: ElevatedButton.styleFrom(
backgroundColor: UnionFlowColors.unionGreen,
foregroundColor: Colors.white,
padding:
const EdgeInsets.symmetric(vertical: 14),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(14)),
),
),
),
const SizedBox(height: 10),
TextButton.icon(
onPressed: _lancerOuSimuler,
icon: const Icon(Icons.refresh_rounded, size: 18),
label: const Text('Rouvrir Wave'),
style: TextButton.styleFrom(
foregroundColor: waveBlue),
),
],
],
],
),
),
] else ...[
const Icon(Icons.hourglass_top, size: 40, color: Colors.orange),
const SizedBox(height: 16),
const Text(
'Paiement en cours dans Wave…\nRevenez ici une fois le paiement effectué.',
textAlign: TextAlign.center,
style: TextStyle(color: Colors.grey),
),
const SizedBox(height: 24),
OutlinedButton(
onPressed: () => context.read<OnboardingBloc>().add(
const OnboardingRetourDepuisWave(),
),
child: const Text('J\'ai effectué le paiement'),
),
const SizedBox(height: 12),
TextButton(
onPressed: _lancerWave,
child: const Text('Rouvrir Wave'),
),
],
],
),
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000000) return '${(prix / 1000000).toStringAsFixed(1)} M';
final s = prix.toStringAsFixed(0);
if (s.length > 3) {
return '${s.substring(0, s.length - 3)} ${s.substring(s.length - 3)}';
}
return s;
}
}

View File

@@ -0,0 +1,144 @@
/// BLoC pour le sélecteur d'organisation multi-org.
///
/// Charge GET /api/membres/mes-organisations et maintient
/// l'organisation active via [OrgContextService].
library org_switcher_bloc;
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:injectable/injectable.dart';
import 'package:dio/dio.dart';
import '../../../core/network/api_client.dart';
import '../../../core/network/org_context_service.dart';
import '../../../core/utils/logger.dart';
import '../data/models/org_switcher_entry.dart';
// ─── ÉVÉNEMENTS ─────────────────────────────────────────────────────────────
abstract class OrgSwitcherEvent extends Equatable {
const OrgSwitcherEvent();
@override
List<Object?> get props => [];
}
/// Charge la liste des organisations du membre connecté.
class OrgSwitcherLoadRequested extends OrgSwitcherEvent {
const OrgSwitcherLoadRequested();
}
/// Sélectionne une organisation comme active.
class OrgSwitcherSelectRequested extends OrgSwitcherEvent {
final OrgSwitcherEntry organisation;
const OrgSwitcherSelectRequested(this.organisation);
@override
List<Object?> get props => [organisation];
}
// ─── ÉTATS ──────────────────────────────────────────────────────────────────
abstract class OrgSwitcherState extends Equatable {
const OrgSwitcherState();
@override
List<Object?> get props => [];
}
class OrgSwitcherInitial extends OrgSwitcherState {}
class OrgSwitcherLoading extends OrgSwitcherState {}
class OrgSwitcherLoaded extends OrgSwitcherState {
final List<OrgSwitcherEntry> organisations;
final OrgSwitcherEntry? active;
const OrgSwitcherLoaded({required this.organisations, this.active});
OrgSwitcherLoaded copyWith({
List<OrgSwitcherEntry>? organisations,
OrgSwitcherEntry? active,
}) {
return OrgSwitcherLoaded(
organisations: organisations ?? this.organisations,
active: active ?? this.active,
);
}
@override
List<Object?> get props => [organisations, active];
}
class OrgSwitcherError extends OrgSwitcherState {
final String message;
const OrgSwitcherError(this.message);
@override
List<Object?> get props => [message];
}
// ─── BLOC ────────────────────────────────────────────────────────────────────
@injectable
class OrgSwitcherBloc extends Bloc<OrgSwitcherEvent, OrgSwitcherState> {
final ApiClient _apiClient;
final OrgContextService _orgContextService;
static const String _endpoint = '/api/membres/mes-organisations';
OrgSwitcherBloc(this._apiClient, this._orgContextService)
: super(OrgSwitcherInitial()) {
on<OrgSwitcherLoadRequested>(_onLoad);
on<OrgSwitcherSelectRequested>(_onSelect);
}
Future<void> _onLoad(
OrgSwitcherLoadRequested event,
Emitter<OrgSwitcherState> emit,
) async {
emit(OrgSwitcherLoading());
try {
final response = await _apiClient.get<List<dynamic>>(_endpoint);
final rawList = response.data as List<dynamic>? ?? [];
final orgs = rawList
.map((e) => OrgSwitcherEntry.fromJson(e as Map<String, dynamic>))
.toList();
// Auto-select si une seule organisation ou si une org est déjà active
OrgSwitcherEntry? active;
if (_orgContextService.hasContext) {
active = orgs.where((o) => o.organisationId == _orgContextService.activeOrganisationId).firstOrNull;
}
active ??= orgs.isNotEmpty ? orgs.first : null;
if (active != null && !_orgContextService.hasContext) {
_applyActiveOrg(active);
}
emit(OrgSwitcherLoaded(organisations: orgs, active: active));
} on DioException catch (e) {
AppLogger.warning('OrgSwitcherBloc: erreur réseau: ${e.message}');
emit(OrgSwitcherError('Impossible de charger vos organisations: ${e.message}'));
} catch (e) {
AppLogger.error('OrgSwitcherBloc: erreur inattendue: $e');
emit(OrgSwitcherError('Erreur inattendue: $e'));
}
}
Future<void> _onSelect(
OrgSwitcherSelectRequested event,
Emitter<OrgSwitcherState> emit,
) async {
final current = state;
if (current is! OrgSwitcherLoaded) return;
_applyActiveOrg(event.organisation);
emit(current.copyWith(active: event.organisation));
AppLogger.info('OrgSwitcherBloc: sélection → ${event.organisation.nom}');
}
void _applyActiveOrg(OrgSwitcherEntry org) {
_orgContextService.setActiveOrganisation(
organisationId: org.organisationId,
nom: org.nom,
type: org.typeOrganisation,
modulesActifsCsv: org.modulesActifs,
);
}
}

View File

@@ -0,0 +1,73 @@
/// Modèle pour un item du sélecteur d'organisation.
/// Mappé depuis GET /api/membres/mes-organisations.
library org_switcher_entry;
import 'package:equatable/equatable.dart';
class OrgSwitcherEntry extends Equatable {
final String organisationId;
final String nom;
final String? nomCourt;
final String typeOrganisation;
final String? categorieType;
final String? modulesActifs;
final String? statut;
final String? statutMembre;
final String? roleOrg;
final String? dateAdhesion;
const OrgSwitcherEntry({
required this.organisationId,
required this.nom,
this.nomCourt,
required this.typeOrganisation,
this.categorieType,
this.modulesActifs,
this.statut,
this.statutMembre,
this.roleOrg,
this.dateAdhesion,
});
/// Libellé court pour le switcher (nomCourt ou nom tronqué).
String get libelleCourt {
if (nomCourt != null && nomCourt!.isNotEmpty) return nomCourt!;
if (nom.length > 25) return '${nom.substring(0, 22)}';
return nom;
}
/// Modules actifs parsés en Set<String>.
Set<String> get modulesActifsSet {
if (modulesActifs == null || modulesActifs!.isEmpty) return {};
return modulesActifs!.split(',').map((m) => m.trim()).toSet();
}
factory OrgSwitcherEntry.fromJson(Map<String, dynamic> json) {
return OrgSwitcherEntry(
organisationId: json['organisationId']?.toString() ?? '',
nom: json['nom']?.toString() ?? '',
nomCourt: json['nomCourt']?.toString(),
typeOrganisation: json['typeOrganisation']?.toString() ?? '',
categorieType: json['categorieType']?.toString(),
modulesActifs: json['modulesActifs']?.toString(),
statut: json['statut']?.toString(),
statutMembre: json['statutMembre']?.toString(),
roleOrg: json['roleOrg']?.toString(),
dateAdhesion: json['dateAdhesion']?.toString(),
);
}
@override
List<Object?> get props => [
organisationId,
nom,
nomCourt,
typeOrganisation,
categorieType,
modulesActifs,
statut,
statutMembre,
roleOrg,
dateAdhesion,
];
}

View File

@@ -0,0 +1,384 @@
/// Page de sélection d'organisation pour les membres multi-org.
///
/// S'affiche après la connexion si le membre appartient à plusieurs organisations,
/// ou accessible depuis le profil pour changer d'organisation active.
library org_selector_page;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/org_switcher_bloc.dart';
import '../../data/models/org_switcher_entry.dart';
class OrgSelectorPage extends StatefulWidget {
/// Si true, la page ne peut pas être ignorée (premier choix obligatoire).
final bool required;
const OrgSelectorPage({super.key, this.required = false});
@override
State<OrgSelectorPage> createState() => _OrgSelectorPageState();
}
class _OrgSelectorPageState extends State<OrgSelectorPage> {
@override
void initState() {
super.initState();
context.read<OrgSwitcherBloc>().add(const OrgSwitcherLoadRequested());
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
appBar: AppBar(
title: const Text('Choisir une organisation'),
automaticallyImplyLeading: !widget.required,
elevation: 0,
),
body: BlocConsumer<OrgSwitcherBloc, OrgSwitcherState>(
listener: (context, state) {
if (state is OrgSwitcherLoaded && widget.required && state.active != null) {
// Une org a été auto-sélectionnée, on peut continuer
}
},
builder: (context, state) {
if (state is OrgSwitcherLoading) {
return const Center(child: CircularProgressIndicator());
}
if (state is OrgSwitcherError) {
return _ErrorView(
message: state.message,
onRetry: () => context
.read<OrgSwitcherBloc>()
.add(const OrgSwitcherLoadRequested()),
);
}
if (state is OrgSwitcherLoaded) {
if (state.organisations.isEmpty) {
return const _EmptyView();
}
return _OrgList(
organisations: state.organisations,
active: state.active,
onSelect: (org) {
context
.read<OrgSwitcherBloc>()
.add(OrgSwitcherSelectRequested(org));
Navigator.of(context).pop(org);
},
);
}
return const SizedBox.shrink();
},
),
);
}
}
// ─── Widgets privés ──────────────────────────────────────────────────────────
class _OrgList extends StatelessWidget {
final List<OrgSwitcherEntry> organisations;
final OrgSwitcherEntry? active;
final ValueChanged<OrgSwitcherEntry> onSelect;
const _OrgList({
required this.organisations,
required this.active,
required this.onSelect,
});
@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Padding(
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
child: Text(
'Sélectionnez l\'organisation dans laquelle vous souhaitez travailler.',
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
color: Theme.of(context).colorScheme.onSurfaceVariant,
),
),
),
Expanded(
child: ListView.separated(
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
itemCount: organisations.length,
separatorBuilder: (_, __) => const SizedBox(height: 8),
itemBuilder: (context, index) {
final org = organisations[index];
final isActive = active?.organisationId == org.organisationId;
return _OrgCard(
org: org,
isActive: isActive,
onTap: () => onSelect(org),
);
},
),
),
],
);
}
}
class _OrgCard extends StatelessWidget {
final OrgSwitcherEntry org;
final bool isActive;
final VoidCallback onTap;
const _OrgCard({
required this.org,
required this.isActive,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
return Card(
elevation: isActive ? 3 : 1,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
side: isActive
? BorderSide(color: colorScheme.primary, width: 2)
: BorderSide.none,
),
color: isActive
? colorScheme.primaryContainer.withValues(alpha: 0.3)
: colorScheme.surface,
child: InkWell(
onTap: onTap,
borderRadius: BorderRadius.circular(12),
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
children: [
// Icône / avatar
Container(
width: 48,
height: 48,
decoration: BoxDecoration(
color: isActive
? colorScheme.primary
: colorScheme.surfaceContainerHighest,
borderRadius: BorderRadius.circular(12),
),
alignment: Alignment.center,
child: Text(
org.nom.isNotEmpty ? org.nom[0].toUpperCase() : '?',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 20,
color: isActive ? colorScheme.onPrimary : colorScheme.onSurfaceVariant,
),
),
),
const SizedBox(width: 12),
// Informations
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
org.libelleCourt,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.w600,
color: isActive ? colorScheme.primary : null,
),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
const SizedBox(height: 4),
Row(
children: [
_Chip(org.typeOrganisation),
if (org.statutMembre != null) ...[
const SizedBox(width: 6),
_Chip(
org.statutMembre!,
color: org.statutMembre == 'ACTIF'
? Colors.green.shade700
: Colors.orange.shade700,
),
],
],
),
if (org.roleOrg != null) ...[
const SizedBox(height: 2),
Text(
org.roleOrg!,
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: colorScheme.onSurfaceVariant,
),
),
],
],
),
),
if (isActive)
Icon(Icons.check_circle, color: colorScheme.primary, size: 24),
],
),
),
),
);
}
}
class _Chip extends StatelessWidget {
final String label;
final Color? color;
const _Chip(this.label, {this.color});
@override
Widget build(BuildContext context) {
final effectiveColor = color ?? Theme.of(context).colorScheme.onSurfaceVariant;
return Container(
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
decoration: BoxDecoration(
color: effectiveColor.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(4),
),
child: Text(
label,
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w500,
color: effectiveColor,
),
),
);
}
}
class _ErrorView extends StatelessWidget {
final String message;
final VoidCallback onRetry;
const _ErrorView({required this.message, required this.onRetry});
@override
Widget build(BuildContext context) {
return Center(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.cloud_off, size: 56, color: Colors.grey),
const SizedBox(height: 16),
Text(message, textAlign: TextAlign.center),
const SizedBox(height: 16),
ElevatedButton.icon(
onPressed: onRetry,
icon: const Icon(Icons.refresh),
label: const Text('Réessayer'),
),
],
),
),
);
}
}
class _EmptyView extends StatelessWidget {
const _EmptyView();
@override
Widget build(BuildContext context) {
return const Center(
child: Padding(
padding: EdgeInsets.all(24),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.business_outlined, size: 56, color: Colors.grey),
SizedBox(height: 16),
Text(
'Vous n\'êtes membre d\'aucune organisation active.',
textAlign: TextAlign.center,
),
],
),
),
);
}
}
/// Widget compact pour afficher/changer l'org active dans une AppBar ou drawer.
///
/// Usage:
/// ```dart
/// OrgSwitcherBadge(onTap: () => _openOrgSelector(context))
/// ```
class OrgSwitcherBadge extends StatelessWidget {
final OrgSwitcherEntry? activeOrg;
final VoidCallback onTap;
const OrgSwitcherBadge({
super.key,
required this.activeOrg,
required this.onTap,
});
@override
Widget build(BuildContext context) {
final colorScheme = Theme.of(context).colorScheme;
final label = activeOrg?.libelleCourt ?? 'Choisir organisation';
return GestureDetector(
onTap: onTap,
child: Container(
constraints: const BoxConstraints(maxWidth: 200),
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6),
decoration: BoxDecoration(
color: colorScheme.primaryContainer.withValues(alpha: 0.4),
borderRadius: BorderRadius.circular(20),
border: Border.all(
color: colorScheme.primary.withValues(alpha: 0.4),
),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.business, size: 16, color: colorScheme.primary),
const SizedBox(width: 6),
Flexible(
child: Text(
label,
style: TextStyle(
fontSize: 13,
fontWeight: FontWeight.w600,
color: colorScheme.primary,
),
overflow: TextOverflow.ellipsis,
),
),
const SizedBox(width: 4),
Icon(Icons.arrow_drop_down, size: 18, color: colorScheme.primary),
],
),
),
);
}
}
/// Ouvre [OrgSelectorPage] comme bottom sheet modal.
///
/// Retourne l'[OrgSwitcherEntry] sélectionnée ou null si annulé.
Future<OrgSwitcherEntry?> showOrgSelector(
BuildContext context, {
bool required = false,
}) {
return Navigator.of(context).push<OrgSwitcherEntry>(
MaterialPageRoute(
builder: (_) => BlocProvider.value(
value: context.read<OrgSwitcherBloc>(),
child: OrgSelectorPage(required: required),
),
),
);
}

View File

@@ -605,6 +605,12 @@ class _OrganizationsPageState extends State<OrganizationsPage> with TickerProvid
return _buildEmptyState();
}
// Vérifier le rôle une seule fois pour toute la liste (UI-02)
final authState = context.read<AuthBloc>().state;
final canManageOrgs = authState is AuthAuthenticated &&
(authState.effectiveRole == UserRole.superAdmin ||
authState.effectiveRole == UserRole.orgAdmin);
return ListView.separated(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
@@ -617,9 +623,9 @@ class _OrganizationsPageState extends State<OrganizationsPage> with TickerProvid
child: OrganizationCard(
organization: org,
onTap: () => _showOrganizationDetails(org),
onEdit: () => _showEditOrganizationDialog(org),
onDelete: () => _confirmDeleteOrganization(org),
showActions: true,
onEdit: canManageOrgs ? () => _showEditOrganizationDialog(org) : null,
onDelete: canManageOrgs ? () => _confirmDeleteOrganization(org) : null,
showActions: canManageOrgs,
),
);
},

View File

@@ -175,10 +175,10 @@ class ProfileRepositoryImpl implements IProfileRepository {
@override
Future<void> changePassword(String id, String oldPassword, String newPassword) async {
try {
// Appel direct à l'API Keycloak pour changer le mot de passe
// Via l'endpoint /api/auth/change-password qui proxy vers Keycloak
// Changement de mot de passe via l'API UnionFlow
// Endpoint: POST /api/membres/auth/change-password (direct Keycloak Admin)
final response = await _apiClient.post(
'/api/auth/change-password',
'/api/membres/auth/change-password',
data: {
'userId': id,
'oldPassword': oldPassword,

View File

@@ -17,6 +17,8 @@ import '../../../../core/l10n/locale_provider.dart';
import '../../../../core/theme/theme_provider.dart';
import '../../../authentication/presentation/bloc/auth_bloc.dart';
import '../../../members/data/models/membre_complete_model.dart';
import '../../../organizations/bloc/org_switcher_bloc.dart';
import '../../../organizations/presentation/pages/org_selector_page.dart';
import '../../../settings/presentation/pages/language_settings_page.dart';
import '../../../settings/presentation/pages/privacy_settings_page.dart';
import '../../../settings/presentation/pages/feedback_page.dart';
@@ -309,6 +311,31 @@ class _ProfilePageState extends State<ProfilePage>
_buildStatItem('ORG', orgValue),
],
),
// Sélecteur d'organisation (multi-org)
BlocBuilder<OrgSwitcherBloc, OrgSwitcherState>(
builder: (context, orgState) {
if (orgState is! OrgSwitcherLoaded ||
orgState.organisations.length <= 1) {
return const SizedBox.shrink();
}
return Padding(
padding: const EdgeInsets.only(top: 12),
child: Center(
child: OrgSwitcherBadge(
activeOrg: orgState.active,
onTap: () async {
final selected = await showOrgSelector(context);
if (selected != null && context.mounted) {
context
.read<OrgSwitcherBloc>()
.add(OrgSwitcherSelectRequested(selected));
}
},
),
),
);
},
),
],
),
);

View File

@@ -3,17 +3,26 @@ library profile_page_wrapper;
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../../core/di/injection_container.dart';
import '../../../organizations/bloc/org_switcher_bloc.dart';
import '../bloc/profile_bloc.dart';
import 'profile_page.dart';
/// Wrapper qui fournit le ProfileBloc à la ProfilePage
/// Wrapper qui fournit le ProfileBloc et OrgSwitcherBloc à la ProfilePage.
class ProfilePageWrapper extends StatelessWidget {
const ProfilePageWrapper({super.key});
@override
Widget build(BuildContext context) {
return BlocProvider<ProfileBloc>(
create: (_) => sl<ProfileBloc>(),
return MultiBlocProvider(
providers: [
BlocProvider<ProfileBloc>(
create: (_) => sl<ProfileBloc>(),
),
BlocProvider<OrgSwitcherBloc>(
create: (_) => sl<OrgSwitcherBloc>()
..add(const OrgSwitcherLoadRequested()),
),
],
child: const ProfilePage(),
);
}