refactoring

This commit is contained in:
dahoud
2026-03-31 09:14:47 +00:00
parent 9bfffeeebe
commit 5383df6dcb
200 changed files with 11192 additions and 7063 deletions

View File

@@ -0,0 +1,292 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:injectable/injectable.dart';
import '../data/datasources/souscription_datasource.dart';
import '../data/models/formule_model.dart';
import '../data/models/souscription_status_model.dart';
import '../../../../core/utils/logger.dart';
// ─────────────────────────────────────────────────────────────── Events ──────
abstract class OnboardingEvent extends Equatable {
const OnboardingEvent();
@override
List<Object?> get props => [];
}
/// Démarre le workflow (charge les formules + état courant si souscription existante)
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});
@override
List<Object?> get props => [initialState, existingSouscriptionId];
}
/// L'utilisateur a sélectionné une formule et une plage
class OnboardingFormuleSelected extends OnboardingEvent {
final String codeFormule;
final String plage;
const OnboardingFormuleSelected({required this.codeFormule, required this.plage});
@override
List<Object?> get props => [codeFormule, plage];
}
/// L'utilisateur a sélectionné la période et le type d'organisation
class OnboardingPeriodeSelected extends OnboardingEvent {
final String typePeriode;
final String typeOrganisation;
final String organisationId;
const OnboardingPeriodeSelected({
required this.typePeriode,
required this.typeOrganisation,
required this.organisationId,
});
@override
List<Object?> get props => [typePeriode, typeOrganisation, organisationId];
}
/// Confirme la demande et crée la souscription en base
class OnboardingDemandeConfirmee extends OnboardingEvent {
const OnboardingDemandeConfirmee();
}
/// Initie le paiement Wave
class OnboardingPaiementInitie extends OnboardingEvent {
const OnboardingPaiementInitie();
}
/// L'utilisateur est revenu dans l'app après le paiement Wave
class OnboardingRetourDepuisWave extends OnboardingEvent {
const OnboardingRetourDepuisWave();
}
// ─────────────────────────────────────────────────────────────── States ──────
abstract class OnboardingState extends Equatable {
const OnboardingState();
@override
List<Object?> get props => [];
}
class OnboardingInitial extends OnboardingState {}
class OnboardingLoading extends OnboardingState {}
class OnboardingError extends OnboardingState {
final String message;
const OnboardingError(this.message);
@override
List<Object?> get props => [message];
}
/// Étape 1 : choix formule + plage (affiche la grille des formules)
class OnboardingStepFormule extends OnboardingState {
final List<FormuleModel> formules;
const OnboardingStepFormule(this.formules);
@override
List<Object?> get props => [formules];
}
/// Étape 2 : choix période + type organisation (formule/plage déjà sélectionnés)
class OnboardingStepPeriode extends OnboardingState {
final String codeFormule;
final String plage;
final List<FormuleModel> formules;
const OnboardingStepPeriode({
required this.codeFormule,
required this.plage,
required this.formules,
});
@override
List<Object?> get props => [codeFormule, plage, formules];
}
/// Étape 3 : récapitulatif avec montant calculé (avant paiement)
class OnboardingStepSummary extends OnboardingState {
final SouscriptionStatusModel souscription;
const OnboardingStepSummary(this.souscription);
@override
List<Object?> get props => [souscription];
}
/// Étape 4 : paiement Wave — URL à ouvrir dans le navigateur
class OnboardingStepPaiement extends OnboardingState {
final SouscriptionStatusModel souscription;
final String waveLaunchUrl;
const OnboardingStepPaiement({required this.souscription, required this.waveLaunchUrl});
@override
List<Object?> get props => [souscription, waveLaunchUrl];
}
/// Étape 5 : en attente de validation SuperAdmin
class OnboardingStepAttente extends OnboardingState {
final SouscriptionStatusModel? souscription;
const OnboardingStepAttente({this.souscription});
@override
List<Object?> get props => [souscription];
}
/// Souscription rejetée par le SuperAdmin
class OnboardingRejected extends OnboardingState {
final String? commentaire;
const OnboardingRejected({this.commentaire});
@override
List<Object?> get props => [commentaire];
}
// ─────────────────────────────────────────────────────────────── BLoC ────────
@injectable
class OnboardingBloc extends Bloc<OnboardingEvent, OnboardingState> {
final SouscriptionDatasource _datasource;
// Données accumulées au fil du wizard
List<FormuleModel> _formules = [];
String? _codeFormule;
String? _plage;
String? _typePeriode;
String? _typeOrganisation;
String? _organisationId;
SouscriptionStatusModel? _souscription;
OnboardingBloc(this._datasource) : super(OnboardingInitial()) {
on<OnboardingStarted>(_onStarted);
on<OnboardingFormuleSelected>(_onFormuleSelected);
on<OnboardingPeriodeSelected>(_onPeriodeSelected);
on<OnboardingDemandeConfirmee>(_onDemandeConfirmee);
on<OnboardingPaiementInitie>(_onPaiementInitie);
on<OnboardingRetourDepuisWave>(_onRetourDepuisWave);
}
Future<void> _onStarted(OnboardingStarted event, Emitter<OnboardingState> emit) async {
emit(OnboardingLoading());
try {
_formules = await _datasource.getFormules();
switch (event.initialState) {
case 'NO_SUBSCRIPTION':
emit(OnboardingStepFormule(_formules));
case 'AWAITING_PAYMENT':
final sosc = await _datasource.getMaSouscription();
if (sosc != null) {
_souscription = sosc;
emit(OnboardingStepSummary(sosc));
} else {
emit(OnboardingStepFormule(_formules));
}
case 'PAYMENT_INITIATED':
final sosc = await _datasource.getMaSouscription();
if (sosc != null && sosc.waveLaunchUrl != null) {
_souscription = sosc;
emit(OnboardingStepPaiement(
souscription: sosc,
waveLaunchUrl: sosc.waveLaunchUrl!,
));
} else {
emit(OnboardingStepAttente(souscription: sosc));
}
case 'AWAITING_VALIDATION':
final sosc = await _datasource.getMaSouscription();
_souscription = sosc;
emit(OnboardingStepAttente(souscription: sosc));
case 'REJECTED':
final sosc = await _datasource.getMaSouscription();
emit(OnboardingRejected(commentaire: sosc?.statutValidation));
default:
emit(OnboardingStepFormule(_formules));
}
} catch (e) {
AppLogger.error('OnboardingBloc._onStarted: $e');
emit(const OnboardingError('Impossible de charger les formules. Vérifiez votre connexion.'));
}
}
void _onFormuleSelected(OnboardingFormuleSelected event, Emitter<OnboardingState> emit) {
_codeFormule = event.codeFormule;
_plage = event.plage;
emit(OnboardingStepPeriode(
codeFormule: event.codeFormule,
plage: event.plage,
formules: _formules,
));
}
void _onPeriodeSelected(OnboardingPeriodeSelected event, Emitter<OnboardingState> emit) {
_typePeriode = event.typePeriode;
_typeOrganisation = event.typeOrganisation;
_organisationId = event.organisationId;
}
Future<void> _onDemandeConfirmee(
OnboardingDemandeConfirmee event, Emitter<OnboardingState> emit) async {
if (_codeFormule == null || _plage == null || _typePeriode == null ||
_typeOrganisation == null || _organisationId == null) {
emit(const OnboardingError('Données manquantes. Recommencez depuis le début.'));
return;
}
emit(OnboardingLoading());
try {
final sosc = await _datasource.creerDemande(
typeFormule: _codeFormule!,
plageMembres: _plage!,
typePeriode: _typePeriode!,
typeOrganisation: _typeOrganisation!,
organisationId: _organisationId!,
);
if (sosc != null) {
_souscription = sosc;
emit(OnboardingStepSummary(sosc));
} else {
emit(const OnboardingError('Erreur lors de la création de la demande.'));
}
} catch (e) {
emit(OnboardingError('Erreur: $e'));
}
}
Future<void> _onPaiementInitie(
OnboardingPaiementInitie event, Emitter<OnboardingState> emit) async {
final souscId = _souscription?.souscriptionId;
if (souscId == null) {
emit(const OnboardingError('Souscription introuvable.'));
return;
}
emit(OnboardingLoading());
try {
final updated = await _datasource.initierPaiement(souscId);
if (updated?.waveLaunchUrl != null) {
_souscription = updated;
emit(OnboardingStepPaiement(
souscription: updated!,
waveLaunchUrl: updated.waveLaunchUrl!,
));
} else {
emit(const OnboardingError('Impossible d\'initier le paiement Wave.'));
}
} catch (e) {
emit(OnboardingError('Erreur paiement: $e'));
}
}
Future<void> _onRetourDepuisWave(
OnboardingRetourDepuisWave event, Emitter<OnboardingState> emit) async {
emit(OnboardingLoading());
try {
final souscId = _souscription?.souscriptionId;
if (souscId != null) {
await _datasource.confirmerPaiement(souscId);
}
final sosc = await _datasource.getMaSouscription();
_souscription = sosc;
emit(OnboardingStepAttente(souscription: sosc));
} catch (e) {
// En cas d'erreur, on affiche quand même l'écran d'attente
emit(OnboardingStepAttente(souscription: _souscription));
}
}
}

