Initial commit du projet Flutter
This commit is contained in:
184
lib/controllers/services_controller.dart
Normal file
184
lib/controllers/services_controller.dart
Normal file
@@ -0,0 +1,184 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../models/service_model.dart';
|
||||
import '../services/wortis_api_service.dart';
|
||||
|
||||
class ServicesController extends ChangeNotifier {
|
||||
final WortisApiService _apiService = WortisApiService();
|
||||
|
||||
List<WortisService> _allServices = [];
|
||||
Map<String, List<WortisService>> _servicesBySector = {};
|
||||
bool _isLoading = false;
|
||||
String? _error;
|
||||
String _searchQuery = '';
|
||||
String _selectedSector = 'Tous';
|
||||
|
||||
// Ordre de priorité des secteurs (index 0 = plus haute priorité)
|
||||
static const List<String> _sectorPriority = [
|
||||
'Service Public',
|
||||
// Ajoutez d'autres secteurs selon vos besoins
|
||||
];
|
||||
|
||||
// Getters
|
||||
List<WortisService> get allServices => _allServices;
|
||||
Map<String, List<WortisService>> get servicesBySector => _servicesBySector;
|
||||
bool get isLoading => _isLoading;
|
||||
String? get error => _error;
|
||||
String get searchQuery => _searchQuery;
|
||||
String get selectedSector => _selectedSector;
|
||||
|
||||
List<String> get sectors => ['Tous', ..._servicesBySector.keys];
|
||||
|
||||
// Méthode pour obtenir la priorité d'un secteur
|
||||
int _getSectorPriority(String sector) {
|
||||
final normalizedSector = sector.toLowerCase();
|
||||
for (int i = 0; i < _sectorPriority.length; i++) {
|
||||
if (_sectorPriority[i].toLowerCase() == normalizedSector) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
return _sectorPriority
|
||||
.length; // Secteurs non listés ont la priorité la plus basse
|
||||
}
|
||||
|
||||
// Méthode pour trier les services par secteur prioritaire et rang
|
||||
List<WortisService> _sortServicesByPriority(List<WortisService> services) {
|
||||
final List<WortisService> sortedServices = List.from(services);
|
||||
|
||||
sortedServices.sort((a, b) {
|
||||
// D'abord, comparer par priorité de secteur
|
||||
final priorityA = _getSectorPriority(a.secteurActivite);
|
||||
final priorityB = _getSectorPriority(b.secteurActivite);
|
||||
|
||||
if (priorityA != priorityB) {
|
||||
return priorityA.compareTo(priorityB);
|
||||
}
|
||||
|
||||
// Si même secteur, trier par rang
|
||||
if (a.rang != null && b.rang != null) {
|
||||
return a.rang!.compareTo(b.rang!);
|
||||
}
|
||||
// Si seulement le premier a un rang, il passe en premier
|
||||
else if (a.rang != null && b.rang == null) {
|
||||
return -1;
|
||||
}
|
||||
// Si seulement le deuxième a un rang, il passe en premier
|
||||
else if (a.rang == null && b.rang != null) {
|
||||
return 1;
|
||||
}
|
||||
// Si aucun n'a de rang, trier par nom alphabétiquement
|
||||
else {
|
||||
return a.name.compareTo(b.name);
|
||||
}
|
||||
});
|
||||
|
||||
return sortedServices;
|
||||
}
|
||||
|
||||
// Services filtrés selon la recherche et le secteur avec tri par priorité
|
||||
List<WortisService> get filteredServices {
|
||||
List<WortisService> services;
|
||||
|
||||
if (_selectedSector == 'Tous') {
|
||||
services = _allServices;
|
||||
} else {
|
||||
services = _servicesBySector[_selectedSector] ?? [];
|
||||
}
|
||||
|
||||
if (_searchQuery.isNotEmpty) {
|
||||
services =
|
||||
services.where((service) {
|
||||
final name = service.name.toLowerCase();
|
||||
final description = service.description.toLowerCase();
|
||||
final sector = service.secteurActivite.toLowerCase();
|
||||
final query = _searchQuery.toLowerCase();
|
||||
|
||||
return name.contains(query) ||
|
||||
description.contains(query) ||
|
||||
sector.contains(query);
|
||||
}).toList();
|
||||
}
|
||||
|
||||
// Appliquer le tri par priorité de secteur et rang
|
||||
return _sortServicesByPriority(services);
|
||||
}
|
||||
|
||||
// Charger les services depuis l'API
|
||||
Future<void> loadServices() async {
|
||||
_isLoading = true;
|
||||
_error = null;
|
||||
notifyListeners();
|
||||
|
||||
try {
|
||||
_allServices = await _apiService.getServices();
|
||||
|
||||
// Trier tous les services par priorité dès le chargement
|
||||
_allServices = _sortServicesByPriority(_allServices);
|
||||
|
||||
_servicesBySector = _apiService.groupServicesBySector(_allServices);
|
||||
|
||||
// Trier les services dans chaque secteur
|
||||
_servicesBySector.forEach((key, value) {
|
||||
_servicesBySector[key] = _sortServicesByPriority(value);
|
||||
});
|
||||
|
||||
_error = null;
|
||||
} catch (e) {
|
||||
_error = e.toString();
|
||||
_allServices = [];
|
||||
_servicesBySector = {};
|
||||
} finally {
|
||||
_isLoading = false;
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
// Rafraîchir les services
|
||||
Future<void> refreshServices() async {
|
||||
await loadServices();
|
||||
}
|
||||
|
||||
// Mettre à jour la recherche
|
||||
void updateSearchQuery(String query) {
|
||||
_searchQuery = query;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Changer le secteur sélectionné
|
||||
void selectSector(String sector) {
|
||||
_selectedSector = sector;
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Vider la recherche
|
||||
void clearSearch() {
|
||||
_searchQuery = '';
|
||||
notifyListeners();
|
||||
}
|
||||
|
||||
// Obtenir un service par ID
|
||||
WortisService? getServiceById(String id) {
|
||||
try {
|
||||
return _allServices.firstWhere((service) => service.id == id);
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Obtenir les services actifs uniquement avec tri par priorité
|
||||
List<WortisService> get activeServices {
|
||||
final active = _allServices.where((service) => service.status).toList();
|
||||
return _sortServicesByPriority(active);
|
||||
}
|
||||
|
||||
// Obtenir le nombre de services par secteur
|
||||
Map<String, int> get servicesCountBySector {
|
||||
Map<String, int> count = {};
|
||||
for (var entry in _servicesBySector.entries) {
|
||||
count[entry.key] = entry.value.length;
|
||||
}
|
||||
return count;
|
||||
}
|
||||
|
||||
// Méthode pour modifier l'ordre de priorité des secteurs si nécessaire
|
||||
static List<String> get sectorPriority => List.from(_sectorPriority);
|
||||
}
|
||||
1340
lib/index.html
Normal file
1340
lib/index.html
Normal file
File diff suppressed because it is too large
Load Diff
1134
lib/main.dart
Normal file
1134
lib/main.dart
Normal file
File diff suppressed because it is too large
Load Diff
178
lib/models/service_model.dart
Normal file
178
lib/models/service_model.dart
Normal file
@@ -0,0 +1,178 @@
|
||||
// Dans ../models/service_model.dart
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class WortisService {
|
||||
final String id;
|
||||
final String name;
|
||||
final String description;
|
||||
final String secteurActivite;
|
||||
final bool status;
|
||||
final String? icon;
|
||||
final String? banner;
|
||||
final String? linkView;
|
||||
final String? typeService;
|
||||
final String? boutonList;
|
||||
final String? buttonService;
|
||||
final String? error400;
|
||||
final String? error500;
|
||||
final String? titeDescription;
|
||||
final int? rang; // ← Ajoutez cette ligne
|
||||
|
||||
WortisService({
|
||||
required this.id,
|
||||
required this.name,
|
||||
required this.description,
|
||||
required this.secteurActivite,
|
||||
required this.status,
|
||||
this.icon,
|
||||
this.banner,
|
||||
this.linkView,
|
||||
this.typeService,
|
||||
this.boutonList,
|
||||
this.buttonService,
|
||||
this.error400,
|
||||
this.error500,
|
||||
this.titeDescription,
|
||||
this.rang, // ← Ajoutez cette ligne
|
||||
});
|
||||
|
||||
factory WortisService.fromJson(Map<String, dynamic> json) {
|
||||
return WortisService(
|
||||
id: json['_id'] ?? '',
|
||||
name: json['name'] ?? '',
|
||||
description: json['description'] ?? '',
|
||||
secteurActivite: json['SecteurActivite'] ?? '',
|
||||
status: json['status'] ?? false,
|
||||
icon: json['icon'],
|
||||
banner: json['banner'],
|
||||
linkView: json['link_view'],
|
||||
typeService: json['Type_Service'],
|
||||
boutonList: json['bouton_list'],
|
||||
buttonService: json['button_service'],
|
||||
error400: json['error_400'],
|
||||
error500: json['error_500'],
|
||||
titeDescription: json['tite_description'],
|
||||
rang: json['rang'] as int?, // ← Ajoutez cette ligne
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> toJson() {
|
||||
return {
|
||||
'_id': id,
|
||||
'name': name,
|
||||
'description': description,
|
||||
'SecteurActivite': secteurActivite,
|
||||
'status': status,
|
||||
'icon': icon,
|
||||
'banner': banner,
|
||||
'link_view': linkView,
|
||||
'Type_Service': typeService,
|
||||
'bouton_list': boutonList,
|
||||
'button_service': buttonService,
|
||||
'error_400': error400,
|
||||
'error_500': error500,
|
||||
'tite_description': titeDescription,
|
||||
'rang': rang, // ← Ajoutez cette ligne
|
||||
};
|
||||
}
|
||||
|
||||
// Getter pour l'icône Flutter (vous pouvez garder votre logique existante)
|
||||
IconData get flutterIcon {
|
||||
switch (icon?.toLowerCase()) {
|
||||
case 'movie':
|
||||
return Icons.movie;
|
||||
case 'car':
|
||||
return Icons.directions_car;
|
||||
case 'shopping':
|
||||
return Icons.shopping_cart;
|
||||
case 'food':
|
||||
return Icons.restaurant;
|
||||
case 'hotel':
|
||||
return Icons.hotel;
|
||||
case 'transport':
|
||||
return Icons.directions_bus;
|
||||
case 'health':
|
||||
return Icons.local_hospital;
|
||||
case 'education':
|
||||
return Icons.school;
|
||||
case 'finance':
|
||||
return Icons.account_balance;
|
||||
default:
|
||||
return Icons.miscellaneous_services;
|
||||
}
|
||||
}
|
||||
|
||||
// Getter pour la couleur du secteur (vous pouvez garder votre logique existante)
|
||||
Color get sectorColor {
|
||||
switch (secteurActivite.toLowerCase()) {
|
||||
case 'billetterie':
|
||||
return Color(0xFF6B46C1);
|
||||
case 'transport':
|
||||
return Color(0xFF059669);
|
||||
case 'restauration':
|
||||
return Color(0xFFDC2626);
|
||||
case 'hébergement':
|
||||
return Color(0xFF2563EB);
|
||||
case 'finance':
|
||||
return Color(0xFF7C2D12);
|
||||
case 'santé':
|
||||
return Color(0xFF0891B2);
|
||||
case 'éducation':
|
||||
return Color(0xFF7C3AED);
|
||||
default:
|
||||
return Color(0xFF6B7280);
|
||||
}
|
||||
}
|
||||
|
||||
// Méthode copyWith pour créer une copie avec des modifications
|
||||
WortisService copyWith({
|
||||
String? id,
|
||||
String? name,
|
||||
String? description,
|
||||
String? secteurActivite,
|
||||
bool? status,
|
||||
String? icon,
|
||||
String? banner,
|
||||
String? linkView,
|
||||
String? typeService,
|
||||
String? boutonList,
|
||||
String? buttonService,
|
||||
String? error400,
|
||||
String? error500,
|
||||
String? titeDescription,
|
||||
int? rang,
|
||||
}) {
|
||||
return WortisService(
|
||||
id: id ?? this.id,
|
||||
name: name ?? this.name,
|
||||
description: description ?? this.description,
|
||||
secteurActivite: secteurActivite ?? this.secteurActivite,
|
||||
status: status ?? this.status,
|
||||
icon: icon ?? this.icon,
|
||||
banner: banner ?? this.banner,
|
||||
linkView: linkView ?? this.linkView,
|
||||
typeService: typeService ?? this.typeService,
|
||||
boutonList: boutonList ?? this.boutonList,
|
||||
buttonService: buttonService ?? this.buttonService,
|
||||
error400: error400 ?? this.error400,
|
||||
error500: error500 ?? this.error500,
|
||||
titeDescription: titeDescription ?? this.titeDescription,
|
||||
rang: rang ?? this.rang,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
String toString() {
|
||||
return 'WortisService(id: $id, name: $name, secteur: $secteurActivite, status: $status, rang: $rang)';
|
||||
}
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
if (identical(this, other)) return true;
|
||||
return other is WortisService && other.id == id;
|
||||
}
|
||||
|
||||
@override
|
||||
int get hashCode => id.hashCode;
|
||||
}
|
||||
2832
lib/pages/admin_dashboard.dart
Normal file
2832
lib/pages/admin_dashboard.dart
Normal file
File diff suppressed because it is too large
Load Diff
840
lib/pages/class.dart
Normal file
840
lib/pages/class.dart
Normal file
@@ -0,0 +1,840 @@
|
||||
// lib/class/class.dart
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
/// Gestionnaire de connectivité
|
||||
class ConnectivityManager {
|
||||
final BuildContext context;
|
||||
|
||||
ConnectivityManager(this.context);
|
||||
|
||||
/// Initialiser la connectivité
|
||||
void get initConnectivity {
|
||||
print('Initialisation de la connectivité');
|
||||
}
|
||||
}
|
||||
|
||||
/// Gestionnaire d'overlays personnalisés
|
||||
class CustomOverlay {
|
||||
static OverlayEntry? _currentOverlay;
|
||||
|
||||
/// Afficher un message d'erreur
|
||||
static void showError(BuildContext context, {required String message}) {
|
||||
hide();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.error, color: Colors.white, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.red,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
duration: Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher un message de succès
|
||||
static void showSuccess(BuildContext context, {required String message}) {
|
||||
hide();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.white, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher un message d'information
|
||||
static void showInfo(BuildContext context, {required String message}) {
|
||||
hide();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: Colors.white, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Color(0xFF006699),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
duration: Duration(seconds: 3),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher un avertissement
|
||||
static void showWarning(BuildContext context, {required String message}) {
|
||||
hide();
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.warning_amber, color: Colors.white, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
message,
|
||||
style: TextStyle(color: Colors.white, fontSize: 14),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.orange,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
duration: Duration(seconds: 4),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Afficher un indicateur de chargement
|
||||
static void showLoading(
|
||||
BuildContext context, {
|
||||
String message = 'Chargement...',
|
||||
}) {
|
||||
hide();
|
||||
|
||||
_currentOverlay = OverlayEntry(
|
||||
builder:
|
||||
(context) => Material(
|
||||
color: Colors.black54,
|
||||
child: Center(
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
CircularProgressIndicator(
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Color(0xFF006699),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
message,
|
||||
style: TextStyle(fontSize: 16, color: Colors.black87),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
Overlay.of(context).insert(_currentOverlay!);
|
||||
}
|
||||
|
||||
/// Masquer l'overlay
|
||||
static void hide() {
|
||||
if (_currentOverlay != null) {
|
||||
_currentOverlay!.remove();
|
||||
_currentOverlay = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Classe utilitaire pour les widgets personnalisés
|
||||
class CustomWidgets {
|
||||
/// Créer un champ de saisie stylé
|
||||
static Widget buildStyledTextField({
|
||||
required String label,
|
||||
required String hint,
|
||||
required IconData icon,
|
||||
TextEditingController? controller,
|
||||
bool obscureText = false,
|
||||
String? Function(String?)? validator,
|
||||
void Function(String)? onChanged,
|
||||
bool readOnly = false,
|
||||
VoidCallback? onTap,
|
||||
TextInputType? keyboardType,
|
||||
int? maxLength,
|
||||
String? suffixText,
|
||||
Widget? suffix,
|
||||
}) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
color: Color(0xFF2C3E50),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
TextFormField(
|
||||
controller: controller,
|
||||
validator: validator,
|
||||
obscureText: obscureText,
|
||||
readOnly: readOnly,
|
||||
onTap: onTap,
|
||||
onChanged: onChanged,
|
||||
keyboardType: keyboardType,
|
||||
maxLength: maxLength,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
prefixIcon: Icon(icon, color: Color(0xFF006699)),
|
||||
suffixText: suffixText,
|
||||
suffix: suffix,
|
||||
filled: true,
|
||||
fillColor: Colors.white,
|
||||
counterText: '',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Color(0xFFE0E7FF)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Color(0xFFE0E7FF)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Color(0xFF006699), width: 2),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide(color: Colors.red),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// Créer un bouton stylé
|
||||
static Widget buildStyledButton({
|
||||
required String text,
|
||||
required VoidCallback onPressed,
|
||||
bool isLoading = false,
|
||||
Color? backgroundColor,
|
||||
Color? textColor,
|
||||
IconData? icon,
|
||||
double? height,
|
||||
double? width,
|
||||
bool enabled = true,
|
||||
}) {
|
||||
return SizedBox(
|
||||
width: width ?? double.infinity,
|
||||
height: height ?? 48,
|
||||
child: ElevatedButton(
|
||||
onPressed: (isLoading || !enabled) ? null : onPressed,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: backgroundColor ?? Color(0xFF006699),
|
||||
foregroundColor: textColor ?? Colors.white,
|
||||
elevation: 2,
|
||||
disabledBackgroundColor: Colors.grey[300],
|
||||
disabledForegroundColor: Colors.grey[600],
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child:
|
||||
isLoading
|
||||
? SizedBox(
|
||||
width: 20,
|
||||
height: 20,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
),
|
||||
)
|
||||
: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(icon, size: 18),
|
||||
SizedBox(width: 8),
|
||||
],
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Badge de type de compte =====
|
||||
static Widget buildAccountTypeBadge({
|
||||
required bool isEnterprise,
|
||||
double fontSize = 12,
|
||||
EdgeInsets? padding,
|
||||
}) {
|
||||
return Container(
|
||||
padding: padding ?? EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6).withOpacity(0.1)
|
||||
: Color(0xFF006699).withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6).withOpacity(0.3)
|
||||
: Color(0xFF006699).withOpacity(0.3),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
isEnterprise ? Icons.business : Icons.person,
|
||||
color: isEnterprise ? Color(0xFF8B5CF6) : Color(0xFF006699),
|
||||
size: fontSize + 2,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
isEnterprise ? 'Entreprise' : 'Agent',
|
||||
style: TextStyle(
|
||||
color: isEnterprise ? Color(0xFF8B5CF6) : Color(0xFF006699),
|
||||
fontSize: fontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Carte d'information avec icône =====
|
||||
static Widget buildInfoCard({
|
||||
required String title,
|
||||
required String value,
|
||||
required IconData icon,
|
||||
Color? iconColor,
|
||||
Color? backgroundColor,
|
||||
VoidCallback? onTap,
|
||||
}) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: backgroundColor ?? Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color: (iconColor ?? Color(0xFF006699)).withOpacity(0.2),
|
||||
width: 1,
|
||||
),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.05),
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: (iconColor ?? Color(0xFF006699)).withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(
|
||||
icon,
|
||||
color: iconColor ?? Color(0xFF006699),
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 16),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Colors.black87,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
if (onTap != null)
|
||||
Icon(Icons.arrow_forward_ios, size: 16, color: Colors.grey[400]),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Carte de statistique =====
|
||||
static Widget buildStatCard({
|
||||
required String title,
|
||||
required String value,
|
||||
required IconData icon,
|
||||
Color? color,
|
||||
String? subtitle,
|
||||
}) {
|
||||
final cardColor = color ?? Color(0xFF006699);
|
||||
|
||||
return Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [cardColor.withOpacity(0.8), cardColor],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: cardColor.withOpacity(0.3),
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Icon(icon, color: Colors.white, size: 32),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Icon(Icons.trending_up, color: Colors.white, size: 16),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
title,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.9),
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
if (subtitle != null) ...[
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
subtitle,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.7),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Séparateur avec texte =====
|
||||
static Widget buildDividerWithText(String text) {
|
||||
return Row(
|
||||
children: [
|
||||
Expanded(child: Divider(color: Colors.grey[300], thickness: 1)),
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16),
|
||||
child: Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: Colors.grey[600],
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
Expanded(child: Divider(color: Colors.grey[300], thickness: 1)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Liste vide stylée =====
|
||||
static Widget buildEmptyState({
|
||||
required String message,
|
||||
String? subtitle,
|
||||
IconData? icon,
|
||||
VoidCallback? onRefresh,
|
||||
}) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
icon ?? Icons.inbox_outlined,
|
||||
size: 80,
|
||||
color: Colors.grey[400],
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
message,
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.grey[700],
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
if (subtitle != null) ...[
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
subtitle,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[500]),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
],
|
||||
if (onRefresh != null) ...[
|
||||
SizedBox(height: 24),
|
||||
ElevatedButton.icon(
|
||||
onPressed: onRefresh,
|
||||
icon: Icon(Icons.refresh),
|
||||
label: Text('Actualiser'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Color(0xFF006699),
|
||||
foregroundColor: Colors.white,
|
||||
padding: EdgeInsets.symmetric(horizontal: 24, vertical: 12),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Dialog de confirmation =====
|
||||
static Future<bool> showConfirmDialog({
|
||||
required BuildContext context,
|
||||
required String title,
|
||||
required String message,
|
||||
String confirmText = 'Confirmer',
|
||||
String cancelText = 'Annuler',
|
||||
Color? confirmColor,
|
||||
IconData? icon,
|
||||
}) async {
|
||||
final result = await showDialog<bool>(
|
||||
context: context,
|
||||
builder:
|
||||
(context) => AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
if (icon != null) ...[
|
||||
Icon(icon, color: confirmColor ?? Color(0xFF006699)),
|
||||
SizedBox(width: 12),
|
||||
],
|
||||
Expanded(child: Text(title, style: TextStyle(fontSize: 18))),
|
||||
],
|
||||
),
|
||||
content: Text(
|
||||
message,
|
||||
style: TextStyle(fontSize: 14, color: Colors.grey[700]),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.of(context).pop(false),
|
||||
child: Text(
|
||||
cancelText,
|
||||
style: TextStyle(color: Colors.grey[600]),
|
||||
),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.of(context).pop(true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: confirmColor ?? Color(0xFF006699),
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Text(confirmText),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
return result ?? false;
|
||||
}
|
||||
|
||||
/// ===== NOUVEAU: Badge de statut =====
|
||||
static Widget buildStatusBadge({
|
||||
required String text,
|
||||
required bool isActive,
|
||||
double fontSize = 12,
|
||||
}) {
|
||||
return Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
isActive
|
||||
? Colors.green.withOpacity(0.1)
|
||||
: Colors.orange.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color:
|
||||
isActive
|
||||
? Colors.green.withOpacity(0.3)
|
||||
: Colors.orange.withOpacity(0.3),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: isActive ? Colors.green : Colors.orange,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
color: isActive ? Colors.green[700] : Colors.orange[700],
|
||||
fontSize: fontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// ===== NOUVELLE CLASSE: Utilitaires pour entreprises =====
|
||||
class EnterpriseWidgets {
|
||||
/// Badge entreprise
|
||||
static Widget buildEnterpriseBadge({
|
||||
required String enterpriseName,
|
||||
double fontSize = 12,
|
||||
EdgeInsets? padding,
|
||||
}) {
|
||||
return Container(
|
||||
padding: padding ?? EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Color(0xFF8B5CF6).withOpacity(0.8), Color(0xFF8B5CF6)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Color(0xFF8B5CF6).withOpacity(0.3),
|
||||
blurRadius: 8,
|
||||
offset: Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.business, color: Colors.white, size: fontSize + 2),
|
||||
SizedBox(width: 6),
|
||||
Flexible(
|
||||
child: Text(
|
||||
enterpriseName,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: fontSize,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Carte d'information entreprise
|
||||
static Widget buildEnterpriseInfoCard({
|
||||
required String enterpriseId,
|
||||
required String enterpriseName,
|
||||
required double balance,
|
||||
int? totalMembers,
|
||||
VoidCallback? onTap,
|
||||
}) {
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [Color(0xFF8B5CF6).withOpacity(0.8), Color(0xFF8B5CF6)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Color(0xFF8B5CF6).withOpacity(0.3),
|
||||
blurRadius: 15,
|
||||
offset: Offset(0, 8),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Icon(Icons.business, color: Colors.white, size: 32),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
enterpriseId,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
enterpriseName,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Solde disponible',
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
'${balance.toStringAsFixed(0)} FCFA',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (totalMembers != null)
|
||||
Column(
|
||||
children: [
|
||||
Icon(Icons.people, color: Colors.white, size: 24),
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
'$totalMembers',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'Membres',
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
fontSize: 10,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
2695
lib/pages/dashboard.dart
Normal file
2695
lib/pages/dashboard.dart
Normal file
File diff suppressed because it is too large
Load Diff
2348
lib/pages/form_service.dart
Normal file
2348
lib/pages/form_service.dart
Normal file
File diff suppressed because it is too large
Load Diff
1451
lib/pages/home.dart
Normal file
1451
lib/pages/home.dart
Normal file
File diff suppressed because it is too large
Load Diff
946
lib/pages/login.dart
Normal file
946
lib/pages/login.dart
Normal file
@@ -0,0 +1,946 @@
|
||||
// ===== lib/pages/login.dart AVEC SUPPORT ENTREPRISE =====
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:wtpe/widgets/wortis_logo.dart';
|
||||
import '../main.dart';
|
||||
import '../services/wortis_api_service.dart';
|
||||
import 'role_navigator.dart';
|
||||
|
||||
class LoginPage extends StatefulWidget {
|
||||
const LoginPage({super.key});
|
||||
|
||||
@override
|
||||
_LoginPageState createState() => _LoginPageState();
|
||||
}
|
||||
|
||||
class _LoginPageState extends State<LoginPage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
final _agentIdController = TextEditingController();
|
||||
final _pinController = TextEditingController();
|
||||
bool _obscurePin = true;
|
||||
bool _apiConnected = false;
|
||||
bool _testingConnection = false;
|
||||
|
||||
late AnimationController _animationController;
|
||||
late Animation<double> _fadeAnimation;
|
||||
late Animation<Offset> _slideAnimation;
|
||||
|
||||
// Couleurs Wortis
|
||||
static const Color primaryColor = Color(0xFF006699);
|
||||
static const Color secondaryColor = Color(0xFF0088CC);
|
||||
static const Color accentColor = Color(0xFFFF6B35);
|
||||
static const Color backgroundColor = Color(0xFFF8FAFC);
|
||||
static const Color surfaceColor = Colors.white;
|
||||
static const Color errorColor = Color(0xFFE53E3E);
|
||||
static const Color textPrimaryColor = Color(0xFF1A202C);
|
||||
static const Color textSecondaryColor = Color(0xFF718096);
|
||||
static const Color borderColor = Color(0xFFE2E8F0);
|
||||
static const Color enterpriseColor = Color(0xFF8B5CF6);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_setupAnimations();
|
||||
_testApiConnection();
|
||||
}
|
||||
|
||||
void _setupAnimations() {
|
||||
_animationController = AnimationController(
|
||||
duration: Duration(milliseconds: 1500),
|
||||
vsync: this,
|
||||
);
|
||||
|
||||
_fadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _animationController,
|
||||
curve: Interval(0.0, 0.8, curve: Curves.easeOut),
|
||||
),
|
||||
);
|
||||
|
||||
_slideAnimation = Tween<Offset>(
|
||||
begin: Offset(0, 0.3),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: _animationController,
|
||||
curve: Interval(0.3, 1.0, curve: Curves.easeOut),
|
||||
),
|
||||
);
|
||||
|
||||
_animationController.forward();
|
||||
}
|
||||
|
||||
Future<void> _testApiConnection() async {
|
||||
setState(() {
|
||||
_testingConnection = true;
|
||||
});
|
||||
|
||||
final isConnected = await AuthApiService.testConnection();
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_apiConnected = isConnected;
|
||||
_testingConnection = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _createTestUser() async {
|
||||
String? nom = await _showCreateUserDialog();
|
||||
if (nom == null || nom.isEmpty) return;
|
||||
|
||||
final result = await AuthApiService.createUser(nom, '1234');
|
||||
|
||||
if (result['success'] == true) {
|
||||
final agentId = result['generated_agent_id'];
|
||||
setState(() {
|
||||
_agentIdController.text = agentId;
|
||||
_pinController.text = '1234';
|
||||
});
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.white),
|
||||
SizedBox(width: 8),
|
||||
Expanded(child: Text('Utilisateur créé: $agentId / PIN: 1234')),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
);
|
||||
} else {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Erreur: ${result['message']}'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<String?> _showCreateUserDialog() async {
|
||||
final nameController = TextEditingController();
|
||||
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
builder:
|
||||
(context) => AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(Icons.person_add, color: primaryColor),
|
||||
SizedBox(width: 12),
|
||||
Text('Créer un utilisateur'),
|
||||
],
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: primaryColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: primaryColor.withOpacity(0.3)),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(Icons.info_outline, color: primaryColor, size: 20),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'L\'ID agent sera généré automatiquement (WRT####)',
|
||||
style: TextStyle(fontSize: 12, color: primaryColor),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: nameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nom complet',
|
||||
hintText: 'Ex: Jean Dupont',
|
||||
prefixIcon: Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
autofocus: true,
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context),
|
||||
child: Text('Annuler'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed:
|
||||
() => Navigator.pop(context, nameController.text.trim()),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: primaryColor,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
child: Text('Créer', style: TextStyle(color: Colors.white)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_agentIdController.dispose();
|
||||
_pinController.dispose();
|
||||
_animationController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _login() async {
|
||||
if (_formKey.currentState!.validate()) {
|
||||
final authController = Provider.of<AuthController>(
|
||||
context,
|
||||
listen: false,
|
||||
);
|
||||
|
||||
authController.clearError();
|
||||
|
||||
bool success = await authController.login(
|
||||
_agentIdController.text.trim(),
|
||||
_pinController.text.trim(),
|
||||
false,
|
||||
);
|
||||
|
||||
if (success && mounted) {
|
||||
// Afficher un message de bienvenue personnalisé
|
||||
final isEnterprise = authController.isEnterpriseMember;
|
||||
final accountType = isEnterprise ? 'Entreprise' : 'Agent';
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
isEnterprise ? Icons.business : Icons.person,
|
||||
color: Colors.white,
|
||||
size: 20,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Bienvenue ${authController.agentName}',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
if (isEnterprise &&
|
||||
authController.enterprise?.nomEntreprise != null) ...[
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
authController.enterprise!.nomEntreprise,
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.9),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Text(
|
||||
accountType,
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: isEnterprise ? enterpriseColor : Colors.green,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
duration: Duration(seconds: 2),
|
||||
margin: EdgeInsets.all(16),
|
||||
),
|
||||
);
|
||||
|
||||
// Navigation basée sur le rôle
|
||||
final userRole = authController.role ?? 'agent';
|
||||
RoleNavigator.navigateByRole(context, userRole);
|
||||
} else if (mounted) {
|
||||
final errorMessage =
|
||||
authController.errorMessage ?? 'Erreur de connexion';
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.error_outline, color: Colors.white, size: 24),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Connexion échouée',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(errorMessage, style: TextStyle(fontSize: 12)),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: errorColor,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
duration: Duration(seconds: 4),
|
||||
margin: EdgeInsets.all(16),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _openWifiSettings() async {
|
||||
try {
|
||||
const platform = MethodChannel('com.wortis.agent/settings');
|
||||
await platform.invokeMethod('exitKioskMode');
|
||||
await platform.invokeMethod('openWifiSettings');
|
||||
} catch (e) {
|
||||
print('Erreur ouverture WiFi: $e');
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Impossible d\'ouvrir les paramètres WiFi'),
|
||||
backgroundColor: Colors.orange,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: backgroundColor,
|
||||
body: SafeArea(
|
||||
child: SingleChildScrollView(
|
||||
physics: BouncingScrollPhysics(),
|
||||
padding: EdgeInsets.all(24),
|
||||
child: FadeTransition(
|
||||
opacity: _fadeAnimation,
|
||||
child: SlideTransition(
|
||||
position: _slideAnimation,
|
||||
child: Column(
|
||||
children: [
|
||||
SizedBox(height: 20),
|
||||
_buildApiStatusIndicator(),
|
||||
SizedBox(height: 20),
|
||||
_buildHeader(),
|
||||
SizedBox(height: 50),
|
||||
_buildLoginForm(),
|
||||
SizedBox(height: 30),
|
||||
_buildHelpSection(),
|
||||
SizedBox(height: 20),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildApiStatusIndicator() {
|
||||
return Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
_testingConnection
|
||||
? Colors.orange.withOpacity(0.1)
|
||||
: _apiConnected
|
||||
? Colors.green.withOpacity(0.1)
|
||||
: Colors.red.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
border: Border.all(
|
||||
color:
|
||||
_testingConnection
|
||||
? Colors.orange.withOpacity(0.3)
|
||||
: _apiConnected
|
||||
? Colors.green.withOpacity(0.3)
|
||||
: Colors.red.withOpacity(0.3),
|
||||
width: 1.5,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (_testingConnection) ...[
|
||||
SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.orange),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Test connexion...',
|
||||
style: TextStyle(
|
||||
color: Colors.orange.shade700,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
] else ...[
|
||||
Container(
|
||||
padding: EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
_apiConnected
|
||||
? Colors.green.withOpacity(0.2)
|
||||
: Colors.red.withOpacity(0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
_apiConnected
|
||||
? Icons.cloud_done_rounded
|
||||
: Icons.cloud_off_rounded,
|
||||
size: 16,
|
||||
color:
|
||||
_apiConnected ? Colors.green.shade700 : Colors.red.shade700,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
_apiConnected ? 'API connectée' : 'API déconnectée',
|
||||
style: TextStyle(
|
||||
color:
|
||||
_apiConnected ? Colors.green.shade700 : Colors.red.shade700,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
GestureDetector(
|
||||
onTap: _testApiConnection,
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.5),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.refresh_rounded,
|
||||
size: 16,
|
||||
color:
|
||||
_apiConnected
|
||||
? Colors.green.shade700
|
||||
: Colors.red.shade700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHeader() {
|
||||
return Column(
|
||||
children: [
|
||||
WortisLogoWidget(size: 100, isWhite: false, withShadow: true),
|
||||
SizedBox(height: 24),
|
||||
ShaderMask(
|
||||
shaderCallback:
|
||||
(bounds) => LinearGradient(
|
||||
colors: [primaryColor, secondaryColor],
|
||||
).createShader(bounds),
|
||||
child: Text(
|
||||
'WORTIS AGENT',
|
||||
style: TextStyle(
|
||||
fontSize: 28,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
letterSpacing: 2,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Connexion à votre espace',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: textSecondaryColor,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
// Badges des types de comptes supportés
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
_buildAccountTypeBadge(
|
||||
icon: Icons.person,
|
||||
label: 'Agent',
|
||||
color: primaryColor,
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
_buildAccountTypeBadge(
|
||||
icon: Icons.business,
|
||||
label: 'Entreprise',
|
||||
color: enterpriseColor,
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAccountTypeBadge({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required Color color,
|
||||
}) {
|
||||
return Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: color.withOpacity(0.3), width: 1),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, color: color, size: 14),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoginForm() {
|
||||
return Container(
|
||||
padding: EdgeInsets.all(28),
|
||||
decoration: BoxDecoration(
|
||||
color: surfaceColor,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.08),
|
||||
blurRadius: 20,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Form(
|
||||
key: _formKey,
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: primaryColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.login_rounded,
|
||||
color: primaryColor,
|
||||
size: 24,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Text(
|
||||
'Identifiants',
|
||||
style: TextStyle(
|
||||
fontSize: 20,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: textPrimaryColor,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
SizedBox(height: 24),
|
||||
|
||||
_buildTextField(
|
||||
controller: _agentIdController,
|
||||
label: 'ID Agent',
|
||||
hint: 'Entrez votre identifiant',
|
||||
prefixIcon: Icons.badge_outlined,
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'L\'ID agent est requis';
|
||||
}
|
||||
if (value.length < 3) {
|
||||
return 'ID agent trop court (min. 3 caractères)';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
|
||||
SizedBox(height: 20),
|
||||
|
||||
_buildTextField(
|
||||
controller: _pinController,
|
||||
label: 'Code PIN',
|
||||
hint: 'Entrez votre code PIN',
|
||||
prefixIcon: Icons.lock_outline,
|
||||
obscureText: _obscurePin,
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_obscurePin
|
||||
? Icons.visibility_outlined
|
||||
: Icons.visibility_off_outlined,
|
||||
color: textSecondaryColor,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_obscurePin = !_obscurePin;
|
||||
});
|
||||
},
|
||||
),
|
||||
validator: (value) {
|
||||
if (value == null || value.isEmpty) {
|
||||
return 'Le code PIN est requis';
|
||||
}
|
||||
if (value.length < 4) {
|
||||
return 'Le PIN doit contenir au moins 4 chiffres';
|
||||
}
|
||||
return null;
|
||||
},
|
||||
),
|
||||
|
||||
SizedBox(height: 32),
|
||||
|
||||
Consumer<AuthController>(
|
||||
builder: (context, authController, child) {
|
||||
return _buildLoginButton(authController);
|
||||
},
|
||||
),
|
||||
|
||||
SizedBox(height: 16),
|
||||
|
||||
Container(
|
||||
width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _openWifiSettings,
|
||||
icon: Icon(Icons.wifi_find_rounded, size: 20),
|
||||
label: Text('Paramètres WiFi'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: EdgeInsets.symmetric(vertical: 14),
|
||||
side: BorderSide(color: primaryColor, width: 1.5),
|
||||
foregroundColor: primaryColor,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
// Bouton de test (commenté par défaut)
|
||||
// if (_apiConnected) ...[
|
||||
// SizedBox(height: 16),
|
||||
// TextButton.icon(
|
||||
// onPressed: _createTestUser,
|
||||
// icon: Icon(Icons.add_circle_outline, size: 18),
|
||||
// label: Text('Créer utilisateur test'),
|
||||
// style: TextButton.styleFrom(foregroundColor: primaryColor),
|
||||
// ),
|
||||
// ],
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildTextField({
|
||||
required TextEditingController controller,
|
||||
required String label,
|
||||
required String hint,
|
||||
required IconData prefixIcon,
|
||||
Widget? suffixIcon,
|
||||
bool obscureText = false,
|
||||
String? Function(String?)? validator,
|
||||
}) {
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: textPrimaryColor,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
TextFormField(
|
||||
controller: controller,
|
||||
validator: validator,
|
||||
obscureText: obscureText,
|
||||
decoration: InputDecoration(
|
||||
hintText: hint,
|
||||
hintStyle: TextStyle(color: textSecondaryColor),
|
||||
prefixIcon: Icon(prefixIcon, color: primaryColor),
|
||||
suffixIcon: suffixIcon,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: borderColor),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: borderColor),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: primaryColor, width: 2),
|
||||
),
|
||||
errorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: errorColor),
|
||||
),
|
||||
focusedErrorBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: BorderSide(color: errorColor, width: 2),
|
||||
),
|
||||
contentPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 16),
|
||||
filled: true,
|
||||
fillColor: backgroundColor.withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoginButton(AuthController authController) {
|
||||
return Container(
|
||||
height: 54,
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [primaryColor, secondaryColor],
|
||||
begin: Alignment.centerLeft,
|
||||
end: Alignment.centerRight,
|
||||
),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: primaryColor.withOpacity(0.4),
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: ElevatedButton(
|
||||
onPressed: authController.isLoading ? null : _login,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Colors.transparent,
|
||||
shadowColor: Colors.transparent,
|
||||
foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child:
|
||||
authController.isLoading
|
||||
? SizedBox(
|
||||
width: 24,
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
|
||||
),
|
||||
)
|
||||
: Row(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.login_rounded, size: 22),
|
||||
SizedBox(width: 10),
|
||||
Text(
|
||||
'SE CONNECTER',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
letterSpacing: 1.2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildHelpSection() {
|
||||
return Container(
|
||||
padding: EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [
|
||||
secondaryColor.withOpacity(0.1),
|
||||
primaryColor.withOpacity(0.05),
|
||||
],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: secondaryColor.withOpacity(0.3), width: 1.5),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: primaryColor.withOpacity(0.2),
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
Icons.help_outline_rounded,
|
||||
color: primaryColor,
|
||||
size: 32,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Besoin d\'aide ?',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: textPrimaryColor,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.7),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
|
||||
// child: Column(
|
||||
// children: [
|
||||
// Row(
|
||||
// children: [
|
||||
// Icon(Icons.person, color: primaryColor, size: 16),
|
||||
// SizedBox(width: 8),
|
||||
// Expanded(
|
||||
// child: Text(
|
||||
// 'Compte Agent - Accès individuel',
|
||||
// style: TextStyle(fontSize: 13, color: textPrimaryColor),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// SizedBox(height: 8),
|
||||
// Row(
|
||||
// children: [
|
||||
// Icon(Icons.business, color: enterpriseColor, size: 16),
|
||||
// SizedBox(width: 8),
|
||||
// Expanded(
|
||||
// child: Text(
|
||||
// 'Compte Entreprise - Solde partagé',
|
||||
// style: TextStyle(fontSize: 13, color: textPrimaryColor),
|
||||
// ),
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
// ],
|
||||
// ),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
decoration: BoxDecoration(
|
||||
color: primaryColor,
|
||||
borderRadius: BorderRadius.circular(25),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: primaryColor.withOpacity(0.3),
|
||||
blurRadius: 8,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.phone, color: Colors.white, size: 18),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Support: 50 05',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
3973
lib/pages/main_navigation.dart
Normal file
3973
lib/pages/main_navigation.dart
Normal file
File diff suppressed because it is too large
Load Diff
1
lib/pages/profile.dart
Normal file
1
lib/pages/profile.dart
Normal file
@@ -0,0 +1 @@
|
||||
// TODO Implement this library.
|
||||
2240
lib/pages/rechargeur_dashboard.dart
Normal file
2240
lib/pages/rechargeur_dashboard.dart
Normal file
File diff suppressed because it is too large
Load Diff
85
lib/pages/role_navigator.dart
Normal file
85
lib/pages/role_navigator.dart
Normal file
@@ -0,0 +1,85 @@
|
||||
// lib/utils/role_navigator.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import '../pages/main_navigation.dart';
|
||||
import '../pages/admin_dashboard.dart';
|
||||
import '../pages/rechargeur_dashboard.dart';
|
||||
|
||||
class RoleNavigator {
|
||||
/// Naviguer vers la page appropriée selon le rôle
|
||||
static void navigateByRole(BuildContext context, String role) {
|
||||
Widget destination;
|
||||
|
||||
switch (role.toLowerCase()) {
|
||||
case 'admin':
|
||||
destination = AdminDashboard();
|
||||
break;
|
||||
case 'rechargeur':
|
||||
destination = RechargeurDashboard();
|
||||
break;
|
||||
case 'agent':
|
||||
default:
|
||||
destination = MainNavigationPage(initialIndex: 0);
|
||||
break;
|
||||
}
|
||||
|
||||
Navigator.of(context).pushReplacement(
|
||||
PageRouteBuilder(
|
||||
pageBuilder: (context, animation, secondaryAnimation) => destination,
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) {
|
||||
return FadeTransition(
|
||||
opacity: animation,
|
||||
child: SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: Offset(0.1, 0),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
||||
),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
},
|
||||
transitionDuration: Duration(milliseconds: 600),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Obtenir l'icône selon le rôle
|
||||
static IconData getRoleIcon(String role) {
|
||||
switch (role.toLowerCase()) {
|
||||
case 'admin':
|
||||
return Icons.admin_panel_settings;
|
||||
case 'rechargeur':
|
||||
return Icons.add_circle;
|
||||
case 'agent':
|
||||
default:
|
||||
return Icons.person;
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtenir la couleur selon le rôle
|
||||
static Color getRoleColor(String role) {
|
||||
switch (role.toLowerCase()) {
|
||||
case 'admin':
|
||||
return Color(0xFFE53E3E); // Rouge
|
||||
case 'rechargeur':
|
||||
return Color(0xFF38A169); // Vert
|
||||
case 'agent':
|
||||
default:
|
||||
return Color(0xFF006699); // Bleu Wortis
|
||||
}
|
||||
}
|
||||
|
||||
/// Obtenir le nom d'affichage du rôle
|
||||
static String getRoleDisplayName(String role) {
|
||||
switch (role.toLowerCase()) {
|
||||
case 'admin':
|
||||
return 'Administrateur';
|
||||
case 'rechargeur':
|
||||
return 'Rechargeur';
|
||||
case 'agent':
|
||||
default:
|
||||
return 'Agent';
|
||||
}
|
||||
}
|
||||
}
|
||||
371
lib/pages/service.json
Normal file
371
lib/pages/service.json
Normal file
@@ -0,0 +1,371 @@
|
||||
{
|
||||
"_id": {
|
||||
"$oid": "67800eeeaff834f203a70cad"
|
||||
},
|
||||
"name": "Cartes Play Store",
|
||||
"Type_Service": "PaiementImmediat",
|
||||
"SecteurActivite": "Cartes Virtuelles",
|
||||
"icon": "credit_score_outlined",
|
||||
"banner": "https://apigede.wortispay.cg/apk-mobile/banner_service/wsgaming.jpg",
|
||||
"description": "Achetez des cartes Google Play pour accéder à des applications, des jeux, de la musique et bien plus encore sur votre appareil Android.\nVeuillez vous rassurer que votre compte est bien localisé en France.",
|
||||
"tite_description": "Potentiel déverrouillé",
|
||||
"status": true,
|
||||
"error_400": "Pas encore defenit",
|
||||
"error_500": "Quelque chose a mal fonctioné",
|
||||
"comment_payer": "1.\tSélectionnez le montant de la carte Play Store.\n\n2.\tRenseignez vos détails pour l'achat.\n\n3.\tPayez via Mobile Money ou carte bancaire.",
|
||||
"button_service": "Payer",
|
||||
"bouton_list": "Ajouter un élément",
|
||||
"steps": [
|
||||
{
|
||||
"request": "POST",
|
||||
"fields": [
|
||||
{
|
||||
"name": "Service",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "Google Play",
|
||||
"label": "Google Play"
|
||||
},
|
||||
{
|
||||
"value": "Apple",
|
||||
"label": "Apple"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"link": "https://api.live.wortis.cg/verify_card_apk",
|
||||
"title_button": "Suivant",
|
||||
"body": {
|
||||
"service": "Service"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": "POST",
|
||||
"fields": [
|
||||
{
|
||||
"name": "typeCard",
|
||||
"type": "selecteur",
|
||||
"label": "Choisir votre forfait",
|
||||
"options": [
|
||||
{
|
||||
"value": "Google Play Essentiel 10 €/8 913 Fcfa",
|
||||
"label": "Google Play Essentiel\n10 €/8 913 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Google Play Découverte 15 €/13 369 Fcfa",
|
||||
"label": "Google Play Découverte\n15 €/13 369 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Google Avancée 25 €/22 281 Fcfa",
|
||||
"label": "Google Avancée\n25 €/22 281 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Google Deluxe 50€ 50 €/44 563 Fcfa",
|
||||
"label": "Google Deluxe 50€\n50 €/44 563 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Google Deluxe 100€ 100 €/89 125 Fcfa",
|
||||
"label": "Google Deluxe 100€\n100 €/89 125 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "Google Play"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "typeCard",
|
||||
"type": "selecteur",
|
||||
"label": "Choisir votre forfait",
|
||||
"options": [
|
||||
{
|
||||
"value": "Apple Essentiel 10 €/8 913 Fcfa",
|
||||
"label": "Apple Essentiel\n 10 €/8 913 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Apple Découverte 15 €/13 369 Fcfa",
|
||||
"label": "Apple Découverte \n15 €/13 369 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Apple Avancée 25 €/22 281 Fcfa",
|
||||
"label": "Apple Avancée \n25 €/22 281 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Apple Deluxe 50 €/44 563 Fcfa",
|
||||
"label": "Apple Deluxe \n50 €/44 563 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "Apple"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "nom",
|
||||
"type": "text",
|
||||
"label": "Nom et Prénoms",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "email",
|
||||
"type": "text",
|
||||
"label": "Email",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "mobile",
|
||||
"type": "number",
|
||||
"label": "Numéro de paiement",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "token",
|
||||
"type": "hidden",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"nom": "nom",
|
||||
"service": "service_selected",
|
||||
"email": "email",
|
||||
"mobile": "mobile",
|
||||
"typeCard": "typeCard",
|
||||
"token": "token"
|
||||
},
|
||||
"link_momo": "https://api.live.wortis.cg/commande_card_apk",
|
||||
"api_fields": {
|
||||
"service_selected": {
|
||||
"type": "text",
|
||||
"readonly": true,
|
||||
"label": "Service Sélectionné",
|
||||
"key": "service"
|
||||
}
|
||||
},
|
||||
"link_cb": "https://api.live.wortis.cg/commande_card_apk"
|
||||
}
|
||||
],
|
||||
"logo": "https://apigede.wortispay.cg/apk-mobile/service_logo/game.png"
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
{
|
||||
"_id": {
|
||||
"$oid": "677d5e75c11a9f6c491f288e"
|
||||
},
|
||||
"name": "Cartes Gaming",
|
||||
"Type_Service": "PaiementImmediat",
|
||||
"SecteurActivite": "Cartes Virtuelles",
|
||||
"icon": "credit_score_outlined",
|
||||
"banner": "https://apigede.wortispay.cg/apk-mobile/banner_service/wsgaming.jpg",
|
||||
"description": "Achetez des cartes de jeu en ligne pour vos plateformes favorites (PlayStation, Xbox, Steam, etc.). Profitez d'une expérience de jeu ininterrompue et d'un accès rapide à des contenus premium.",
|
||||
"tite_description": "Accès jeux",
|
||||
"status": true,
|
||||
"error_400": "Pas encore defenit",
|
||||
"error_500": "Quelque chose a mal fonctioné",
|
||||
"comment_payer": "1.\tSélectionnez la carte de jeu souhaitée.\n\n2.\tIndiquez le montant et vos détails de livraison.\n\n3.\tProcédez au paiement via Mobile Money ou carte bancaire.",
|
||||
"button_service": "Payer",
|
||||
"bouton_list": "Ajouter un élément",
|
||||
"steps": [
|
||||
{
|
||||
"request": "POST",
|
||||
"fields": [
|
||||
{
|
||||
"name": "Service",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "Steam",
|
||||
"label": "Steam"
|
||||
},
|
||||
{
|
||||
"value": "Nitendo",
|
||||
"label": "Nitendo"
|
||||
},
|
||||
{
|
||||
"value": "Fortnite",
|
||||
"label": "Fortnite"
|
||||
},
|
||||
{
|
||||
"value": "PlayStation",
|
||||
"label": "PlayStation"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"link": "https://api.live.wortis.cg/verify_card_apk",
|
||||
"title_button": "Suivant",
|
||||
"body": {
|
||||
"service": "Service"
|
||||
}
|
||||
},
|
||||
{
|
||||
"request": "POST",
|
||||
"fields": [
|
||||
{
|
||||
"name": "TypeCard",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "Steam Essentiel 10 €/ 8 913 Fcfa",
|
||||
"label": "Steam Essentiel \n10 €/ 8 913 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Steam Standard 20 €/17 825 Fcfa",
|
||||
"label": "Steam Standard \n20 €/17 825 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Steam Delux 50 €/ 44 563 Fcfa",
|
||||
"label": "Steam Delux \n50 €/ 44 563 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Steam Ultime 100 €/ 89 125 Fcfa",
|
||||
"label": "Steam Ultime \n100 €/ 89 125 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "Steam"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "TypeCard",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "Nitendo Décourte 15 €/ 13 369 Fcfa",
|
||||
"label": "Nitendo Décourte \n15 €/ 13 369 Fcfa"
|
||||
},
|
||||
{
|
||||
"value": "Nitendo Avancée 25 €/22 281 Fcfa",
|
||||
"label": "Nitendo Avancée \n25 €/22 281 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Nitendo Delux 50 €/ 44 563 Fcfa",
|
||||
"label": "Nitendo Delux \n50 €/ 44 563 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Nitendo Ultime 100 €/ 89 125 Fcfa",
|
||||
"label": "Nitendo Ultime \n100 €/ 89 125 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "Nitendo"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "TypeCard",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "Fortnite-1 8.99 €/8 012 Fcfa",
|
||||
"label": "Fortnite-1 \n8.99 €/8 012 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Fortnite-2 22.99 €/20 490 Fcfa",
|
||||
"label": "Fortnite-2 \n22.99 €/20 490 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Fortnite-5 36.99 €/32 967 Fcfa",
|
||||
"label": "Fortnite-5 \n36.99 €/32 967 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "Fortnite-13 89.99 €/80 204 Fcfa",
|
||||
"label": "Fortnite-13 \n89.99 €/80 204 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "Fortnite"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "TypeCard",
|
||||
"type": "selecteur",
|
||||
"options": [
|
||||
{
|
||||
"value": "PS Essentiel 10 €/8 913 Fcfa",
|
||||
"label": "PS Essentiel \n10 €/8 913 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "PS Standard 20 €/17 825 Fcfa",
|
||||
"label": "PS Standard \n20 €/17 825 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "PS Prenium 50 €/44 463 Fcfa",
|
||||
"label": "PS Prenium \n50 €/44 463 Fcfa\n"
|
||||
},
|
||||
{
|
||||
"value": "PS Avant-Garde 100 €/89 125 Fcfa",
|
||||
"label": "PS Avant-Garde \n100 €/89 125 Fcfa"
|
||||
}
|
||||
],
|
||||
"dependencies": [
|
||||
{
|
||||
"field": "service_selected",
|
||||
"value": "PlayStation"
|
||||
}
|
||||
],
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "Nom et Prénoms",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "Email",
|
||||
"type": "text",
|
||||
"required": true
|
||||
},
|
||||
{
|
||||
"name": "Numéro de paiement",
|
||||
"type": "number",
|
||||
"required": true
|
||||
}
|
||||
],
|
||||
"body": {
|
||||
"nom": "Nom et Prénoms",
|
||||
"service": "service_selected",
|
||||
"email": "Email",
|
||||
"mobile": "Numéro de paiement",
|
||||
"typeCard": "typeCard"
|
||||
},
|
||||
"link_momo": "https://api.live.wortis.cg/commande_card_apk",
|
||||
"api_fields": {
|
||||
"service_selected": {
|
||||
"type": "text",
|
||||
"readonly": true,
|
||||
"label": "Service Sélectionné",
|
||||
"key": "service"
|
||||
}
|
||||
},
|
||||
"link_cb": "https://api.live.wortis.cg/commande_card_apk"
|
||||
}
|
||||
],
|
||||
"logo": "https://apigede.wortispay.cg/apk-mobile/service_logo/game.png"
|
||||
}
|
||||
157
lib/pages/session_manager.dart
Normal file
157
lib/pages/session_manager.dart
Normal file
@@ -0,0 +1,157 @@
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
class SessionManager {
|
||||
static const String _keyUserId = 'user_id';
|
||||
static const String _keyToken = 'user_token';
|
||||
static const String _keyRole = 'user_role';
|
||||
static const String _keyPIN = 'user_pin'; // Ajouté pour le PIN
|
||||
static const String _keyLoginDate = 'login_date';
|
||||
static const String _keyIsLoggedIn = 'is_logged_in';
|
||||
|
||||
static SessionManager? _instance;
|
||||
static SharedPreferences? _prefs;
|
||||
|
||||
SessionManager._internal();
|
||||
|
||||
factory SessionManager() {
|
||||
_instance ??= SessionManager._internal();
|
||||
return _instance!;
|
||||
}
|
||||
|
||||
Future<void> _initPrefs() async {
|
||||
_prefs ??= await SharedPreferences.getInstance();
|
||||
}
|
||||
|
||||
/// Sauvegarder une session
|
||||
Future<void> saveSession(
|
||||
String userId, {
|
||||
String? token,
|
||||
String? role,
|
||||
String? pinkey, // Ajouté pour le PIN
|
||||
}) async {
|
||||
await _initPrefs();
|
||||
|
||||
await _prefs!.setString(_keyUserId, userId);
|
||||
await _prefs!.setBool(_keyIsLoggedIn, true);
|
||||
await _prefs!.setString(_keyLoginDate, DateTime.now().toIso8601String());
|
||||
|
||||
if (token != null) {
|
||||
await _prefs!.setString(_keyToken, token);
|
||||
}
|
||||
|
||||
if (role != null) {
|
||||
await _prefs!.setString(_keyRole, role);
|
||||
}
|
||||
|
||||
if (pinkey != null) {
|
||||
await _prefs!.setString(_keyPIN, pinkey);
|
||||
}
|
||||
|
||||
print('Session sauvegardée pour $userId');
|
||||
}
|
||||
|
||||
/// Vérifier si l'utilisateur est connecté
|
||||
Future<bool> isLoggedIn() async {
|
||||
await _initPrefs();
|
||||
return _prefs!.getBool(_keyIsLoggedIn) ?? false;
|
||||
}
|
||||
|
||||
/// Récupérer l'ID utilisateur
|
||||
Future<String?> getUserId() async {
|
||||
await _initPrefs();
|
||||
return _prefs!.getString(_keyUserId);
|
||||
}
|
||||
|
||||
/// Récupérer le token
|
||||
Future<String?> getToken() async {
|
||||
await _initPrefs();
|
||||
return _prefs!.getString(_keyToken);
|
||||
}
|
||||
|
||||
/// Récupérer le rôle
|
||||
Future<String?> getRole() async {
|
||||
await _initPrefs();
|
||||
return _prefs!.getString(_keyRole);
|
||||
}
|
||||
|
||||
/// Récupérer le PIN (nouvelle méthode)
|
||||
Future<String?> getPIN() async {
|
||||
await _initPrefs();
|
||||
return _prefs!.getString(_keyPIN);
|
||||
}
|
||||
|
||||
/// Méthode synchrone pour le PIN (utilisée dans AuthController)
|
||||
String? getPINSync() {
|
||||
return _prefs?.getString(_keyPIN);
|
||||
}
|
||||
|
||||
/// Récupérer la date de connexion
|
||||
Future<DateTime?> getLoginDate() async {
|
||||
await _initPrefs();
|
||||
String? dateString = _prefs!.getString(_keyLoginDate);
|
||||
if (dateString != null) {
|
||||
return DateTime.parse(dateString);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Effacer la session
|
||||
Future<void> clearSession() async {
|
||||
await _initPrefs();
|
||||
|
||||
await _prefs!.remove(_keyUserId);
|
||||
await _prefs!.remove(_keyToken);
|
||||
await _prefs!.remove(_keyRole);
|
||||
await _prefs!.remove(_keyPIN); // Supprimer aussi le PIN
|
||||
await _prefs!.remove(_keyLoginDate);
|
||||
await _prefs!.setBool(_keyIsLoggedIn, false);
|
||||
|
||||
print('Session effacée');
|
||||
}
|
||||
|
||||
/// Mettre à jour le token uniquement
|
||||
Future<void> updateToken(String newToken) async {
|
||||
await _initPrefs();
|
||||
await _prefs!.setString(_keyToken, newToken);
|
||||
}
|
||||
|
||||
/// Vérifier si la session a expiré
|
||||
Future<bool> isSessionExpired({Duration? maxAge}) async {
|
||||
maxAge ??= Duration(days: 30); // 30 jours par défaut
|
||||
|
||||
DateTime? loginDate = await getLoginDate();
|
||||
if (loginDate == null) return true;
|
||||
|
||||
return DateTime.now().difference(loginDate) > maxAge;
|
||||
}
|
||||
|
||||
/// Obtenir toutes les informations de session
|
||||
Future<Map<String, dynamic>> getSessionInfo() async {
|
||||
await _initPrefs();
|
||||
|
||||
return {
|
||||
'user_id': await getUserId(),
|
||||
'token': await getToken(),
|
||||
'role': await getRole(),
|
||||
'pin': await getPIN(),
|
||||
'login_date': await getLoginDate(),
|
||||
'is_logged_in': await isLoggedIn(),
|
||||
'is_expired': await isSessionExpired(),
|
||||
};
|
||||
}
|
||||
|
||||
/// Debug: Afficher les informations de session
|
||||
Future<void> debugPrintSession() async {
|
||||
Map<String, dynamic> sessionInfo = await getSessionInfo();
|
||||
print('=== Informations de Session ===');
|
||||
sessionInfo.forEach((key, value) {
|
||||
if (key == 'pin' || key == 'token') {
|
||||
// Masquer les données sensibles
|
||||
print('$key: ${value?.toString().substring(0, 4) ?? 'null'}...');
|
||||
} else {
|
||||
print('$key: $value');
|
||||
}
|
||||
});
|
||||
print('================================');
|
||||
}
|
||||
}
|
||||
533
lib/pages/splash_screen.dart
Normal file
533
lib/pages/splash_screen.dart
Normal file
@@ -0,0 +1,533 @@
|
||||
// ===== lib/pages/splash_screen.dart MODIFIÉ AVEC API =====
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../main.dart'; // Pour AuthController
|
||||
import '../widgets/wortis_logo.dart'; // NOUVEAU: Import du widget logo
|
||||
import 'login.dart';
|
||||
import 'main_navigation.dart';
|
||||
|
||||
class SplashScreen extends StatefulWidget {
|
||||
const SplashScreen({super.key});
|
||||
|
||||
@override
|
||||
_SplashScreenState createState() => _SplashScreenState();
|
||||
}
|
||||
|
||||
class _SplashScreenState extends State<SplashScreen>
|
||||
with TickerProviderStateMixin {
|
||||
late AnimationController _logoController;
|
||||
late AnimationController _textController;
|
||||
late AnimationController _loadingController;
|
||||
|
||||
late Animation<double> _logoFadeAnimation;
|
||||
late Animation<double> _logoScaleAnimation;
|
||||
late Animation<Offset> _logoSlideAnimation;
|
||||
|
||||
late Animation<double> _textFadeAnimation;
|
||||
late Animation<Offset> _textSlideAnimation;
|
||||
|
||||
late Animation<double> _loadingFadeAnimation;
|
||||
|
||||
String _statusMessage = 'Initialisation...';
|
||||
bool _hasApiConnection = false;
|
||||
|
||||
// Couleurs Wortis
|
||||
static const Color primaryColor = Color(0xFF006699);
|
||||
static const Color secondaryColor = Color(0xFF0088CC);
|
||||
static const Color accentColor = Color(0xFFFF6B35);
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_setupAnimations();
|
||||
_startAnimationSequence();
|
||||
_checkAuthStatus();
|
||||
}
|
||||
|
||||
void _setupAnimations() {
|
||||
_logoController = AnimationController(
|
||||
duration: Duration(milliseconds: 2000),
|
||||
vsync: this,
|
||||
);
|
||||
|
||||
_textController = AnimationController(
|
||||
duration: Duration(milliseconds: 1500),
|
||||
vsync: this,
|
||||
);
|
||||
|
||||
_loadingController = AnimationController(
|
||||
duration: Duration(milliseconds: 1200),
|
||||
vsync: this,
|
||||
);
|
||||
|
||||
_logoFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _logoController,
|
||||
curve: Interval(0.0, 0.6, curve: Curves.easeOut),
|
||||
),
|
||||
);
|
||||
|
||||
_logoScaleAnimation = Tween<double>(begin: 0.3, end: 1.0).animate(
|
||||
CurvedAnimation(
|
||||
parent: _logoController,
|
||||
curve: Interval(0.0, 0.8, curve: Curves.elasticOut),
|
||||
),
|
||||
);
|
||||
|
||||
_logoSlideAnimation = Tween<Offset>(
|
||||
begin: Offset(0, -0.5),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(
|
||||
parent: _logoController,
|
||||
curve: Interval(0.2, 1.0, curve: Curves.easeOutCubic),
|
||||
),
|
||||
);
|
||||
|
||||
_textFadeAnimation = Tween<double>(
|
||||
begin: 0.0,
|
||||
end: 1.0,
|
||||
).animate(CurvedAnimation(parent: _textController, curve: Curves.easeOut));
|
||||
|
||||
_textSlideAnimation = Tween<Offset>(
|
||||
begin: Offset(0, 0.3),
|
||||
end: Offset.zero,
|
||||
).animate(CurvedAnimation(parent: _textController, curve: Curves.easeOut));
|
||||
|
||||
_loadingFadeAnimation = Tween<double>(begin: 0.0, end: 1.0).animate(
|
||||
CurvedAnimation(parent: _loadingController, curve: Curves.easeIn),
|
||||
);
|
||||
}
|
||||
|
||||
void _startAnimationSequence() async {
|
||||
_logoController.forward();
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 800));
|
||||
if (mounted) _textController.forward();
|
||||
|
||||
await Future.delayed(Duration(milliseconds: 400));
|
||||
if (mounted) _loadingController.repeat();
|
||||
}
|
||||
|
||||
void _updateStatus(String message) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_statusMessage = message;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
void _checkAuthStatus() async {
|
||||
try {
|
||||
// Étape 1: Test de connexion API
|
||||
_updateStatus('Test de connexion API...');
|
||||
await Future.delayed(Duration(milliseconds: 800));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
final authController = Provider.of<AuthController>(
|
||||
context,
|
||||
listen: false,
|
||||
);
|
||||
|
||||
// Tester la connexion à l'API
|
||||
_hasApiConnection = await authController.testApiConnection();
|
||||
|
||||
if (_hasApiConnection) {
|
||||
_updateStatus('API connectée ✓');
|
||||
await Future.delayed(Duration(milliseconds: 600));
|
||||
} else {
|
||||
_updateStatus('Mode hors ligne');
|
||||
await Future.delayed(Duration(milliseconds: 600));
|
||||
}
|
||||
|
||||
// Étape 2: Vérification de l'authentification
|
||||
_updateStatus('Vérification de session...');
|
||||
await Future.delayed(Duration(milliseconds: 800));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
bool isLoggedIn = await authController.checkLoginStatus(context);
|
||||
print('L\'utilisateur est : $isLoggedIn');
|
||||
|
||||
_updateStatus('Finalisation...');
|
||||
await Future.delayed(Duration(milliseconds: 500));
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Animation de sortie
|
||||
await _logoController.reverse();
|
||||
|
||||
if (!mounted) return;
|
||||
|
||||
// Navigation
|
||||
Navigator.of(context).pushReplacement(
|
||||
PageRouteBuilder(
|
||||
pageBuilder: (context, animation, secondaryAnimation) {
|
||||
return isLoggedIn
|
||||
? MainNavigationPage(initialIndex: 0)
|
||||
: LoginPage();
|
||||
},
|
||||
transitionsBuilder: (context, animation, secondaryAnimation, child) {
|
||||
return FadeTransition(
|
||||
opacity: animation,
|
||||
child: SlideTransition(
|
||||
position: Tween<Offset>(
|
||||
begin: Offset(0.0, 0.1),
|
||||
end: Offset.zero,
|
||||
).animate(
|
||||
CurvedAnimation(parent: animation, curve: Curves.easeOut),
|
||||
),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
},
|
||||
transitionDuration: Duration(milliseconds: 600),
|
||||
),
|
||||
);
|
||||
} catch (e) {
|
||||
print('Erreur lors de la vérification d\'authentification: $e');
|
||||
_updateStatus('Erreur de connexion');
|
||||
await Future.delayed(Duration(seconds: 2));
|
||||
|
||||
if (mounted) {
|
||||
Navigator.of(
|
||||
context,
|
||||
).pushReplacement(MaterialPageRoute(builder: (context) => LoginPage()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void _showConnectionError() {
|
||||
if (mounted) {
|
||||
showDialog(
|
||||
context: context,
|
||||
barrierDismissible: false,
|
||||
builder:
|
||||
(context) => AlertDialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(Icons.warning, color: Colors.orange),
|
||||
SizedBox(width: 8),
|
||||
Text('Connexion API'),
|
||||
],
|
||||
),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Impossible de se connecter au serveur Flask.\n',
|
||||
style: TextStyle(fontWeight: FontWeight.w500),
|
||||
),
|
||||
Text('Vérifiez que :'),
|
||||
SizedBox(height: 8),
|
||||
Text('• Le serveur Flask est démarré'),
|
||||
Text('• MongoDB fonctionne'),
|
||||
Text('• L\'URL API est correcte'),
|
||||
Text('• Votre connexion réseau'),
|
||||
SizedBox(height: 12),
|
||||
Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade100,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
'Vous pouvez continuer en mode hors ligne avec des données de démonstration.',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey.shade700,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
_checkAuthStatus(); // Réessayer
|
||||
},
|
||||
child: Text('Réessayer'),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
Navigator.of(context).pushReplacement(
|
||||
MaterialPageRoute(builder: (context) => LoginPage()),
|
||||
);
|
||||
},
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: primaryColor,
|
||||
),
|
||||
child: Text(
|
||||
'Continuer',
|
||||
style: TextStyle(color: Colors.white),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_logoController.dispose();
|
||||
_textController.dispose();
|
||||
_loadingController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
primaryColor,
|
||||
primaryColor.withOpacity(0.8),
|
||||
secondaryColor,
|
||||
],
|
||||
stops: [0.0, 0.6, 1.0],
|
||||
),
|
||||
),
|
||||
child: SafeArea(
|
||||
child: Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Spacer(flex: 2),
|
||||
|
||||
// Logo principal animé
|
||||
_buildAnimatedLogo(),
|
||||
|
||||
SizedBox(height: 40),
|
||||
|
||||
// Texte principal animé
|
||||
_buildAnimatedText(),
|
||||
|
||||
Spacer(flex: 2),
|
||||
|
||||
// Section loading avec statut API
|
||||
_buildLoadingSection(),
|
||||
|
||||
SizedBox(height: 60),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAnimatedLogo() {
|
||||
return AnimatedBuilder(
|
||||
animation: _logoController,
|
||||
builder: (context, child) {
|
||||
return SlideTransition(
|
||||
position: _logoSlideAnimation,
|
||||
child: FadeTransition(
|
||||
opacity: _logoFadeAnimation,
|
||||
child: Transform.scale(
|
||||
scale: _logoScaleAnimation.value,
|
||||
child: WortisLogoWidget(
|
||||
size: 130,
|
||||
isWhite: true, // Logo blanc pour le fond bleu
|
||||
withShadow: true,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildAnimatedText() {
|
||||
return AnimatedBuilder(
|
||||
animation: _textController,
|
||||
builder: (context, child) {
|
||||
return SlideTransition(
|
||||
position: _textSlideAnimation,
|
||||
child: FadeTransition(
|
||||
opacity: _textFadeAnimation,
|
||||
child: Column(
|
||||
children: [
|
||||
Text(
|
||||
'WORTIS',
|
||||
style: TextStyle(
|
||||
fontSize: 42,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.white,
|
||||
letterSpacing: 8,
|
||||
shadows: [
|
||||
Shadow(
|
||||
offset: Offset(0, 3),
|
||||
blurRadius: 6,
|
||||
color: Colors.black.withOpacity(0.4),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: 12),
|
||||
|
||||
Text(
|
||||
'Réseau Commercial',
|
||||
style: TextStyle(
|
||||
fontSize: 18,
|
||||
color: Colors.white.withOpacity(0.9),
|
||||
letterSpacing: 3,
|
||||
fontWeight: FontWeight.w300,
|
||||
shadows: [
|
||||
Shadow(
|
||||
offset: Offset(0, 1),
|
||||
blurRadius: 3,
|
||||
color: Colors.black.withOpacity(0.3),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: 8),
|
||||
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: Colors.white.withOpacity(0.3),
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
_hasApiConnection ? Icons.cloud_done : Icons.cloud_off,
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
size: 14,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
'Agent Mobile App v1.0',
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
letterSpacing: 1,
|
||||
fontWeight: FontWeight.w400,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildLoadingSection() {
|
||||
return AnimatedBuilder(
|
||||
animation: _loadingController,
|
||||
builder: (context, child) {
|
||||
return FadeTransition(
|
||||
opacity: _loadingFadeAnimation,
|
||||
child: Column(
|
||||
children: [
|
||||
Stack(
|
||||
alignment: Alignment.center,
|
||||
children: [
|
||||
SizedBox(
|
||||
width: 50,
|
||||
height: 50,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 3,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white.withOpacity(0.8),
|
||||
),
|
||||
backgroundColor: Colors.white.withOpacity(0.2),
|
||||
),
|
||||
),
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: _hasApiConnection ? Colors.green : Colors.orange,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
SizedBox(height: 20),
|
||||
|
||||
// Message de statut dynamique
|
||||
Text(
|
||||
_statusMessage,
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
color: Colors.white.withOpacity(0.9),
|
||||
fontWeight: FontWeight.w300,
|
||||
letterSpacing: 1,
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: 8),
|
||||
|
||||
Text(
|
||||
'Initialisation de votre espace agent',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.white.withOpacity(0.7),
|
||||
fontWeight: FontWeight.w300,
|
||||
),
|
||||
),
|
||||
|
||||
if (!_hasApiConnection &&
|
||||
_statusMessage.contains('hors ligne')) ...[
|
||||
SizedBox(height: 12),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.orange.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
border: Border.all(color: Colors.orange.withOpacity(0.3)),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.wifi_off,
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
size: 14,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
'Mode démo',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
600
lib/services/connectivity_service.dart
Normal file
600
lib/services/connectivity_service.dart
Normal file
@@ -0,0 +1,600 @@
|
||||
// lib/services/connectivity_service.dart - VERSION AVEC SUPPORT ENTREPRISE
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../main.dart'; // Pour accéder à AuthController
|
||||
|
||||
class ConnectivityService extends ChangeNotifier {
|
||||
static final ConnectivityService _instance = ConnectivityService._internal();
|
||||
factory ConnectivityService() => _instance;
|
||||
ConnectivityService._internal();
|
||||
|
||||
bool _isConnected = true;
|
||||
bool _isChecking = false;
|
||||
Timer? _periodicTimer;
|
||||
bool _hasNetworkInterface = true;
|
||||
DateTime? _lastDisconnectionTime;
|
||||
int _reconnectionAttempts = 0;
|
||||
|
||||
bool get isConnected => _isConnected;
|
||||
bool get hasNetworkInterface => _hasNetworkInterface;
|
||||
DateTime? get lastDisconnectionTime => _lastDisconnectionTime;
|
||||
int get reconnectionAttempts => _reconnectionAttempts;
|
||||
|
||||
// Clé globale pour accéder au navigator
|
||||
static GlobalKey<NavigatorState>? navigatorKey;
|
||||
|
||||
/// Initialiser le service avec la clé navigator
|
||||
static void setNavigatorKey(GlobalKey<NavigatorState> key) {
|
||||
navigatorKey = key;
|
||||
print('✅ NavigatorKey configuré pour ConnectivityService');
|
||||
}
|
||||
|
||||
/// Démarrer la surveillance
|
||||
void startMonitoring() {
|
||||
print('🌐 Démarrage de la surveillance de connectivité');
|
||||
_periodicTimer?.cancel();
|
||||
_periodicTimer = Timer.periodic(Duration(seconds: 5), (timer) {
|
||||
checkConnectivity();
|
||||
});
|
||||
|
||||
// Vérification initiale après un délai
|
||||
Future.delayed(Duration(seconds: 2), () {
|
||||
checkConnectivity();
|
||||
});
|
||||
}
|
||||
|
||||
/// Vérifier la connectivité
|
||||
Future<void> checkConnectivity() async {
|
||||
if (_isChecking) return;
|
||||
_isChecking = true;
|
||||
|
||||
try {
|
||||
print('🔍 Vérification de la connectivité...');
|
||||
|
||||
// Étape 1: Vérifier les interfaces réseau
|
||||
_hasNetworkInterface = await _checkNetworkInterfaces();
|
||||
|
||||
if (!_hasNetworkInterface) {
|
||||
print('❌ Aucune interface réseau trouvée');
|
||||
_updateConnectivityStatus(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// Étape 2: Tester la connectivité internet
|
||||
bool hasInternetAccess = await _testInternetConnectivity();
|
||||
print('🌍 Accès internet: $hasInternetAccess');
|
||||
|
||||
_updateConnectivityStatus(hasInternetAccess);
|
||||
} catch (e) {
|
||||
print('❌ Erreur lors de la vérification: $e');
|
||||
_updateConnectivityStatus(false);
|
||||
} finally {
|
||||
_isChecking = false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Vérifier les interfaces réseau
|
||||
Future<bool> _checkNetworkInterfaces() async {
|
||||
try {
|
||||
final interfaces = await NetworkInterface.list(
|
||||
includeLinkLocal: false,
|
||||
type: InternetAddressType.any,
|
||||
);
|
||||
|
||||
bool hasActiveInterface = interfaces.any(
|
||||
(interface) =>
|
||||
!interface.name.toLowerCase().contains('lo') &&
|
||||
interface.addresses.isNotEmpty,
|
||||
);
|
||||
|
||||
print('📡 Interfaces réseau actives: $hasActiveInterface');
|
||||
if (hasActiveInterface) {
|
||||
print(
|
||||
' Interfaces trouvées: ${interfaces.map((i) => i.name).join(", ")}',
|
||||
);
|
||||
}
|
||||
|
||||
return hasActiveInterface;
|
||||
} catch (e) {
|
||||
print('❌ Erreur vérification interfaces: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Tester la connectivité internet avec plusieurs cibles
|
||||
Future<bool> _testInternetConnectivity() async {
|
||||
final testTargets = [
|
||||
{'host': '1.1.1.1', 'port': 53, 'name': 'Cloudflare DNS'},
|
||||
{'host': '8.8.8.8', 'port': 53, 'name': 'Google DNS'},
|
||||
{'host': 'google.com', 'port': 80, 'name': 'Google'},
|
||||
];
|
||||
|
||||
for (var target in testTargets) {
|
||||
try {
|
||||
final socket = await Socket.connect(
|
||||
target['host'] as String,
|
||||
target['port'] as int,
|
||||
timeout: Duration(seconds: 3),
|
||||
);
|
||||
socket.destroy();
|
||||
print('✅ Connexion réussie à ${target['name']}');
|
||||
return true;
|
||||
} catch (e) {
|
||||
print('⚠️ Échec connexion à ${target['name']}: $e');
|
||||
}
|
||||
}
|
||||
|
||||
print('❌ Toutes les tentatives de connexion ont échoué');
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Mettre à jour le statut de connectivité
|
||||
void _updateConnectivityStatus(bool isConnected) {
|
||||
if (isConnected != _isConnected) {
|
||||
print('🔄 Changement connectivité: $_isConnected -> $isConnected');
|
||||
|
||||
final previousStatus = _isConnected;
|
||||
_isConnected = isConnected;
|
||||
|
||||
if (!_isConnected) {
|
||||
_lastDisconnectionTime = DateTime.now();
|
||||
_reconnectionAttempts = 0;
|
||||
_showNoConnectionDialog();
|
||||
} else if (previousStatus == false && _isConnected) {
|
||||
// Reconnexion réussie
|
||||
print('✅ Reconnexion établie');
|
||||
_reconnectionAttempts = 0;
|
||||
_showReconnectionSuccess();
|
||||
}
|
||||
|
||||
notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/// Afficher le dialog de perte de connexion
|
||||
void _showNoConnectionDialog() {
|
||||
if (navigatorKey?.currentState == null) {
|
||||
print('⚠️ NavigatorState non disponible');
|
||||
return;
|
||||
}
|
||||
|
||||
print('🚨 Affichage du popup de perte de connexion');
|
||||
|
||||
navigatorKey!.currentState!.push(
|
||||
PageRouteBuilder(
|
||||
opaque: false,
|
||||
barrierDismissible: false,
|
||||
barrierColor: Colors.black54,
|
||||
pageBuilder: (BuildContext context, _, __) {
|
||||
return WillPopScope(
|
||||
onWillPop: () async => false,
|
||||
child: Dialog(
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: _buildDialogContent(context),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Construire le contenu du dialog de déconnexion
|
||||
Widget _buildDialogContent(BuildContext context) {
|
||||
return Container(
|
||||
padding: EdgeInsets.all(24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
// Icône animée
|
||||
TweenAnimationBuilder<double>(
|
||||
duration: Duration(milliseconds: 800),
|
||||
tween: Tween(begin: 0.0, end: 1.0),
|
||||
builder: (context, value, child) {
|
||||
return Transform.scale(
|
||||
scale: value,
|
||||
child: Container(
|
||||
width: 80,
|
||||
height: 80,
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
colors: [Colors.red[400]!, Colors.red[600]!],
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
),
|
||||
shape: BoxShape.circle,
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.red.withOpacity(0.3),
|
||||
blurRadius: 20,
|
||||
offset: Offset(0, 10),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Icon(
|
||||
Icons.wifi_off_rounded,
|
||||
color: Colors.white,
|
||||
size: 40,
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
|
||||
SizedBox(height: 24),
|
||||
|
||||
// Titre
|
||||
Text(
|
||||
'Problème de connexion',
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF006699),
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
|
||||
SizedBox(height: 16),
|
||||
|
||||
// Message détaillé
|
||||
Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red[50],
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(color: Colors.red[200]!, width: 1),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
_hasNetworkInterface
|
||||
? Icons.cloud_off_rounded
|
||||
: Icons.wifi_off_rounded,
|
||||
color: Colors.red[700],
|
||||
size: 24,
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_getDetailedMessage(),
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
color: Colors.red[900],
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(height: 24),
|
||||
|
||||
// Informations utilisateur (si connecté)
|
||||
Consumer<AuthController>(
|
||||
builder: (context, authController, child) {
|
||||
if (authController.isLoggedIn) {
|
||||
final isEnterprise = authController.isEnterpriseMember;
|
||||
return Container(
|
||||
padding: EdgeInsets.all(12),
|
||||
margin: EdgeInsets.only(bottom: 16),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6).withOpacity(0.1)
|
||||
: Color(0xFF006699).withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border.all(
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6).withOpacity(0.3)
|
||||
: Color(0xFF006699).withOpacity(0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
isEnterprise ? Icons.business : Icons.person,
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6)
|
||||
: Color(0xFF006699),
|
||||
size: 20,
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
authController.agentName ?? 'Agent',
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.black87,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
if (isEnterprise &&
|
||||
authController.enterprise?.nomEntreprise !=
|
||||
null) ...[
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
authController.enterprise!.nomEntreprise,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(
|
||||
horizontal: 8,
|
||||
vertical: 4,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
isEnterprise
|
||||
? Color(0xFF8B5CF6)
|
||||
: Color(0xFF006699),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
isEnterprise ? 'Entreprise' : 'Agent',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 10,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
return SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
|
||||
// Boutons d'action
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
_reconnectionAttempts++;
|
||||
checkConnectivity();
|
||||
},
|
||||
icon: Icon(Icons.refresh_rounded, size: 20),
|
||||
label: Text('Réessayer'),
|
||||
style: OutlinedButton.styleFrom(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
side: BorderSide(color: Color(0xFF006699), width: 2),
|
||||
foregroundColor: Color(0xFF006699),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: () {
|
||||
Navigator.of(context).pop();
|
||||
_openWifiSettings();
|
||||
},
|
||||
icon: Icon(Icons.wifi_find_rounded, size: 20),
|
||||
label: Text('WiFi'),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: Color(0xFF006699),
|
||||
foregroundColor: Colors.white,
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
elevation: 2,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
|
||||
// Compteur de tentatives
|
||||
if (_reconnectionAttempts > 0) ...[
|
||||
SizedBox(height: 12),
|
||||
Text(
|
||||
'Tentative ${_reconnectionAttempts + 1}',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Message détaillé selon le type de problème
|
||||
String _getDetailedMessage() {
|
||||
if (!_hasNetworkInterface) {
|
||||
return 'Aucun réseau WiFi détecté. Veuillez vous connecter à un réseau WiFi pour utiliser WORTIS Agent.';
|
||||
} else {
|
||||
return 'Connexion internet indisponible. Vérifiez que votre réseau WiFi a accès à internet.';
|
||||
}
|
||||
}
|
||||
|
||||
/// Afficher un message de reconnexion réussie
|
||||
void _showReconnectionSuccess() {
|
||||
if (navigatorKey?.currentContext == null) return;
|
||||
|
||||
final context = navigatorKey!.currentContext!;
|
||||
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white.withOpacity(0.2),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(Icons.wifi_rounded, color: Colors.white, size: 20),
|
||||
),
|
||||
SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'Connexion rétablie',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
SizedBox(height: 2),
|
||||
Text(
|
||||
'Vous pouvez continuer à utiliser l\'application',
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.9),
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green[600],
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
duration: Duration(seconds: 3),
|
||||
margin: EdgeInsets.all(16),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Ouvrir les paramètres WiFi
|
||||
void _openWifiSettings() async {
|
||||
try {
|
||||
print('📱 Ouverture des paramètres WiFi');
|
||||
const platform = MethodChannel('com.wortis.agent/settings');
|
||||
|
||||
// Sortir du mode kiosque si activé
|
||||
try {
|
||||
await platform.invokeMethod('exitKioskMode');
|
||||
} catch (e) {
|
||||
print('⚠️ Mode kiosque non actif ou erreur: $e');
|
||||
}
|
||||
|
||||
// Ouvrir les paramètres WiFi
|
||||
await platform.invokeMethod('openWifiSettings');
|
||||
|
||||
// Fermer le dialog
|
||||
if (navigatorKey?.currentContext != null) {
|
||||
Navigator.of(navigatorKey!.currentContext!).pop();
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ Erreur ouverture paramètres WiFi: $e');
|
||||
|
||||
if (navigatorKey?.currentContext != null) {
|
||||
ScaffoldMessenger.of(navigatorKey!.currentContext!).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text('Impossible d\'ouvrir les paramètres WiFi'),
|
||||
backgroundColor: Colors.red,
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Forcer un test manuel (pour debug)
|
||||
void forceCheck() {
|
||||
print('🔧 Test forcé de connectivité');
|
||||
checkConnectivity();
|
||||
}
|
||||
|
||||
/// Méthode de test pour forcer l'affichage du popup
|
||||
void showTestPopup() {
|
||||
print('🧪 Test d\'affichage du popup de déconnexion');
|
||||
_isConnected = false;
|
||||
_lastDisconnectionTime = DateTime.now();
|
||||
_reconnectionAttempts = 0;
|
||||
_showNoConnectionDialog();
|
||||
}
|
||||
|
||||
/// Simuler une reconnexion (pour test)
|
||||
void simulateReconnection() {
|
||||
print('🧪 Simulation de reconnexion');
|
||||
_updateConnectivityStatus(true);
|
||||
}
|
||||
|
||||
/// Obtenir les statistiques de connectivité
|
||||
Map<String, dynamic> getConnectivityStats() {
|
||||
return {
|
||||
'is_connected': _isConnected,
|
||||
'has_network_interface': _hasNetworkInterface,
|
||||
'last_disconnection': _lastDisconnectionTime?.toIso8601String(),
|
||||
'reconnection_attempts': _reconnectionAttempts,
|
||||
'is_checking': _isChecking,
|
||||
};
|
||||
}
|
||||
|
||||
/// Réinitialiser les statistiques
|
||||
void resetStats() {
|
||||
_reconnectionAttempts = 0;
|
||||
_lastDisconnectionTime = null;
|
||||
print('📊 Statistiques de connectivité réinitialisées');
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
print('🛑 Arrêt du service de connectivité');
|
||||
_periodicTimer?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/// Extension pour des méthodes utilitaires
|
||||
extension ConnectivityServiceExtension on ConnectivityService {
|
||||
/// Vérifier si la connexion est stable
|
||||
bool get isStable {
|
||||
return _isConnected && _reconnectionAttempts == 0;
|
||||
}
|
||||
|
||||
/// Obtenir le temps depuis la dernière déconnexion
|
||||
Duration? get timeSinceLastDisconnection {
|
||||
if (_lastDisconnectionTime == null) return null;
|
||||
return DateTime.now().difference(_lastDisconnectionTime!);
|
||||
}
|
||||
|
||||
/// Obtenir un message de statut lisible
|
||||
String get statusMessage {
|
||||
if (_isConnected) {
|
||||
if (_reconnectionAttempts > 0) {
|
||||
return 'Connexion rétablie après $_reconnectionAttempts tentatives';
|
||||
}
|
||||
return 'Connecté';
|
||||
} else {
|
||||
if (!_hasNetworkInterface) {
|
||||
return 'Aucun réseau WiFi';
|
||||
}
|
||||
return 'Pas de connexion internet';
|
||||
}
|
||||
}
|
||||
}
|
||||
561
lib/services/wortis_api_service.dart
Normal file
561
lib/services/wortis_api_service.dart
Normal file
@@ -0,0 +1,561 @@
|
||||
// Enhanced lib/services/wortis_api_service.dart
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../models/service_model.dart';
|
||||
|
||||
class WortisApiService {
|
||||
static const String baseUrl = 'https://api.live.wortis.cg/tpe';
|
||||
|
||||
// Singleton pattern
|
||||
static final WortisApiService _instance = WortisApiService._internal();
|
||||
factory WortisApiService() => _instance;
|
||||
WortisApiService._internal();
|
||||
|
||||
// Retry configuration
|
||||
static const int maxRetries = 3;
|
||||
static const Duration retryDelay = Duration(seconds: 2);
|
||||
|
||||
Future<List<WortisService>> getServices() async {
|
||||
return _retryRequest<List<WortisService>>(() async {
|
||||
final response = await http
|
||||
.get(
|
||||
Uri.parse('$baseUrl/get_services_back'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
)
|
||||
.timeout(Duration(seconds: 30));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
final List<dynamic> servicesJson = jsonData['all_services'] ?? [];
|
||||
|
||||
return servicesJson
|
||||
.map((serviceJson) => WortisService.fromJson(serviceJson))
|
||||
.toList();
|
||||
} else {
|
||||
throw Exception('Erreur API: ${response.statusCode}');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Méthode pour grouper les services par secteur
|
||||
Map<String, List<WortisService>> groupServicesBySector(
|
||||
List<WortisService> services,
|
||||
) {
|
||||
Map<String, List<WortisService>> grouped = {};
|
||||
|
||||
for (var service in services) {
|
||||
String sector = service.secteurActivite;
|
||||
if (grouped[sector] == null) {
|
||||
grouped[sector] = [];
|
||||
}
|
||||
grouped[sector]!.add(service);
|
||||
}
|
||||
|
||||
return grouped;
|
||||
}
|
||||
|
||||
// Generic retry logic
|
||||
Future<T> _retryRequest<T>(Future<T> Function() request) async {
|
||||
Exception? lastException;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await request();
|
||||
} on SocketException catch (e) {
|
||||
lastException = e;
|
||||
print('Tentative $attempt échouée (SocketException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on HttpException catch (e) {
|
||||
lastException = e;
|
||||
print('Tentative $attempt échouée (HttpException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on http.ClientException catch (e) {
|
||||
lastException = e;
|
||||
print('Tentative $attempt échouée (ClientException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} catch (e) {
|
||||
// For other exceptions, don't retry
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception(
|
||||
'Impossible de se connecter après $maxRetries tentatives: $lastException',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class AuthApiService {
|
||||
static const String baseUrl = 'https://api.live.wortis.cg/tpe';
|
||||
static const int maxRetries = 3;
|
||||
static const Duration retryDelay = Duration(seconds: 2);
|
||||
|
||||
/// Test de connexion à l'API avec retry
|
||||
static Future<bool> testConnection() async {
|
||||
try {
|
||||
return await _retryRequest<bool>(() async {
|
||||
final response = await http
|
||||
.get(
|
||||
Uri.parse('http://google.com/'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
)
|
||||
.timeout(Duration(seconds: 10));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = jsonDecode(response.body);
|
||||
return data['success'] == true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur test connexion après plusieurs tentatives: $e');
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Connexion utilisateur avec retry
|
||||
static Future<Map<String, dynamic>> login(String agentId, String pin) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse('$baseUrl/auth/login'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode({'agent_id': agentId, 'pin': pin}),
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur login API après retry: $e');
|
||||
return {'success': false, 'message': 'Erreur de connexion au serveur'};
|
||||
}
|
||||
}
|
||||
|
||||
/// Créer un utilisateur avec retry
|
||||
static Future<Map<String, dynamic>> createUser(
|
||||
String nom,
|
||||
String pin, {
|
||||
String role = 'agent',
|
||||
}) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse('$baseUrl/users/register'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode({'nom': nom, 'pin': pin, 'role': role}),
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur création utilisateur après retry: $e');
|
||||
return {'success': false, 'message': 'Erreur de création'};
|
||||
}
|
||||
}
|
||||
|
||||
/// Récupérer le solde d'un agent avec retry
|
||||
static Future<Map<String, dynamic>> getAgentBalance(String agentId) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.get(
|
||||
Uri.parse('$baseUrl/agent/$agentId/balance'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur récupération solde après retry: $e');
|
||||
return {
|
||||
'success': false,
|
||||
'message': 'Erreur lors de la récupération du solde',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Recharger le solde d'un agent avec retry
|
||||
static Future<Map<String, dynamic>> rechargeAgent(
|
||||
String agentId,
|
||||
double montant,
|
||||
) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse('$baseUrl/agent/$agentId/recharge'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode({'montant': montant}),
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur recharge après retry: $e');
|
||||
return {'success': false, 'message': 'Erreur lors de la recharge'};
|
||||
}
|
||||
}
|
||||
|
||||
/// Mettre à jour le solde d'un agent avec retry
|
||||
static Future<Map<String, dynamic>> updateAgentBalance(
|
||||
String agentId,
|
||||
double nouveauSolde,
|
||||
) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.put(
|
||||
Uri.parse('$baseUrl/agent/$agentId/balance'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode({'solde': nouveauSolde}),
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur mise à jour solde après retry: $e');
|
||||
return {
|
||||
'success': false,
|
||||
'message': 'Erreur lors de la mise à jour du solde',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Enregistrer une transaction avec retry
|
||||
static Future<Map<String, dynamic>> recordTransaction({
|
||||
required String agentId,
|
||||
required String serviceId,
|
||||
required String serviceName,
|
||||
required double montant,
|
||||
required double commission,
|
||||
required String typeTransaction,
|
||||
required Map<String, dynamic> detailsTransaction,
|
||||
}) async {
|
||||
try {
|
||||
return await _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse('$baseUrl/transactions'),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode({
|
||||
'agent_id': agentId,
|
||||
'service_id': serviceId,
|
||||
'service_name': serviceName,
|
||||
'montant': montant,
|
||||
'commission': commission,
|
||||
'type_transaction': typeTransaction,
|
||||
'details': detailsTransaction,
|
||||
'date_transaction': DateTime.now().toIso8601String(),
|
||||
}),
|
||||
)
|
||||
.timeout(Duration(seconds: 15));
|
||||
|
||||
return jsonDecode(response.body);
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur enregistrement transaction après retry: $e');
|
||||
return {
|
||||
'success': false,
|
||||
'message': 'Erreur lors de l\'enregistrement de la transaction',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Generic retry logic for AuthApiService
|
||||
static Future<T> _retryRequest<T>(Future<T> Function() request) async {
|
||||
Exception? lastException;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await request();
|
||||
} on SocketException catch (e) {
|
||||
lastException = e;
|
||||
print('AuthAPI - Tentative $attempt échouée (SocketException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on HttpException catch (e) {
|
||||
lastException = e;
|
||||
print('AuthAPI - Tentative $attempt échouée (HttpException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on http.ClientException catch (e) {
|
||||
lastException = e;
|
||||
print('AuthAPI - Tentative $attempt échouée (ClientException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} catch (e) {
|
||||
// For other exceptions, don't retry
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception(
|
||||
'Impossible de se connecter après $maxRetries tentatives: $lastException',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class ApiService {
|
||||
static const String baseUrl = 'https://api.live.wortis.cg/tpe';
|
||||
static const int maxRetries = 3;
|
||||
static const Duration retryDelay = Duration(seconds: 2);
|
||||
|
||||
/// Récupérer les champs d'un service avec retry amélioré
|
||||
Future<Map<String, dynamic>> fetchServiceFields(String serviceName) async {
|
||||
return _retryRequest<Map<String, dynamic>>(() async {
|
||||
// Fix: Remove double slash in URL
|
||||
final url = '$baseUrl/service/${Uri.encodeComponent(serviceName)}';
|
||||
print('Fetching service fields from: $url');
|
||||
|
||||
final response = await http
|
||||
.get(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Accept': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
'User-Agent': 'WortisApp/1.0',
|
||||
},
|
||||
)
|
||||
.timeout(Duration(seconds: 30));
|
||||
|
||||
print('Response status: ${response.statusCode}');
|
||||
print('Response headers: ${response.headers}');
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return jsonDecode(response.body);
|
||||
} else {
|
||||
throw Exception(
|
||||
'Erreur API: ${response.statusCode} - ${response.body}',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Vérifier les données avec GET et retry
|
||||
Future<Map<String, dynamic>> verifyDataGet(
|
||||
String url,
|
||||
Map<String, dynamic> params,
|
||||
) async {
|
||||
return _retryRequest<Map<String, dynamic>>(() async {
|
||||
final uri = Uri.parse(url).replace(
|
||||
queryParameters: params.map(
|
||||
(key, value) => MapEntry(key, value.toString()),
|
||||
),
|
||||
);
|
||||
|
||||
final response = await http
|
||||
.get(
|
||||
uri,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
)
|
||||
.timeout(Duration(seconds: 30));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return jsonDecode(response.body);
|
||||
} else {
|
||||
throw Exception(
|
||||
'Données non trouvées - Status: ${response.statusCode}',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Vérifier les données avec POST et retry
|
||||
Future<Map<String, dynamic>> verifyDataPost(
|
||||
String url,
|
||||
Map<String, dynamic> data,
|
||||
String operationId,
|
||||
) async {
|
||||
return _retryRequest<Map<String, dynamic>>(() async {
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode(data),
|
||||
)
|
||||
.timeout(Duration(seconds: 30));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return jsonDecode(response.body);
|
||||
} else {
|
||||
throw Exception(
|
||||
'Données non trouvées - Status: ${response.statusCode}',
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// Soumettre les données du formulaire avec retry
|
||||
Future<void> submitFormData(
|
||||
BuildContext context,
|
||||
String url,
|
||||
Map<String, dynamic> data,
|
||||
Map<String, dynamic>? serviceData,
|
||||
dynamic additionalData,
|
||||
bool isCardPayment,
|
||||
) async {
|
||||
try {
|
||||
await _retryRequest<void>(() async {
|
||||
print(url);
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse(url),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
body: jsonEncode(data),
|
||||
)
|
||||
.timeout(Duration(seconds: 30));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final responseData = jsonDecode(response.body);
|
||||
|
||||
// Afficher un message de succès
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.check_circle, color: Colors.white),
|
||||
SizedBox(width: 8),
|
||||
Text('Transaction effectuée avec succès'),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// Retourner à la page précédente
|
||||
Navigator.of(context).pop();
|
||||
}
|
||||
} else {
|
||||
throw Exception(
|
||||
'Erreur lors de la soumission - Status: ${response.statusCode}',
|
||||
);
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
print('Erreur submitFormData après retry: $e');
|
||||
if (context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.error, color: Colors.white),
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Erreur lors de la transaction: ${e.toString()}',
|
||||
maxLines: 2,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.red,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
duration: Duration(seconds: 5),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Annuler l'opération en cours
|
||||
void cancelOperation() {
|
||||
print('Opération annulée');
|
||||
}
|
||||
|
||||
// Generic retry logic for ApiService
|
||||
Future<T> _retryRequest<T>(Future<T> Function() request) async {
|
||||
Exception? lastException;
|
||||
|
||||
for (int attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
return await request();
|
||||
} on SocketException catch (e) {
|
||||
lastException = e;
|
||||
print('API - Tentative $attempt échouée (SocketException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on HttpException catch (e) {
|
||||
lastException = e;
|
||||
print('API - Tentative $attempt échouée (HttpException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} on http.ClientException catch (e) {
|
||||
lastException = e;
|
||||
print('API - Tentative $attempt échouée (ClientException): $e');
|
||||
if (attempt < maxRetries) {
|
||||
await Future.delayed(retryDelay * attempt);
|
||||
}
|
||||
} catch (e) {
|
||||
// For other exceptions, don't retry
|
||||
rethrow;
|
||||
}
|
||||
}
|
||||
|
||||
throw Exception(
|
||||
'Impossible de se connecter après $maxRetries tentatives: $lastException',
|
||||
);
|
||||
}
|
||||
}
|
||||
2651
lib/tpe.py
Normal file
2651
lib/tpe.py
Normal file
File diff suppressed because it is too large
Load Diff
328
lib/widgets/balance_widget.dart
Normal file
328
lib/widgets/balance_widget.dart
Normal file
@@ -0,0 +1,328 @@
|
||||
// lib/widgets/balance_widget.dart
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../main.dart';
|
||||
import '../services/wortis_api_service.dart';
|
||||
|
||||
class BalanceWidget extends StatefulWidget {
|
||||
final bool showIcon;
|
||||
final bool compact;
|
||||
final Color? textColor;
|
||||
final Color? backgroundColor;
|
||||
|
||||
const BalanceWidget({
|
||||
super.key,
|
||||
this.showIcon = true,
|
||||
this.compact = false,
|
||||
this.textColor,
|
||||
this.backgroundColor,
|
||||
});
|
||||
|
||||
@override
|
||||
_BalanceWidgetState createState() => _BalanceWidgetState();
|
||||
}
|
||||
|
||||
class _BalanceWidgetState extends State<BalanceWidget> {
|
||||
bool _isRefreshing = false;
|
||||
DateTime _lastRefresh = DateTime.now();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Rafraîchir le solde au démarrage
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
_refreshBalance();
|
||||
});
|
||||
}
|
||||
|
||||
Future<void> _refreshBalance() async {
|
||||
final authController = Provider.of<AuthController>(context, listen: false);
|
||||
final agentId = authController.agentId;
|
||||
|
||||
if (agentId == null || _isRefreshing) return;
|
||||
|
||||
setState(() {
|
||||
_isRefreshing = true;
|
||||
});
|
||||
|
||||
try {
|
||||
// Test de connexion API d'abord
|
||||
final isConnected = await AuthApiService.testConnection();
|
||||
|
||||
if (isConnected) {
|
||||
final response = await AuthApiService.getAgentBalance(agentId);
|
||||
|
||||
if (response['success'] == true && mounted) {
|
||||
final nouveauSolde = (response['solde'] ?? 0.0).toDouble();
|
||||
authController.updateBalance(nouveauSolde);
|
||||
|
||||
setState(() {
|
||||
_lastRefresh = DateTime.now();
|
||||
});
|
||||
|
||||
// Afficher un message si le solde a changé significativement
|
||||
final ancienSolde = authController.balance;
|
||||
if ((nouveauSolde - ancienSolde).abs() > 100) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
Icon(Icons.refresh, color: Colors.white, size: 16),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Solde mis à jour: ${nouveauSolde.toStringAsFixed(0)} XAF',
|
||||
),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
duration: Duration(seconds: 2),
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
print('Erreur rafraîchissement solde: $e');
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_isRefreshing = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
String _getTimeAgo() {
|
||||
final now = DateTime.now();
|
||||
final difference = now.difference(_lastRefresh);
|
||||
|
||||
if (difference.inMinutes < 1) {
|
||||
return 'À l\'instant';
|
||||
} else if (difference.inMinutes < 60) {
|
||||
return 'Il y a ${difference.inMinutes}min';
|
||||
} else {
|
||||
return 'Il y a ${difference.inHours}h';
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Consumer<AuthController>(
|
||||
builder: (context, authController, child) {
|
||||
// Utiliser le solde actif (entreprise ou personnel selon le type de compte)
|
||||
final solde = authController.activeBalance;
|
||||
final isEnterprise = authController.isEnterpriseMember;
|
||||
final textColor = widget.textColor ?? Colors.white;
|
||||
|
||||
if (widget.compact) {
|
||||
return GestureDetector(
|
||||
onTap: _refreshBalance,
|
||||
child: Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: widget.backgroundColor ?? Colors.white.withOpacity(0.2),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: (widget.backgroundColor ?? Colors.white).withOpacity(
|
||||
0.3,
|
||||
),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
if (widget.showIcon) ...[
|
||||
Icon(
|
||||
isEnterprise ? Icons.business_center : Icons.account_balance_wallet,
|
||||
color: textColor,
|
||||
size: 14,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
],
|
||||
if (_isRefreshing)
|
||||
SizedBox(
|
||||
width: 12,
|
||||
height: 12,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 1.5,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(textColor),
|
||||
),
|
||||
)
|
||||
else
|
||||
Text(
|
||||
'${solde.toStringAsFixed(0)} XAF',
|
||||
style: TextStyle(
|
||||
color: textColor,
|
||||
fontSize: 12,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// Version étendue
|
||||
final enterpriseColor = Color(0xFF8B5CF6);
|
||||
final displayColor = isEnterprise ? enterpriseColor : Color(0xFF006699);
|
||||
|
||||
return Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: widget.backgroundColor ?? Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
blurRadius: 10,
|
||||
offset: Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: [
|
||||
Icon(
|
||||
isEnterprise ? Icons.business_center : Icons.account_balance_wallet,
|
||||
color: displayColor,
|
||||
size: 24,
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Flexible(
|
||||
child: Text(
|
||||
isEnterprise ? 'Solde entreprise' : 'Solde disponible',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.black87,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
if (isEnterprise && authController.enterprise?.nomEntreprise != null) ...[
|
||||
SizedBox(height: 4),
|
||||
Text(
|
||||
authController.enterprise!.nomEntreprise,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
GestureDetector(
|
||||
onTap: _isRefreshing ? null : _refreshBalance,
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: displayColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child:
|
||||
_isRefreshing
|
||||
? SizedBox(
|
||||
width: 16,
|
||||
height: 16,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(displayColor),
|
||||
),
|
||||
)
|
||||
: Icon(
|
||||
Icons.refresh,
|
||||
color: displayColor,
|
||||
size: 16,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 12),
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Flexible(
|
||||
child: Text(
|
||||
solde.toStringAsFixed(0),
|
||||
style: TextStyle(
|
||||
fontSize: 32,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: displayColor,
|
||||
),
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
Padding(
|
||||
padding: EdgeInsets.only(bottom: 4),
|
||||
child: Text(
|
||||
'XAF',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: Text(
|
||||
'Dernière mise à jour: ${_getTimeAgo()}',
|
||||
style: TextStyle(fontSize: 12, color: Colors.grey[500]),
|
||||
),
|
||||
),
|
||||
if (isEnterprise)
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: enterpriseColor.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.business, size: 10, color: enterpriseColor),
|
||||
SizedBox(width: 4),
|
||||
Text(
|
||||
'PRO',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
color: enterpriseColor,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
0
lib/widgets/connectivity_wrapper.dart
Normal file
0
lib/widgets/connectivity_wrapper.dart
Normal file
484
lib/widgets/pin_verification_dialog.dart
Normal file
484
lib/widgets/pin_verification_dialog.dart
Normal file
@@ -0,0 +1,484 @@
|
||||
// widgets/pin_verification_dialog.dart - Version mise à jour
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
|
||||
class PinVerificationDialog extends StatefulWidget {
|
||||
final String agentName;
|
||||
final String serviceName;
|
||||
final double baseAmount;
|
||||
final double fees;
|
||||
final double totalAmount;
|
||||
final double agentBalance; // Nouveau paramètre
|
||||
final Function(String) onPinConfirmed;
|
||||
final VoidCallback onCancel;
|
||||
|
||||
const PinVerificationDialog({
|
||||
super.key,
|
||||
required this.agentName,
|
||||
required this.serviceName,
|
||||
required this.baseAmount,
|
||||
required this.fees,
|
||||
required this.totalAmount,
|
||||
required this.agentBalance, // Nouveau paramètre requis
|
||||
required this.onPinConfirmed,
|
||||
required this.onCancel,
|
||||
});
|
||||
|
||||
@override
|
||||
_PinVerificationDialogState createState() => _PinVerificationDialogState();
|
||||
}
|
||||
|
||||
class _PinVerificationDialogState extends State<PinVerificationDialog> {
|
||||
final TextEditingController _pinController = TextEditingController();
|
||||
bool _isObscured = true;
|
||||
bool _isLoading = false;
|
||||
String? _errorMessage;
|
||||
|
||||
// Formatter pour les montants
|
||||
String _formatAmount(double amount) {
|
||||
final formatter = NumberFormat('#,###', 'fr_FR');
|
||||
return formatter.format(amount);
|
||||
}
|
||||
|
||||
// Vérifier si l'agent a suffisamment de solde
|
||||
bool get _hasSufficientBalance {
|
||||
return widget.agentBalance >= widget.totalAmount;
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_pinController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _handlePinConfirmation() async {
|
||||
if (_pinController.text.length < 4) {
|
||||
setState(() {
|
||||
_errorMessage = 'Le PIN doit contenir au moins 4 chiffres';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (!_hasSufficientBalance) {
|
||||
setState(() {
|
||||
_errorMessage = 'Solde insuffisant pour effectuer cette transaction';
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setState(() {
|
||||
_isLoading = true;
|
||||
_errorMessage = null;
|
||||
});
|
||||
|
||||
try {
|
||||
// Simuler une vérification (remplacez par votre logique de vérification)
|
||||
await Future.delayed(const Duration(seconds: 1));
|
||||
|
||||
widget.onPinConfirmed(_pinController.text);
|
||||
} catch (e) {
|
||||
setState(() {
|
||||
_errorMessage = 'Erreur lors de la vérification du PIN';
|
||||
_isLoading = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final size = MediaQuery.of(context).size;
|
||||
final isSmallScreen = size.width < 360;
|
||||
|
||||
return Dialog(
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
elevation: 0,
|
||||
backgroundColor: Colors.transparent,
|
||||
child: Container(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: size.width * 0.9,
|
||||
maxHeight: size.height * 0.8,
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.1),
|
||||
spreadRadius: 0,
|
||||
blurRadius: 10,
|
||||
offset: const Offset(0, 4),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: SingleChildScrollView(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(isSmallScreen ? 16 : 24),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.center,
|
||||
children: [
|
||||
// En-tête avec icône de sécurité
|
||||
Container(
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: const Color(0xFF006699).withOpacity(0.1),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: const Icon(
|
||||
Icons.security,
|
||||
size: 32,
|
||||
color: Color(0xFF006699),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Titre
|
||||
Text(
|
||||
'Confirmation sécurisée',
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 20 : 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Colors.black87,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
Text(
|
||||
'Vérifiez les détails et confirmez avec votre PIN',
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 14 : 16,
|
||||
color: Colors.black54,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Informations de la transaction
|
||||
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: [
|
||||
// Service
|
||||
_buildDetailRow(
|
||||
icon: Icons.business_center,
|
||||
label: 'Service',
|
||||
value: widget.serviceName,
|
||||
isSmallScreen: isSmallScreen,
|
||||
),
|
||||
|
||||
if (widget.baseAmount > 0) ...[
|
||||
const SizedBox(height: 12),
|
||||
_buildDetailRow(
|
||||
icon: Icons.account_balance_wallet,
|
||||
label: 'Montant à payer',
|
||||
value: '${_formatAmount(widget.baseAmount)} FCFA',
|
||||
isSmallScreen: isSmallScreen,
|
||||
),
|
||||
],
|
||||
|
||||
if (widget.fees > 0) ...[
|
||||
const SizedBox(height: 12),
|
||||
_buildDetailRow(
|
||||
icon: Icons.receipt_long,
|
||||
label: 'Frais',
|
||||
value: '${_formatAmount(widget.fees)} FCFA',
|
||||
isSmallScreen: isSmallScreen,
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 12),
|
||||
Divider(color: Colors.grey[300]),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Total
|
||||
_buildDetailRow(
|
||||
icon: Icons.payments,
|
||||
label: 'Total',
|
||||
value: '${_formatAmount(widget.totalAmount)} FCFA',
|
||||
isTotal: true,
|
||||
isSmallScreen: isSmallScreen,
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Solde agent avec indicateur de suffisance
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color:
|
||||
_hasSufficientBalance
|
||||
? Colors.green[50]
|
||||
: Colors.red[50],
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color:
|
||||
_hasSufficientBalance
|
||||
? Colors.green[200]!
|
||||
: Colors.red[200]!,
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
_hasSufficientBalance
|
||||
? Icons.check_circle
|
||||
: Icons.warning,
|
||||
color:
|
||||
_hasSufficientBalance
|
||||
? Colors.green[600]
|
||||
: Colors.red[600],
|
||||
size: 20,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'Votre solde',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.grey[600],
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
Text(
|
||||
'${_formatAmount(widget.agentBalance)} FCFA',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.bold,
|
||||
color:
|
||||
_hasSufficientBalance
|
||||
? Colors.green[700]
|
||||
: Colors.red[700],
|
||||
),
|
||||
),
|
||||
if (!_hasSufficientBalance)
|
||||
Text(
|
||||
'Solde insuffisant',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.red[600],
|
||||
fontStyle: FontStyle.italic,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Champ PIN
|
||||
Text(
|
||||
'PIN de sécurité',
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 14 : 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.black87,
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
TextField(
|
||||
controller: _pinController,
|
||||
keyboardType: TextInputType.number,
|
||||
obscureText: _isObscured,
|
||||
maxLength: 6,
|
||||
enabled: !_isLoading && _hasSufficientBalance,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Saisissez votre PIN',
|
||||
prefixIcon: const Icon(
|
||||
Icons.lock,
|
||||
color: Color(0xFF006699),
|
||||
),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(
|
||||
_isObscured ? Icons.visibility : Icons.visibility_off,
|
||||
color: Colors.grey,
|
||||
),
|
||||
onPressed: () {
|
||||
setState(() {
|
||||
_isObscured = !_isObscured;
|
||||
});
|
||||
},
|
||||
),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Color(0xFFE0E7FF)),
|
||||
),
|
||||
enabledBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(color: Color(0xFFE0E7FF)),
|
||||
),
|
||||
focusedBorder: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
borderSide: const BorderSide(
|
||||
color: Color(0xFF006699),
|
||||
width: 2,
|
||||
),
|
||||
),
|
||||
counterText: '',
|
||||
),
|
||||
onSubmitted:
|
||||
_hasSufficientBalance
|
||||
? (_) => _handlePinConfirmation()
|
||||
: null,
|
||||
),
|
||||
|
||||
if (_errorMessage != null) ...[
|
||||
const SizedBox(height: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red[50],
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: Colors.red[200]!),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
color: Colors.red[600],
|
||||
size: 16,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_errorMessage!,
|
||||
style: TextStyle(
|
||||
color: Colors.red[600],
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// Boutons
|
||||
Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextButton(
|
||||
onPressed: _isLoading ? null : widget.onCancel,
|
||||
style: TextButton.styleFrom(
|
||||
padding: EdgeInsets.symmetric(
|
||||
vertical: isSmallScreen ? 12 : 16,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
'Annuler',
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 14 : 16,
|
||||
color: Colors.grey[600],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: ElevatedButton(
|
||||
onPressed:
|
||||
(_isLoading || !_hasSufficientBalance)
|
||||
? null
|
||||
: _handlePinConfirmation,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: const Color(0xFF006699),
|
||||
foregroundColor: Colors.white,
|
||||
padding: EdgeInsets.symmetric(
|
||||
vertical: isSmallScreen ? 12 : 16,
|
||||
),
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
elevation: 0,
|
||||
),
|
||||
child:
|
||||
_isLoading
|
||||
? SizedBox(
|
||||
height: isSmallScreen ? 16 : 20,
|
||||
width: isSmallScreen ? 16 : 20,
|
||||
child: const CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
valueColor: AlwaysStoppedAnimation<Color>(
|
||||
Colors.white,
|
||||
),
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
'CONFIRMER',
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 14 : 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildDetailRow({
|
||||
required IconData icon,
|
||||
required String label,
|
||||
required String value,
|
||||
bool isTotal = false,
|
||||
required bool isSmallScreen,
|
||||
}) {
|
||||
return Row(
|
||||
children: [
|
||||
Icon(
|
||||
icon,
|
||||
size: isSmallScreen ? 16 : 18,
|
||||
color: isTotal ? const Color(0xFF006699) : Colors.grey[600],
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 13 : 14,
|
||||
fontWeight: isTotal ? FontWeight.w600 : FontWeight.w500,
|
||||
color: isTotal ? const Color(0xFF006699) : Colors.grey[700],
|
||||
),
|
||||
),
|
||||
),
|
||||
Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
fontSize: isSmallScreen ? 13 : 14,
|
||||
fontWeight: isTotal ? FontWeight.bold : FontWeight.w600,
|
||||
color: isTotal ? const Color(0xFF006699) : Colors.black87,
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
377
lib/widgets/responsive_helper.dart
Normal file
377
lib/widgets/responsive_helper.dart
Normal file
@@ -0,0 +1,377 @@
|
||||
// ===== lib/utils/responsive_helper.dart =====
|
||||
// Système de responsivité centralisé pour tablettes et rotation
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'dart:math' as math;
|
||||
|
||||
/// Gestionnaire principal de la responsivité et rotation
|
||||
class ResponsiveHelper {
|
||||
|
||||
// =================== CONSTANTES DE BREAKPOINTS ===================
|
||||
|
||||
/// Breakpoints pour différentes tailles d'écran
|
||||
static const double phoneMaxWidth = 400;
|
||||
static const double tabletMinWidth = 600;
|
||||
static const double desktopMinWidth = 1024;
|
||||
|
||||
/// Hauteurs critiques pour détection d'orientation
|
||||
static const double portraitMinHeight = 600;
|
||||
static const double landscapeMaxHeight = 500;
|
||||
|
||||
// =================== DÉTECTION DE TYPE D'APPAREIL ===================
|
||||
|
||||
/// Détermine si c'est un petit téléphone
|
||||
static bool isSmallPhone(BuildContext context) {
|
||||
return MediaQuery.of(context).size.width < phoneMaxWidth;
|
||||
}
|
||||
|
||||
/// Détermine si c'est un téléphone standard
|
||||
static bool isPhone(BuildContext context) {
|
||||
return MediaQuery.of(context).size.width < tabletMinWidth;
|
||||
}
|
||||
|
||||
/// Détermine si c'est une tablette
|
||||
static bool isTablet(BuildContext context) {
|
||||
final width = MediaQuery.of(context).size.width;
|
||||
return width >= tabletMinWidth && width < desktopMinWidth;
|
||||
}
|
||||
|
||||
/// Détermine si c'est un grand écran/desktop
|
||||
static bool isDesktop(BuildContext context) {
|
||||
return MediaQuery.of(context).size.width >= desktopMinWidth;
|
||||
}
|
||||
|
||||
// =================== DÉTECTION D'ORIENTATION ===================
|
||||
|
||||
/// Détection précise de l'orientation
|
||||
static bool isPortrait(BuildContext context) {
|
||||
final size = MediaQuery.of(context).size;
|
||||
return size.height > size.width;
|
||||
}
|
||||
|
||||
/// Détection du mode paysage
|
||||
static bool isLandscape(BuildContext context) {
|
||||
final size = MediaQuery.of(context).size;
|
||||
return size.width > size.height;
|
||||
}
|
||||
|
||||
/// Détection spéciale pour tablette en mode paysage
|
||||
static bool isTabletLandscape(BuildContext context) {
|
||||
return isTablet(context) && isLandscape(context);
|
||||
}
|
||||
|
||||
/// Détection spéciale pour téléphone en mode paysage
|
||||
static bool isPhoneLandscape(BuildContext context) {
|
||||
return isPhone(context) && isLandscape(context);
|
||||
}
|
||||
|
||||
// =================== CONFIGURATION D'ORIENTATION ===================
|
||||
|
||||
/// Force l'orientation portrait et paysage pour tablettes
|
||||
static void enableAllOrientations() {
|
||||
SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
DeviceOrientation.landscapeLeft,
|
||||
DeviceOrientation.landscapeRight,
|
||||
]);
|
||||
}
|
||||
|
||||
/// Force uniquement le mode portrait (pour certains écrans si nécessaire)
|
||||
static void enablePortraitOnly() {
|
||||
SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.portraitUp,
|
||||
DeviceOrientation.portraitDown,
|
||||
]);
|
||||
}
|
||||
|
||||
/// Force uniquement le mode paysage
|
||||
static void enableLandscapeOnly() {
|
||||
SystemChrome.setPreferredOrientations([
|
||||
DeviceOrientation.landscapeLeft,
|
||||
DeviceOrientation.landscapeRight,
|
||||
]);
|
||||
}
|
||||
|
||||
// =================== DIMENSIONS RESPONSIVES ===================
|
||||
|
||||
/// Obtient la largeur responsive selon l'appareil
|
||||
static double getResponsiveWidth(BuildContext context, {
|
||||
double? phone,
|
||||
double? tablet,
|
||||
double? desktop,
|
||||
}) {
|
||||
if (isDesktop(context)) return desktop ?? tablet ?? phone ?? 0;
|
||||
if (isTablet(context)) return tablet ?? phone ?? 0;
|
||||
return phone ?? 0;
|
||||
}
|
||||
|
||||
/// Obtient la hauteur responsive selon l'appareil
|
||||
static double getResponsiveHeight(BuildContext context, {
|
||||
double? phone,
|
||||
double? tablet,
|
||||
double? desktop,
|
||||
}) {
|
||||
if (isDesktop(context)) return desktop ?? tablet ?? phone ?? 0;
|
||||
if (isTablet(context)) return tablet ?? phone ?? 0;
|
||||
return phone ?? 0;
|
||||
}
|
||||
|
||||
/// Padding responsive adaptatif
|
||||
static EdgeInsets getResponsivePadding(BuildContext context, {
|
||||
EdgeInsets? phone,
|
||||
EdgeInsets? tablet,
|
||||
EdgeInsets? desktop,
|
||||
}) {
|
||||
if (isDesktop(context)) return desktop ?? tablet ?? phone ?? EdgeInsets.zero;
|
||||
if (isTablet(context)) return tablet ?? phone ?? EdgeInsets.zero;
|
||||
return phone ?? EdgeInsets.zero;
|
||||
}
|
||||
|
||||
/// Taille de police responsive
|
||||
static double getResponsiveFontSize(BuildContext context, {
|
||||
double? phone,
|
||||
double? tablet,
|
||||
double? desktop,
|
||||
}) {
|
||||
if (isDesktop(context)) return desktop ?? tablet ?? phone ?? 14;
|
||||
if (isTablet(context)) return tablet ?? phone ?? 14;
|
||||
return phone ?? 14;
|
||||
}
|
||||
|
||||
// =================== GRILLES RESPONSIVES ===================
|
||||
|
||||
/// Nombre de colonnes selon la taille d'écran
|
||||
static int getGridColumns(BuildContext context, {
|
||||
int phoneColumns = 2,
|
||||
int tabletPortraitColumns = 3,
|
||||
int tabletLandscapeColumns = 4,
|
||||
int desktopColumns = 5,
|
||||
}) {
|
||||
if (isDesktop(context)) return desktopColumns;
|
||||
if (isTabletLandscape(context)) return tabletLandscapeColumns;
|
||||
if (isTablet(context)) return tabletPortraitColumns;
|
||||
return phoneColumns;
|
||||
}
|
||||
|
||||
/// Ratio d'aspect adaptatif pour les cartes
|
||||
static double getCardAspectRatio(BuildContext context) {
|
||||
if (isPhoneLandscape(context)) return 2.5;
|
||||
if (isTabletLandscape(context)) return 1.8;
|
||||
if (isTablet(context)) return 1.4;
|
||||
return 1.2; // Portrait par défaut
|
||||
}
|
||||
|
||||
// =================== WIDGETS RESPONSIVES ===================
|
||||
|
||||
/// Container responsive avec padding adaptatif
|
||||
static Widget responsiveContainer({
|
||||
required BuildContext context,
|
||||
required Widget child,
|
||||
EdgeInsets? phonePadding,
|
||||
EdgeInsets? tabletPadding,
|
||||
EdgeInsets? desktopPadding,
|
||||
Color? backgroundColor,
|
||||
BorderRadius? borderRadius,
|
||||
}) {
|
||||
return Container(
|
||||
padding: getResponsivePadding(
|
||||
context,
|
||||
phone: phonePadding ?? const EdgeInsets.all(16),
|
||||
tablet: tabletPadding ?? const EdgeInsets.all(24),
|
||||
desktop: desktopPadding ?? const EdgeInsets.all(32),
|
||||
),
|
||||
decoration: BoxDecoration(
|
||||
color: backgroundColor,
|
||||
borderRadius: borderRadius ?? BorderRadius.circular(12),
|
||||
),
|
||||
child: child,
|
||||
);
|
||||
}
|
||||
|
||||
/// Texte responsive avec tailles adaptatives
|
||||
static Widget responsiveText(
|
||||
String text, {
|
||||
required BuildContext context,
|
||||
double? phoneSize,
|
||||
double? tabletSize,
|
||||
double? desktopSize,
|
||||
FontWeight? fontWeight,
|
||||
Color? color,
|
||||
TextAlign? textAlign,
|
||||
int? maxLines,
|
||||
TextOverflow? overflow,
|
||||
}) {
|
||||
return Text(
|
||||
text,
|
||||
style: TextStyle(
|
||||
fontSize: getResponsiveFontSize(
|
||||
context,
|
||||
phone: phoneSize ?? 14,
|
||||
tablet: tabletSize ?? 16,
|
||||
desktop: desktopSize ?? 18,
|
||||
),
|
||||
fontWeight: fontWeight,
|
||||
color: color,
|
||||
),
|
||||
textAlign: textAlign,
|
||||
maxLines: maxLines,
|
||||
overflow: overflow,
|
||||
);
|
||||
}
|
||||
|
||||
// =================== LAYOUTS RESPONSIVES ===================
|
||||
|
||||
/// Layout responsive en colonnes
|
||||
static Widget responsiveRow({
|
||||
required BuildContext context,
|
||||
required List<Widget> children,
|
||||
MainAxisAlignment mainAxisAlignment = MainAxisAlignment.start,
|
||||
CrossAxisAlignment crossAxisAlignment = CrossAxisAlignment.center,
|
||||
bool forceColumnOnPhone = true,
|
||||
}) {
|
||||
if (forceColumnOnPhone && isPhone(context)) {
|
||||
return Column(
|
||||
mainAxisAlignment: mainAxisAlignment,
|
||||
crossAxisAlignment: crossAxisAlignment,
|
||||
children: children,
|
||||
);
|
||||
}
|
||||
|
||||
return Row(
|
||||
mainAxisAlignment: mainAxisAlignment,
|
||||
crossAxisAlignment: crossAxisAlignment,
|
||||
children: children,
|
||||
);
|
||||
}
|
||||
|
||||
/// GridView responsive adaptatif
|
||||
static Widget responsiveGridView({
|
||||
required BuildContext context,
|
||||
required List<Widget> children,
|
||||
int? phoneColumns,
|
||||
int? tabletPortraitColumns,
|
||||
int? tabletLandscapeColumns,
|
||||
int? desktopColumns,
|
||||
double childAspectRatio = 1.0,
|
||||
double crossAxisSpacing = 8.0,
|
||||
double mainAxisSpacing = 8.0,
|
||||
EdgeInsets? padding,
|
||||
ScrollPhysics? physics,
|
||||
}) {
|
||||
final columns = getGridColumns(
|
||||
context,
|
||||
phoneColumns: phoneColumns ?? 2,
|
||||
tabletPortraitColumns: tabletPortraitColumns ?? 3,
|
||||
tabletLandscapeColumns: tabletLandscapeColumns ?? 4,
|
||||
desktopColumns: desktopColumns ?? 5,
|
||||
);
|
||||
|
||||
return GridView.count(
|
||||
shrinkWrap: true,
|
||||
physics: physics ?? const NeverScrollableScrollPhysics(),
|
||||
crossAxisCount: columns,
|
||||
childAspectRatio: childAspectRatio,
|
||||
crossAxisSpacing: crossAxisSpacing,
|
||||
mainAxisSpacing: mainAxisSpacing,
|
||||
padding: padding ?? getResponsivePadding(
|
||||
context,
|
||||
phone: const EdgeInsets.all(16),
|
||||
tablet: const EdgeInsets.all(24),
|
||||
),
|
||||
children: children,
|
||||
);
|
||||
}
|
||||
|
||||
// =================== NAVIGATION RESPONSIVE ===================
|
||||
|
||||
/// Détermine si on doit utiliser un Drawer ou une BottomNavigationBar
|
||||
static bool shouldUseDrawer(BuildContext context) {
|
||||
return isTabletLandscape(context) || isDesktop(context);
|
||||
}
|
||||
|
||||
/// Détermine si on doit utiliser une navigation rail (côté gauche)
|
||||
static bool shouldUseNavigationRail(BuildContext context) {
|
||||
return isTabletLandscape(context) || isDesktop(context);
|
||||
}
|
||||
|
||||
// =================== ORIENTATIONS SPÉCIFIQUES ===================
|
||||
|
||||
/// Initialise les orientations selon l'appareil
|
||||
static void initializeOrientations(BuildContext context) {
|
||||
if (isTablet(context) || isDesktop(context)) {
|
||||
enableAllOrientations();
|
||||
} else {
|
||||
// Pour les téléphones, on peut choisir de limiter ou non
|
||||
enableAllOrientations(); // Ou enablePortraitOnly() selon les besoins
|
||||
}
|
||||
}
|
||||
|
||||
// =================== UTILITAIRES DIVERS ===================
|
||||
|
||||
/// Obtient la largeur maximale recommandée pour le contenu
|
||||
static double getMaxContentWidth(BuildContext context) {
|
||||
final screenWidth = MediaQuery.of(context).size.width;
|
||||
|
||||
if (isDesktop(context)) {
|
||||
return math.min(screenWidth * 0.8, 1200); // Max 1200px sur desktop
|
||||
} else if (isTablet(context)) {
|
||||
return screenWidth * 0.9; // 90% sur tablette
|
||||
}
|
||||
return screenWidth; // 100% sur téléphone
|
||||
}
|
||||
|
||||
/// Centre le contenu avec une largeur maximale
|
||||
static Widget centerContent({
|
||||
required BuildContext context,
|
||||
required Widget child,
|
||||
double? maxWidth,
|
||||
}) {
|
||||
return Center(
|
||||
child: ConstrainedBox(
|
||||
constraints: BoxConstraints(
|
||||
maxWidth: maxWidth ?? getMaxContentWidth(context),
|
||||
),
|
||||
child: child,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Détermine l'espacement entre les éléments
|
||||
static double getSpacing(BuildContext context, {
|
||||
double? small,
|
||||
double? medium,
|
||||
double? large,
|
||||
}) {
|
||||
if (isDesktop(context)) return large ?? 24;
|
||||
if (isTablet(context)) return medium ?? 16;
|
||||
return small ?? 12;
|
||||
}
|
||||
}
|
||||
|
||||
// =================== EXTENSION POUR MEDIAQUERY ===================
|
||||
|
||||
/// Extension pour simplifier l'utilisation de ResponsiveHelper
|
||||
extension ResponsiveExtension on BuildContext {
|
||||
bool get isSmallPhone => ResponsiveHelper.isSmallPhone(this);
|
||||
bool get isPhone => ResponsiveHelper.isPhone(this);
|
||||
bool get isTablet => ResponsiveHelper.isTablet(this);
|
||||
bool get isDesktop => ResponsiveHelper.isDesktop(this);
|
||||
bool get isPortrait => ResponsiveHelper.isPortrait(this);
|
||||
bool get isLandscape => ResponsiveHelper.isLandscape(this);
|
||||
bool get isTabletLandscape => ResponsiveHelper.isTabletLandscape(this);
|
||||
bool get isPhoneLandscape => ResponsiveHelper.isPhoneLandscape(this);
|
||||
|
||||
double responsiveWidth({double? phone, double? tablet, double? desktop}) =>
|
||||
ResponsiveHelper.getResponsiveWidth(this, phone: phone, tablet: tablet, desktop: desktop);
|
||||
|
||||
double responsiveHeight({double? phone, double? tablet, double? desktop}) =>
|
||||
ResponsiveHelper.getResponsiveHeight(this, phone: phone, tablet: tablet, desktop: desktop);
|
||||
|
||||
double responsiveFontSize({double? phone, double? tablet, double? desktop}) =>
|
||||
ResponsiveHelper.getResponsiveFontSize(this, phone: phone, tablet: tablet, desktop: desktop);
|
||||
|
||||
EdgeInsets responsivePadding({EdgeInsets? phone, EdgeInsets? tablet, EdgeInsets? desktop}) =>
|
||||
ResponsiveHelper.getResponsivePadding(this, phone: phone, tablet: tablet, desktop: desktop);
|
||||
}
|
||||
|
||||
108
lib/widgets/wortis_logo.dart
Normal file
108
lib/widgets/wortis_logo.dart
Normal file
@@ -0,0 +1,108 @@
|
||||
// ===== lib/widgets/wortis_logo.dart FONCTIONNEL =====
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class WortisLogoWidget extends StatelessWidget {
|
||||
final double size;
|
||||
final bool isWhite;
|
||||
final bool withShadow;
|
||||
final String? customPath;
|
||||
|
||||
const WortisLogoWidget({
|
||||
super.key,
|
||||
this.size = 100,
|
||||
this.isWhite = false,
|
||||
this.withShadow = true,
|
||||
this.customPath,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Utilise exactement vos noms de fichiers
|
||||
String logoPath =
|
||||
customPath ??
|
||||
(isWhite
|
||||
? 'assets/images/wortis_logo_white.png'
|
||||
: 'assets/images/wortis_logo.png');
|
||||
|
||||
return Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
borderRadius: BorderRadius.circular(size * 0.15),
|
||||
boxShadow:
|
||||
withShadow
|
||||
? [
|
||||
BoxShadow(
|
||||
color: Colors.black.withOpacity(0.2),
|
||||
blurRadius: size * 0.1,
|
||||
offset: Offset(0, size * 0.05),
|
||||
spreadRadius: 1,
|
||||
),
|
||||
]
|
||||
: null,
|
||||
),
|
||||
child: ClipRRect(
|
||||
borderRadius: BorderRadius.circular(size * 0.15),
|
||||
child: Image.asset(
|
||||
logoPath,
|
||||
width: size,
|
||||
height: size,
|
||||
fit: BoxFit.contain,
|
||||
errorBuilder: (context, error, stackTrace) {
|
||||
// Debug : Afficher l'erreur pour diagnostiquer
|
||||
print('Erreur chargement logo: $error');
|
||||
print('Chemin tenté: $logoPath');
|
||||
|
||||
// Fallback avec le "W" stylisé
|
||||
return Container(
|
||||
width: size,
|
||||
height: size,
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [Color(0xFF006699), Color(0xFF0088CC)],
|
||||
),
|
||||
borderRadius: BorderRadius.circular(size * 0.15),
|
||||
boxShadow:
|
||||
withShadow
|
||||
? [
|
||||
BoxShadow(
|
||||
color: Color(0xFF006699).withOpacity(0.3),
|
||||
blurRadius: size * 0.15,
|
||||
offset: Offset(0, size * 0.08),
|
||||
),
|
||||
]
|
||||
: null,
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
DIAGNOSTIC : Si les images ne s'affichent toujours pas, vérifiez :
|
||||
|
||||
1. pubspec.yaml contient bien :
|
||||
flutter:
|
||||
assets:
|
||||
- assets/images/
|
||||
|
||||
2. Redémarrez l'app complètement (hot restart, pas hot reload)
|
||||
|
||||
3. Dans votre terminal, exécutez :
|
||||
flutter clean
|
||||
flutter pub get
|
||||
flutter run
|
||||
|
||||
4. Vérifiez que les images sont bien au format PNG/JPG valide
|
||||
|
||||
5. Si ça ne marche toujours pas, essayez de renommer temporairement
|
||||
vos fichiers en :
|
||||
- logo1.png
|
||||
- logo2.png
|
||||
Et modifiez les chemins dans le code pour tester.
|
||||
*/
|
||||
Reference in New Issue
Block a user