Files
unionflow-mobile-apps/lib/features/onboarding/data/datasources/souscription_datasource.dart
dahoud 21b519de53 feat(onboarding): UI/UX polish + mapping typeOrg + gestion erreur paiement Wave
Plan selection :
- Grille 2×2 compacte pour les plages (au lieu de liste verticale)
- Badge  POPULAIRE sur STANDARD
- Remise annuelle affichée (−X%/an)
- AnimatedSwitcher + auto-scroll vers formules quand plage sélectionnée
- Dark mode adaptatif complet

Récapitulatif :
- Dark mode complet (AppColors pairs)
- Bloc Total gradient gold adaptatif
- NoteBox avec backgrounds accent.withOpacity()
- Utilise OnboardingBottomBar (consistence)

Payment method :
- Dark mode + couleurs de marque Wave/Orange hardcodées (intentionnel)
- Logo container reste blanc (brand)
- Mapping typeOrganisation détaillé → enum backend ASSOCIATION/MUTUELLE/
  COOPERATIVE/FEDERATION (fix HTTP 400 'Valeur invalide pour typeOrganisation')

Wave payment :
- Dark mode adaptatif
- Message dev clair (simulation automatique)
- Gestion OnboardingPaiementEchoue : SnackBar rouge + reset flags + reste sur page
  (plus de faux succès quand confirmerPaiement() return false ou lève exception)

Bloc : nouvel état OnboardingPaiementEchoue, _onRetourDepuisWave vérifie le return
de confirmerPaiement() (plus de catch silencieux qui émettait OnboardingPaiementConfirme)

Shared widgets : OnboardingSectionTitle + OnboardingBottomBar dark mode + hint optionnel
2026-04-15 20:14:27 +00:00

164 lines
5.5 KiB
Dart

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;
}
/// Mappe le type d'organisation détaillé (ex: MUTUELLE_EPARGNE, CLUB_SPORTIF)
/// vers l'une des 4 catégories acceptées par le backend souscription :
/// ASSOCIATION, MUTUELLE, COOPERATIVE, FEDERATION.
static String? _mapTypeOrganisationBilling(String? detailedType) {
if (detailedType == null || detailedType.isEmpty) return null;
switch (detailedType.toUpperCase()) {
// Catégorie ASSOCIATIF + RELIGIEUX
case 'ASSOCIATION':
case 'CLUB_SERVICE':
case 'CLUB_SPORTIF':
case 'CLUB_CULTUREL':
case 'EGLISE':
case 'GROUPE_PRIERE':
return 'ASSOCIATION';
// Catégorie FINANCIER_SOLIDAIRE (épargne/crédit)
case 'TONTINE':
case 'MUTUELLE_EPARGNE':
case 'MUTUELLE_CREDIT':
case 'MUTUELLE':
return 'MUTUELLE';
// Catégorie COOPERATIVE
case 'COOPERATIVE':
case 'GIE':
return 'COOPERATIVE';
// Catégorie PROFESSIONNEL + RESEAU_FEDERATION
case 'ONG':
case 'FONDATION':
case 'SYNDICAT':
case 'ORDRE_PROFESSIONNEL':
case 'FEDERATION':
case 'RESEAU':
return 'FEDERATION';
default:
return 'ASSOCIATION'; // fallback sûr
}
}
/// Crée une demande de souscription
Future<SouscriptionStatusModel?> creerDemande({
required String typeFormule,
required String plageMembres,
required String typePeriode,
String? typeOrganisation,
required String organisationId,
}) async {
try {
final opts = await _authOptions();
final mappedType = _mapTypeOrganisationBilling(typeOrganisation);
final body = <String, dynamic>{
'typeFormule': typeFormule,
'plageMembres': plageMembres,
'typePeriode': typePeriode,
'organisationId': organisationId,
};
if (mappedType != null && mappedType.isNotEmpty) {
body['typeOrganisation'] = mappedType;
}
final response = await _dio.post(
'$_base/api/souscriptions/demande',
data: body,
options: opts,
);
if ((response.statusCode == 200 || response.statusCode == 201) && response.data is Map) {
return SouscriptionStatusModel.fromJson(response.data as Map);
}
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');
}
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/confirmer-paiement',
queryParameters: {'id': souscriptionId},
options: opts,
);
return response.statusCode == 200;
} catch (e) {
AppLogger.error('SouscriptionDatasource.confirmerPaiement: $e');
}
return false;
}
}