View File

@@ -0,0 +1,118 @@
import 'package:dio/dio.dart';
import 'package:injectable/injectable.dart';
import '../../../../core/config/environment.dart';
import '../../../../core/utils/logger.dart';
import '../../../../features/authentication/data/datasources/keycloak_auth_service.dart';
import '../models/formule_model.dart';
import '../models/souscription_status_model.dart';
@lazySingleton
class SouscriptionDatasource {
final KeycloakAuthService _authService;
final Dio _dio = Dio();
SouscriptionDatasource(this._authService);
Future<Options> _authOptions() async {
final token = await _authService.getValidToken();
return Options(
headers: {'Authorization': 'Bearer $token'},
validateStatus: (s) => s != null && s < 500,
);
}
String get _base => AppConfig.apiBaseUrl;
/// Liste toutes les formules disponibles (public)
Future<List<FormuleModel>> getFormules() async {
try {
final opts = await _authOptions();
final response = await _dio.get('$_base/api/souscriptions/formules', options: opts);
if (response.statusCode == 200 && response.data is List) {
return (response.data as List)
.map((e) => FormuleModel.fromJson(e as Map))
.toList();
}
} catch (e) {
AppLogger.error('SouscriptionDatasource.getFormules: $e');
}
return [];
}
/// Récupère la souscription courante de l'OrgAdmin connecté
Future<SouscriptionStatusModel?> getMaSouscription() async {
try {
final opts = await _authOptions();
final response = await _dio.get('$_base/api/souscriptions/ma-souscription', options: opts);
if (response.statusCode == 200 && response.data is Map) {
return SouscriptionStatusModel.fromJson(response.data as Map);
}
} catch (e) {
AppLogger.error('SouscriptionDatasource.getMaSouscription: $e');
}
return null;
}
/// Crée une demande de souscription
Future<SouscriptionStatusModel?> creerDemande({
required String typeFormule,
required String plageMembres,
required String typePeriode,
required String typeOrganisation,
required String organisationId,
}) async {
try {
final opts = await _authOptions();
final response = await _dio.post(
'$_base/api/souscriptions/demande',
data: {
'typeFormule': typeFormule,
'plageMembres': plageMembres,
'typePeriode': typePeriode,
'typeOrganisation': typeOrganisation,
'organisationId': organisationId,
},
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}');
} catch (e) {
AppLogger.error('SouscriptionDatasource.creerDemande: $e');
}
return null;
}
/// Initie le paiement Wave pour une souscription existante
Future<SouscriptionStatusModel?> initierPaiement(String souscriptionId) async {
try {
final opts = await _authOptions();
final response = await _dio.post(
'$_base/api/souscriptions/$souscriptionId/initier-paiement',
options: opts,
);
if (response.statusCode == 200 && response.data is Map) {
return SouscriptionStatusModel.fromJson(response.data as Map);
}
} catch (e) {
AppLogger.error('SouscriptionDatasource.initierPaiement: $e');
}
return null;
}
/// Confirme le paiement Wave après retour du deep link
Future<bool> confirmerPaiement(String souscriptionId) async {
try {
final opts = await _authOptions();
final response = await _dio.post(
'$_base/api/souscriptions/$souscriptionId/confirmer-paiement',
options: opts,
);
return response.statusCode == 200;
} catch (e) {
AppLogger.error('SouscriptionDatasource.confirmerPaiement: $e');
}
return false;
}
}

View File

@@ -0,0 +1,37 @@
/// Réponse enrichie de /api/membres/mon-statut
class AuthStatusModel {
final String statutCompte;
/// État du workflow d'onboarding — non null si statutCompte == EN_ATTENTE_VALIDATION
final String onboardingState;
final String? souscriptionId;
final String? waveSessionId;
const AuthStatusModel({
required this.statutCompte,
this.onboardingState = 'NO_SUBSCRIPTION',
this.souscriptionId,
this.waveSessionId,
});
bool get isActive => statutCompte == 'ACTIF';
bool get isPendingOnboarding => statutCompte == 'EN_ATTENTE_VALIDATION';
bool get isBlocked =>
statutCompte == 'SUSPENDU' || statutCompte == 'DESACTIVE';
factory AuthStatusModel.fromJson(Map<dynamic, dynamic> json) {
return AuthStatusModel(
statutCompte: (json['statutCompte'] as String?) ?? 'ACTIF',
onboardingState: (json['onboardingState'] as String?) ?? 'NO_SUBSCRIPTION',
souscriptionId: json['souscriptionId'] as String?,
waveSessionId: json['waveSessionId'] as String?,
);
}
factory AuthStatusModel.active() =>
const AuthStatusModel(statutCompte: 'ACTIF', onboardingState: 'VALIDATED');
@override
String toString() =>
'AuthStatusModel($statutCompte, onboarding=$onboardingState, sous=$souscriptionId)';
}

View File

@@ -0,0 +1,43 @@
/// Formule d'abonnement retournée par /api/souscriptions/formules
class FormuleModel {
final String code; // BASIC | STANDARD | PREMIUM
final String libelle;
final String? description;
final String plage; // PETITE | MOYENNE | GRANDE | TRES_GRANDE
final String plageLibelle;
final int minMembres;
final int maxMembres; // -1 = illimité
final double prixMensuel;
final double prixAnnuel;
final int ordreAffichage;
const FormuleModel({
required this.code,
required this.libelle,
this.description,
required this.plage,
required this.plageLibelle,
required this.minMembres,
required this.maxMembres,
required this.prixMensuel,
required this.prixAnnuel,
required this.ordreAffichage,
});
factory FormuleModel.fromJson(Map<dynamic, dynamic> json) {
return FormuleModel(
code: json['code'] as String,
libelle: json['libelle'] as String,
description: json['description'] as String?,
plage: json['plage'] as String,
plageLibelle: (json['plageLibelle'] as String?) ?? '',
minMembres: (json['minMembres'] as num?)?.toInt() ?? 0,
maxMembres: (json['maxMembres'] as num?)?.toInt() ?? -1,
prixMensuel: (json['prixMensuel'] as num?)?.toDouble() ?? 0,
prixAnnuel: (json['prixAnnuel'] as num?)?.toDouble() ?? 0,
ordreAffichage: (json['ordreAffichage'] as num?)?.toInt() ?? 0,
);
}
String get maxMembresLabel => maxMembres == -1 ? '' : '$maxMembres';
}

View File

@@ -0,0 +1,53 @@
/// Statut courant d'une souscription retourné par le backend
class SouscriptionStatusModel {
final String souscriptionId;
final String statutValidation;
final String typeFormule;
final String plageMembres;
final String plageLibelle;
final String typePeriode;
final String typeOrganisation;
final double? montantTotal;
final double? montantMensuelBase;
final double? coefficientApplique;
final String? waveSessionId;
final String? waveLaunchUrl;
final String organisationId;
final String? organisationNom;
const SouscriptionStatusModel({
required this.souscriptionId,
required this.statutValidation,
required this.typeFormule,
required this.plageMembres,
required this.plageLibelle,
required this.typePeriode,
required this.typeOrganisation,
this.montantTotal,
this.montantMensuelBase,
this.coefficientApplique,
this.waveSessionId,
this.waveLaunchUrl,
required this.organisationId,
this.organisationNom,
});
factory SouscriptionStatusModel.fromJson(Map<dynamic, dynamic> json) {
return SouscriptionStatusModel(
souscriptionId: json['souscriptionId'] as String,
statutValidation: json['statutValidation'] as String,
typeFormule: json['typeFormule'] as String,
plageMembres: json['plageMembres'] as String,
plageLibelle: (json['plageLibelle'] as String?) ?? '',
typePeriode: json['typePeriode'] as String,
typeOrganisation: (json['typeOrganisation'] as String?) ?? 'ASSOCIATION',
montantTotal: (json['montantTotal'] as num?)?.toDouble(),
montantMensuelBase: (json['montantMensuelBase'] as num?)?.toDouble(),
coefficientApplique: (json['coefficientApplique'] as num?)?.toDouble(),
waveSessionId: json['waveSessionId'] as String?,
waveLaunchUrl: json['waveLaunchUrl'] as String?,
organisationId: json['organisationId'] as String,
organisationNom: json['organisationNom'] as String?,
);
}
}

View File

@@ -0,0 +1,171 @@
import 'dart:async';
import 'package:flutter/material.dart';
import '../../data/models/souscription_status_model.dart';
import '../../../../features/authentication/presentation/bloc/auth_bloc.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
/// Étape 5 — En attente de validation SuperAdmin
class AwaitingValidationPage extends StatefulWidget {
final SouscriptionStatusModel? souscription;
const AwaitingValidationPage({super.key, this.souscription});
@override
State<AwaitingValidationPage> createState() => _AwaitingValidationPageState();
}
class _AwaitingValidationPageState extends State<AwaitingValidationPage>
with SingleTickerProviderStateMixin {
late AnimationController _pulseController;
late Animation<double> _pulseAnimation;
Timer? _refreshTimer;
@override
void initState() {
super.initState();
_pulseController = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
)..repeat(reverse: true);
_pulseAnimation = Tween(begin: 0.85, 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), (_) {
if (mounted) {
context.read<AuthBloc>().add(const AuthStatusChecked());
}
});
}
@override
void dispose() {
_pulseController.dispose();
_refreshTimer?.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
final sosc = widget.souscription;
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Animation d'attente
ScaleTransition(
scale: _pulseAnimation,
child: Container(
width: 120,
height: 120,
decoration: BoxDecoration(
color: const Color(0xFFFFF3E0),
shape: BoxShape.circle,
border: Border.all(color: const Color(0xFFF57C00), width: 3),
),
child: const Icon(
Icons.hourglass_top_rounded,
size: 60,
color: Color(0xFFF57C00),
),
),
),
const SizedBox(height: 32),
const Text(
'Demande soumise !',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
textAlign: TextAlign.center,
),
const SizedBox(height: 12),
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),
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,
),
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'),
),
const SizedBox(height: 12),
TextButton(
onPressed: () =>
context.read<AuthBloc>().add(const AuthLogoutRequested()),
child: const Text('Se déconnecter'),
),
],
),
),
),
);
}
}
class _SummaryCard extends StatelessWidget {
final SouscriptionStatusModel souscription;
const _SummaryCard({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]!),
),
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'),
],
),
);
}
}
class _Row extends StatelessWidget {
final String label;
final String value;
const _Row(this.label, this.value);
@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)),
],
),
);
}
}

View File

@@ -0,0 +1,149 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../../../core/di/injection.dart';
import 'plan_selection_page.dart';
import 'period_selection_page.dart';
import 'subscription_summary_page.dart';
import 'wave_payment_page.dart';
import 'awaiting_validation_page.dart';
/// Page conteneur du workflow d'onboarding.
/// Reçoit l'état initial du backend (onboardingState) et dispatch au bon écran.
class OnboardingFlowPage extends StatelessWidget {
final String onboardingState;
final String? souscriptionId;
final String organisationId;
const OnboardingFlowPage({
super.key,
required this.onboardingState,
required this.organisationId,
this.souscriptionId,
});
@override
Widget build(BuildContext context) {
return BlocProvider(
create: (_) => getIt<OnboardingBloc>()
..add(OnboardingStarted(
initialState: onboardingState,
existingSouscriptionId: souscriptionId,
)),
child: const _OnboardingFlowView(),
);
}
}
class _OnboardingFlowView extends StatelessWidget {
const _OnboardingFlowView();
@override
Widget build(BuildContext context) {
return BlocBuilder<OnboardingBloc, OnboardingState>(
builder: (context, state) {
if (state is OnboardingLoading || state is OnboardingInitial) {
return const Scaffold(
body: Center(child: CircularProgressIndicator()),
);
}
if (state is OnboardingError) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(24),
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),
const SizedBox(height: 24),
ElevatedButton(
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingStarted(initialState: 'NO_SUBSCRIPTION'),
),
child: const Text('Réessayer'),
),
],
),
),
),
);
}
if (state is OnboardingStepFormule) {
return PlanSelectionPage(formules: state.formules);
}
if (state is OnboardingStepPeriode) {
return PeriodSelectionPage(
codeFormule: state.codeFormule,
plage: state.plage,
formules: state.formules,
);
}
if (state is OnboardingStepSummary) {
return SubscriptionSummaryPage(souscription: state.souscription);
}
if (state is OnboardingStepPaiement) {
return WavePaymentPage(
souscription: state.souscription,
waveLaunchUrl: state.waveLaunchUrl,
);
}
if (state is OnboardingStepAttente) {
return AwaitingValidationPage(souscription: state.souscription);
}
if (state is OnboardingRejected) {
return _RejectedPage(commentaire: state.commentaire);
}
return const Scaffold(body: Center(child: CircularProgressIndicator()));
},
);
}
}
class _RejectedPage extends StatelessWidget {
final String? commentaire;
const _RejectedPage({this.commentaire});
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Padding(
padding: const EdgeInsets.all(32),
child: Column(
mainAxisSize: MainAxisSize.min,
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),
),
if (commentaire != null) ...[
const SizedBox(height: 12),
Text(commentaire!, textAlign: TextAlign.center),
],
const SizedBox(height: 32),
ElevatedButton(
onPressed: () => context.read<OnboardingBloc>().add(
OnboardingStarted(initialState: 'NO_SUBSCRIPTION'),
),
child: const Text('Nouvelle souscription'),
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,224 @@
import 'package:flutter/material.dart';
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';
/// Étape 2 — Choix de la période de facturation et du type d'organisation
class PeriodSelectionPage extends StatefulWidget {
final String codeFormule;
final String plage;
final List<FormuleModel> formules;
const PeriodSelectionPage({
super.key,
required this.codeFormule,
required this.plage,
required this.formules,
});
@override
State<PeriodSelectionPage> createState() => _PeriodSelectionPageState();
}
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'),
];
FormuleModel? get _formule => widget.formules
.where((f) => f.code == widget.codeFormule && f.plage == widget.plage)
.firstOrNull;
double get _prixEstime {
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;
}
String get _organisationId {
final authState = context.read<AuthBloc>().state;
if (authState is AuthAuthenticated) {
return authState.user.organizationContexts.isNotEmpty
? authState.user.organizationContexts.first.organizationId
: '';
}
if (authState is AuthPendingOnboarding) {
return authState.organisationId ?? '';
}
return '';
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
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,
children: [
const Text('Estimation', style: TextStyle(fontWeight: FontWeight.bold)),
Text(
'${_prixEstime.toStringAsFixed(0)} FCFA',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: theme.primaryColor,
),
),
],
),
),
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'),
),
),
);
}
}
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

@@ -0,0 +1,252 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/formule_model.dart';
/// Étape 1 — Choix de la formule (BASIC / STANDARD / PREMIUM) et de la plage de membres
class PlanSelectionPage extends StatefulWidget {
final List<FormuleModel> formules;
const PlanSelectionPage({super.key, required this.formules});
@override
State<PlanSelectionPage> createState() => _PlanSelectionPageState();
}
class _PlanSelectionPageState extends State<PlanSelectionPage> {
String? _selectedPlage;
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'),
];
static const _formules = [
('BASIC', 'Basic', Icons.star_outline, Color(0xFF1976D2)),
('STANDARD', 'Standard', Icons.star_half, Color(0xFF388E3C)),
('PREMIUM', 'Premium', Icons.star, Color(0xFFF57C00)),
];
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;
@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])),
],
),
selected: selected,
onSelected: (_) => setState(() {
_selectedPlage = code;
_selectedFormule = null;
}),
padding:
const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
);
}).toList(),
),
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),
],
),
),
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),
),
child: const Text('Continuer'),
),
),
);
}
}
class _FormuleCard extends StatelessWidget {
final FormuleModel formule;
final String label;
final IconData icon;
final Color color;
final bool selected;
final VoidCallback onTap;
const _FormuleCard({
required this.formule,
required this.label,
required this.icon,
required this.color,
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: 8),
decoration: BoxDecoration(
color: selected ? color.withOpacity(0.1) : Colors.white,
border: Border.all(
color: selected ? color : Colors.grey[300]!,
width: selected ? 2 : 1,
),
borderRadius: BorderRadius.circular(12),
),
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)),
],
),
),
Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
'${_formatPrix(formule.prixMensuel)} FCFA',
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 15,
color: color),
),
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,
),
],
),
),
),
);
}
String _formatPrix(double prix) {
if (prix >= 1000) {
return '${(prix / 1000).toStringAsFixed(0)} 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

@@ -0,0 +1,174 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../bloc/onboarding_bloc.dart';
import '../../data/models/souscription_status_model.dart';
/// Étape 3 — Récapitulatif avant paiement
class SubscriptionSummaryPage extends StatelessWidget {
final SouscriptionStatusModel souscription;
const SubscriptionSummaryPage({super.key, required this.souscription});
static const _periodeLabels = {
'MENSUEL': 'Mensuel',
'TRIMESTRIEL': 'Trimestriel (5%)',
'SEMESTRIEL': 'Semestriel (10%)',
'ANNUEL': 'Annuel (20%)',
};
static const _orgLabels = {
'ASSOCIATION': 'Association / ONG locale',
'MUTUELLE': 'Mutuelle',
'COOPERATIVE': 'Coopérative / Microfinance',
'FEDERATION': 'Fédération / Grande ONG',
};
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final montant = souscription.montantTotal ?? 0;
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)],
),
borderRadius: BorderRadius.circular(16),
),
child: Column(
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,
),
),
Text(
'à régler par Wave Mobile Money',
style: TextStyle(color: Colors.white.withOpacity(0.85)),
),
],
),
),
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,
),
_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,
),
),
),
);
}
}
class _InfoRow extends StatelessWidget {
final String label;
final String value;
final bool bold;
const _InfoRow({required this.label, required this.value, this.bold = false});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.symmetric(vertical: 6),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 160,
child: Text(label,
style: const TextStyle(color: Colors.grey, fontSize: 14)),
),
Expanded(
child: Text(
value,
style: TextStyle(
fontWeight: bold ? FontWeight.bold : FontWeight.normal,
fontSize: bold ? 16 : 14,
),
),
),
],
),
);
}
}

View File

@@ -0,0 +1,145 @@
import 'package:flutter/material.dart';
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';
/// Étape 4 — Lancement du paiement Wave + attente du retour
class WavePaymentPage extends StatefulWidget {
final SouscriptionStatusModel souscription;
final String waveLaunchUrl;
const WavePaymentPage({
super.key,
required this.souscription,
required this.waveLaunchUrl,
});
@override
State<WavePaymentPage> createState() => _WavePaymentPageState();
}
class _WavePaymentPageState extends State<WavePaymentPage>
with WidgetsBindingObserver {
bool _paymentLaunched = false;
bool _appResumed = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@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 {
final uri = Uri.parse(widget.waveLaunchUrl);
if (await canLaunchUrl(uri)) {
setState(() => _paymentLaunched = true);
await launchUrl(uri, mode: LaunchMode.externalApplication);
} else {
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,
),
);
}
}
}
@override
Widget build(BuildContext context) {
final montant = widget.souscription.montantTotal ?? 0;
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),
),
child: const Icon(Icons.waves, color: Colors.white, size: 52),
),
const SizedBox(height: 32),
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),
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,
),
),
] 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'),
),
],
],
),
),
);
}
}