- Corrige l'erreur SQL 'Unknown column fk_operation in users' - L'opération active est récupérée depuis operations.chk_active = 1 - Jointure avec users pour filtrer par entité de l'admin créateur - Query: SELECT o.id FROM operations o INNER JOIN users u ON u.fk_entite = o.fk_entite WHERE u.id = ? AND o.chk_active = 1
1214 lines
44 KiB
Dart
Executable File
1214 lines
44 KiB
Dart
Executable File
import 'package:flutter/material.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'package:geosector_app/core/services/app_info_service.dart';
|
|
import 'package:geosector_app/core/services/hive_service.dart';
|
|
import 'package:geosector_app/core/services/location_service.dart';
|
|
import 'package:geosector_app/core/constants/app_keys.dart';
|
|
import 'package:hive_flutter/hive_flutter.dart';
|
|
import 'dart:async';
|
|
import 'dart:math' as math;
|
|
import 'package:flutter/foundation.dart' show kIsWeb;
|
|
import 'package:url_launcher/url_launcher.dart';
|
|
// Import conditionnel pour le web
|
|
import 'package:universal_html/html.dart' as html;
|
|
// Import des repositories pour reset du cache
|
|
import 'package:geosector_app/app.dart' show passageRepository, sectorRepository, membreRepository;
|
|
// Import des services pour la gestion de session F5
|
|
import 'package:geosector_app/core/services/current_user_service.dart';
|
|
import 'package:geosector_app/core/services/api_service.dart';
|
|
import 'package:geosector_app/core/services/data_loading_service.dart';
|
|
|
|
class SplashPage extends StatefulWidget {
|
|
/// Action à effectuer après l'initialisation (login ou register)
|
|
final String? action;
|
|
|
|
/// Type de login/register (user ou admin) - ignoré pour register
|
|
final String? type;
|
|
|
|
const SplashPage({super.key, this.action, this.type});
|
|
|
|
@override
|
|
State<SplashPage> createState() => _SplashPageState();
|
|
}
|
|
|
|
// Class pour dessiner les petits points blancs sur le fond
|
|
class DotsPainter extends CustomPainter {
|
|
@override
|
|
void paint(Canvas canvas, Size size) {
|
|
final paint = Paint()
|
|
..color = Colors.white.withOpacity(0.5)
|
|
..style = PaintingStyle.fill;
|
|
|
|
final random = math.Random(42); // Seed fixe pour consistance
|
|
final numberOfDots = (size.width * size.height) ~/ 1500;
|
|
|
|
for (int i = 0; i < numberOfDots; i++) {
|
|
final x = random.nextDouble() * size.width;
|
|
final y = random.nextDouble() * size.height;
|
|
final radius = 1.0 + random.nextDouble() * 2.0;
|
|
canvas.drawCircle(Offset(x, y), radius, paint);
|
|
}
|
|
}
|
|
|
|
@override
|
|
bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
|
|
}
|
|
|
|
class _SplashPageState extends State<SplashPage> with SingleTickerProviderStateMixin {
|
|
late AnimationController _animationController;
|
|
late Animation<double> _scaleAnimation;
|
|
bool _isInitializing = true;
|
|
String _statusMessage = "Initialisation...";
|
|
double _progress = 0.0;
|
|
bool _showButtons = false;
|
|
String _appVersion = '';
|
|
bool _showLocationError = false;
|
|
String? _locationErrorMessage;
|
|
bool _isCleaningCache = false;
|
|
|
|
Future<void> _getAppVersion() async {
|
|
// Utilise directement AppInfoService (remplace package_info_plus)
|
|
if (mounted) {
|
|
setState(() {
|
|
_appVersion = AppInfoService.version;
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Effectue un nettoyage sélectif du cache
|
|
/// Préserve la box pending_requests et les données critiques
|
|
Future<void> _performSelectiveCleanup({bool manual = false}) async {
|
|
debugPrint('🧹 Nettoyage du cache (${manual ? "manuel" : "auto"})...');
|
|
|
|
try {
|
|
if (mounted) {
|
|
setState(() {
|
|
_isCleaningCache = true;
|
|
_statusMessage = "Nettoyage du cache en cours...";
|
|
_progress = 0.1;
|
|
});
|
|
}
|
|
|
|
// Étape 1: Nettoyer le Service Worker (Web uniquement)
|
|
if (kIsWeb) {
|
|
try {
|
|
final registrations = await html.window.navigator.serviceWorker?.getRegistrations();
|
|
if (registrations != null) {
|
|
for (final registration in registrations) {
|
|
await registration.unregister();
|
|
}
|
|
}
|
|
if (html.window.caches != null) {
|
|
final cacheNames = await html.window.caches!.keys();
|
|
for (final cacheName in cacheNames) {
|
|
await html.window.caches!.delete(cacheName);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur Service Worker: $e');
|
|
}
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Fermeture des bases de données...";
|
|
_progress = 0.3;
|
|
});
|
|
}
|
|
|
|
// Étape 2: Sauvegarder les données critiques (pending_requests + app_version)
|
|
List<dynamic>? pendingRequests;
|
|
String? savedAppVersion;
|
|
try {
|
|
if (Hive.isBoxOpen(AppKeys.pendingRequestsBoxName)) {
|
|
final pendingBox = Hive.box(AppKeys.pendingRequestsBoxName);
|
|
pendingRequests = pendingBox.values.toList();
|
|
await pendingBox.close();
|
|
}
|
|
if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
|
|
final settingsBox = Hive.box(AppKeys.settingsBoxName);
|
|
savedAppVersion = settingsBox.get('app_version') as String?;
|
|
}
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur sauvegarde données critiques: $e');
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Nettoyage des données locales...";
|
|
_progress = 0.5;
|
|
});
|
|
}
|
|
|
|
// Étape 3: Lister toutes les boxes à nettoyer (SAUF pending_requests)
|
|
final boxesToClean = [
|
|
AppKeys.userBoxName,
|
|
AppKeys.operationsBoxName,
|
|
AppKeys.passagesBoxName,
|
|
AppKeys.sectorsBoxName,
|
|
AppKeys.membresBoxName,
|
|
AppKeys.amicaleBoxName,
|
|
AppKeys.clientsBoxName,
|
|
AppKeys.userSectorBoxName,
|
|
AppKeys.settingsBoxName,
|
|
AppKeys.chatRoomsBoxName,
|
|
AppKeys.chatMessagesBoxName,
|
|
];
|
|
|
|
// Étape 4: Fermer et supprimer les boxes
|
|
for (final boxName in boxesToClean) {
|
|
try {
|
|
if (Hive.isBoxOpen(boxName)) {
|
|
await Hive.box(boxName).close();
|
|
}
|
|
await Hive.deleteBoxFromDisk(boxName);
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur nettoyage box "$boxName": $e');
|
|
}
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Réinitialisation de Hive...";
|
|
_progress = 0.7;
|
|
});
|
|
}
|
|
|
|
// Étape 5: Réinitialiser Hive proprement
|
|
await Hive.close();
|
|
await Future.delayed(const Duration(milliseconds: 500));
|
|
await Hive.initFlutter();
|
|
|
|
// Étape 6: Restaurer les données critiques
|
|
if (pendingRequests != null && pendingRequests.isNotEmpty) {
|
|
final pendingBox = await Hive.openBox(AppKeys.pendingRequestsBoxName);
|
|
for (final request in pendingRequests) {
|
|
await pendingBox.add(request);
|
|
}
|
|
}
|
|
|
|
if (savedAppVersion != null) {
|
|
final settingsBox = await Hive.openBox(AppKeys.settingsBoxName);
|
|
await settingsBox.put('app_version', savedAppVersion);
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Nettoyage terminé !";
|
|
_progress = 1.0;
|
|
});
|
|
}
|
|
|
|
debugPrint('✅ Nettoyage du cache terminé');
|
|
|
|
// Petit délai pour voir le message de succès
|
|
await Future.delayed(const Duration(milliseconds: 500));
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_isCleaningCache = false;
|
|
_progress = 0.0;
|
|
});
|
|
}
|
|
|
|
} catch (e) {
|
|
debugPrint('❌ Erreur nettoyage cache: $e');
|
|
if (mounted) {
|
|
setState(() {
|
|
_isCleaningCache = false;
|
|
_statusMessage = "Erreur lors du nettoyage";
|
|
_progress = 0.0;
|
|
});
|
|
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text('Erreur lors du nettoyage: $e'),
|
|
backgroundColor: Colors.red,
|
|
duration: const Duration(seconds: 5),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Réinitialise le cache de tous les repositories après nettoyage complet
|
|
void _resetAllRepositoriesCache() {
|
|
try {
|
|
passageRepository.resetCache();
|
|
sectorRepository.resetCache();
|
|
membreRepository.resetCache();
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur reset caches repositories: $e');
|
|
}
|
|
}
|
|
|
|
/// Détecte et gère le refresh (F5) avec session existante
|
|
/// Retourne true si une session a été restaurée, false sinon
|
|
Future<bool> _handleSessionRefreshIfNeeded() async {
|
|
if (!kIsWeb) return false;
|
|
|
|
try {
|
|
await CurrentUserService.instance.loadFromHive();
|
|
|
|
final isLoggedIn = CurrentUserService.instance.isLoggedIn;
|
|
final displayMode = CurrentUserService.instance.displayMode;
|
|
final sessionId = CurrentUserService.instance.sessionId;
|
|
|
|
if (!isLoggedIn || sessionId == null) return false;
|
|
|
|
debugPrint('🔄 Session active détectée, restauration...');
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Restauration de votre session...";
|
|
_progress = 0.85;
|
|
});
|
|
}
|
|
|
|
// Configurer ApiService avec le sessionId existant
|
|
ApiService.instance.setSessionId(sessionId);
|
|
|
|
// Appeler le nouvel endpoint API pour restaurer la session
|
|
// IMPORTANT: Utiliser getWithoutQueue() pour ne JAMAIS mettre cette requête en file d'attente
|
|
final response = await ApiService.instance.getWithoutQueue(
|
|
'user/session',
|
|
queryParameters: {'mode': displayMode},
|
|
);
|
|
|
|
// Gestion des codes de retour HTTP
|
|
final statusCode = response.statusCode ?? 0;
|
|
|
|
// Vérifier que la réponse est bien du JSON et pas du HTML
|
|
if (response.data is String) {
|
|
final dataStr = response.data as String;
|
|
if (dataStr.contains('<!DOCTYPE') || dataStr.contains('<html')) {
|
|
debugPrint('❌ L\'API a retourné du HTML au lieu de JSON');
|
|
await CurrentUserService.instance.clearUser();
|
|
return false;
|
|
}
|
|
}
|
|
|
|
final data = response.data as Map<String, dynamic>?;
|
|
|
|
switch (statusCode) {
|
|
case 200:
|
|
if (data == null || data['success'] != true) {
|
|
debugPrint('❌ Format de réponse session invalide');
|
|
await CurrentUserService.instance.clearUser();
|
|
return false;
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Chargement de vos données...";
|
|
_progress = 0.90;
|
|
});
|
|
}
|
|
|
|
final apiData = data['data'] as Map<String, dynamic>?;
|
|
if (apiData == null) {
|
|
debugPrint('❌ Données manquantes dans la réponse');
|
|
await CurrentUserService.instance.clearUser();
|
|
return false;
|
|
}
|
|
|
|
await DataLoadingService.instance.processLoginData(apiData);
|
|
break;
|
|
|
|
case 400:
|
|
debugPrint('❌ Paramètre mode invalide: $displayMode');
|
|
await CurrentUserService.instance.clearUser();
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Erreur technique - veuillez vous reconnecter";
|
|
});
|
|
}
|
|
return false;
|
|
|
|
case 401:
|
|
debugPrint('⚠️ Session expirée');
|
|
await CurrentUserService.instance.clearUser();
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Session expirée - veuillez vous reconnecter";
|
|
});
|
|
}
|
|
return false;
|
|
|
|
case 403:
|
|
final message = data?['message'] ?? 'Accès interdit';
|
|
debugPrint('❌ Accès interdit: $message');
|
|
await CurrentUserService.instance.clearUser();
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Accès interdit - veuillez vous reconnecter";
|
|
});
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text(message),
|
|
backgroundColor: Colors.orange,
|
|
duration: const Duration(seconds: 5),
|
|
),
|
|
);
|
|
}
|
|
return false;
|
|
|
|
case 500:
|
|
final message = data?['message'] ?? 'Erreur serveur';
|
|
debugPrint('❌ Erreur serveur: $message');
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Erreur serveur - veuillez réessayer";
|
|
});
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
content: Text('Erreur serveur: $message'),
|
|
backgroundColor: Colors.red,
|
|
duration: const Duration(seconds: 5),
|
|
),
|
|
);
|
|
}
|
|
return false;
|
|
|
|
default:
|
|
debugPrint('❌ Code HTTP inattendu: $statusCode');
|
|
await CurrentUserService.instance.clearUser();
|
|
return false;
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Session restaurée !";
|
|
_progress = 0.95;
|
|
});
|
|
}
|
|
|
|
// Petit délai pour voir le message
|
|
await Future.delayed(const Duration(milliseconds: 500));
|
|
|
|
// Rediriger vers la bonne interface selon le mode
|
|
if (!mounted) return true;
|
|
|
|
if (displayMode == 'admin') {
|
|
context.go('/admin/home');
|
|
} else {
|
|
context.go('/user/field-mode');
|
|
}
|
|
debugPrint('✅ Session restaurée → $displayMode');
|
|
|
|
return true;
|
|
|
|
} catch (e) {
|
|
debugPrint('❌ Erreur lors de la restauration de session: $e');
|
|
|
|
// En cas d'erreur, effacer la session invalide
|
|
await CurrentUserService.instance.clearUser();
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Erreur de restauration - veuillez vous reconnecter";
|
|
_progress = 0.0;
|
|
});
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|
|
|
|
/// Vérifie si une nouvelle version est disponible et nettoie si nécessaire
|
|
Future<void> _checkVersionAndCleanIfNeeded() async {
|
|
if (!kIsWeb) return;
|
|
|
|
try {
|
|
String lastVersion = '';
|
|
if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
|
|
final settingsBox = Hive.box(AppKeys.settingsBoxName);
|
|
lastVersion = settingsBox.get('app_version', defaultValue: '') as String;
|
|
}
|
|
|
|
if (lastVersion.isNotEmpty && lastVersion != _appVersion) {
|
|
debugPrint('🆕 Nouvelle version: $lastVersion → $_appVersion');
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Nouvelle version détectée, mise à jour...";
|
|
});
|
|
}
|
|
await _performSelectiveCleanup(manual: false);
|
|
_resetAllRepositoriesCache();
|
|
} else if (lastVersion.isEmpty) {
|
|
if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
|
|
final settingsBox = Hive.box(AppKeys.settingsBoxName);
|
|
await settingsBox.put('app_version', _appVersion);
|
|
}
|
|
}
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur vérification version: $e');
|
|
}
|
|
}
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
|
|
// Animation controller
|
|
_animationController = AnimationController(
|
|
vsync: this,
|
|
duration: const Duration(seconds: 5),
|
|
);
|
|
|
|
_scaleAnimation = Tween<double>(
|
|
begin: 4.0,
|
|
end: 1.0,
|
|
).animate(
|
|
CurvedAnimation(
|
|
parent: _animationController,
|
|
curve: Curves.easeOutBack,
|
|
),
|
|
);
|
|
|
|
_animationController.forward();
|
|
_getAppVersion();
|
|
_startInitialization();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
_animationController.dispose();
|
|
super.dispose();
|
|
}
|
|
|
|
void _startInitialization() async {
|
|
try {
|
|
debugPrint('🚀 Initialisation de l\'application...');
|
|
|
|
// Étape 1: Vérification des permissions GPS (obligatoire) - 0 à 10%
|
|
if (!kIsWeb) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Vérification des autorisations GPS...";
|
|
_progress = 0.05;
|
|
});
|
|
}
|
|
|
|
await Future.delayed(const Duration(milliseconds: 200));
|
|
|
|
final hasPermission = await LocationService.checkAndRequestPermission();
|
|
final errorMessage = await LocationService.getLocationErrorMessage();
|
|
|
|
if (!hasPermission) {
|
|
debugPrint('❌ Permissions GPS refusées');
|
|
if (mounted) {
|
|
setState(() {
|
|
_showLocationError = true;
|
|
_locationErrorMessage = errorMessage ?? "L'application nécessite l'accès à votre position pour fonctionner correctement.";
|
|
_isInitializing = false;
|
|
_progress = 0.0;
|
|
});
|
|
}
|
|
return; // On arrête l'initialisation ici
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Autorisations GPS accordées...";
|
|
_progress = 0.10;
|
|
});
|
|
}
|
|
}
|
|
|
|
// Étape 1: Préparation - 10 à 15%
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Démarrage de l'application...";
|
|
_progress = 0.12;
|
|
});
|
|
}
|
|
|
|
await Future.delayed(const Duration(milliseconds: 200)); // Petit délai pour voir le début
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Chargement des composants...";
|
|
_progress = 0.15;
|
|
});
|
|
}
|
|
|
|
// === GESTION F5 WEB : Vérifier session AVANT de détruire les données ===
|
|
if (kIsWeb) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Vérification de session...";
|
|
_progress = 0.20;
|
|
});
|
|
}
|
|
|
|
final hasExistingSession = await HiveService.instance.initializeWithoutReset();
|
|
|
|
if (hasExistingSession) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Restauration de la session...";
|
|
_progress = 0.40;
|
|
});
|
|
}
|
|
|
|
final sessionRestored = await _handleSessionRefreshIfNeeded();
|
|
if (sessionRestored) return;
|
|
}
|
|
}
|
|
|
|
// === INITIALISATION NORMALE (si pas de session F5 ou pas Web) ===
|
|
// Étape 2: Initialisation Hive complète - 15 à 60%
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Configuration du stockage...";
|
|
_progress = 0.30;
|
|
});
|
|
}
|
|
|
|
await HiveService.instance.initializeAndResetHive();
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Préparation des données...";
|
|
_progress = 0.45;
|
|
});
|
|
}
|
|
|
|
await Future.delayed(const Duration(milliseconds: 300)); // Simulation du temps de traitement
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Ouverture des bases...";
|
|
_progress = 0.60;
|
|
});
|
|
}
|
|
|
|
// Étape 3: Ouverture des Box - 60 à 80%
|
|
await HiveService.instance.ensureBoxesAreOpen();
|
|
|
|
// Vérifier et nettoyer si nouvelle version (Web uniquement)
|
|
await _checkVersionAndCleanIfNeeded();
|
|
|
|
// Gérer la box pending_requests séparément pour préserver les données
|
|
try {
|
|
if (!Hive.isBoxOpen(AppKeys.pendingRequestsBoxName)) {
|
|
await Hive.openBox(AppKeys.pendingRequestsBoxName);
|
|
}
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur ouverture pending_requests: $e');
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Vérification du système...";
|
|
_progress = 0.80;
|
|
});
|
|
}
|
|
|
|
// Étape 4: Vérification finale - 80 à 95%
|
|
final allBoxesOpen = HiveService.instance.areAllBoxesOpen();
|
|
if (!allBoxesOpen) {
|
|
debugPrint('❌ Erreur: certaines boxes Hive non ouvertes');
|
|
throw Exception('Une erreur est survenue lors de l\'initialisation');
|
|
}
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Finalisation du chargement...";
|
|
_progress = 0.95;
|
|
});
|
|
}
|
|
|
|
await Future.delayed(const Duration(milliseconds: 300)); // Petit délai pour finaliser
|
|
|
|
// Étape 5: Finalisation - 95 à 100%
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Application prête !";
|
|
_progress = 1.0;
|
|
});
|
|
|
|
// Marquer dans settings que l'initialisation complète de Hive a été effectuée
|
|
try {
|
|
if (Hive.isBoxOpen(AppKeys.settingsBoxName)) {
|
|
final settingsBox = Hive.box(AppKeys.settingsBoxName);
|
|
await settingsBox.put('hive_initialized', true);
|
|
await settingsBox.put('hive_initialized_at', DateTime.now().toIso8601String());
|
|
}
|
|
} catch (e) {
|
|
debugPrint('⚠️ Erreur hive_initialized: $e');
|
|
}
|
|
|
|
// Attendre un court instant pour que l'utilisateur voie "Application prête !"
|
|
await Future.delayed(const Duration(milliseconds: 400));
|
|
|
|
setState(() {
|
|
_isInitializing = false;
|
|
});
|
|
|
|
// Redirection automatique si des paramètres sont fournis
|
|
if (widget.action != null) {
|
|
await _handleAutoRedirect();
|
|
} else {
|
|
// Sur mobile natif ou petit écran, rediriger directement vers connexion utilisateur
|
|
// L'interface admin n'est disponible que sur Web avec grand écran
|
|
if (mounted) {
|
|
final screenWidth = MediaQuery.of(context).size.width;
|
|
final isSmallScreen = screenWidth < 600;
|
|
|
|
if (!kIsWeb || isSmallScreen) {
|
|
context.go('/login/user');
|
|
} else {
|
|
setState(() {
|
|
_showButtons = true;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
debugPrint('✅ Initialisation terminée');
|
|
} catch (e) {
|
|
debugPrint('❌ Erreur initialisation: $e');
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_statusMessage = "Erreur de chargement - Veuillez redémarrer l'application";
|
|
_progress = 1.0;
|
|
_isInitializing = false;
|
|
});
|
|
|
|
// Sur mobile natif ou petit écran, rediriger vers connexion utilisateur même en cas d'erreur
|
|
// L'interface admin n'est disponible que sur Web avec grand écran
|
|
final screenWidth = MediaQuery.of(context).size.width;
|
|
final isSmallScreen = screenWidth < 600;
|
|
|
|
if (!kIsWeb || isSmallScreen) {
|
|
context.go('/login/user');
|
|
} else {
|
|
setState(() {
|
|
_showButtons = true;
|
|
});
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Gère la redirection automatique après l'initialisation
|
|
Future<void> _handleAutoRedirect() async {
|
|
await Future.delayed(const Duration(milliseconds: 300));
|
|
|
|
if (!mounted) return;
|
|
|
|
final action = widget.action?.toLowerCase();
|
|
final type = widget.type?.toLowerCase();
|
|
|
|
// Afficher un message de redirection avant de naviguer
|
|
setState(() {
|
|
_statusMessage = action == 'login'
|
|
? "Redirection vers la connexion..."
|
|
: action == 'register'
|
|
? "Redirection vers l'inscription..."
|
|
: "Redirection...";
|
|
});
|
|
|
|
await Future.delayed(const Duration(milliseconds: 200));
|
|
|
|
if (!mounted) return;
|
|
|
|
switch (action) {
|
|
case 'login':
|
|
if (type == 'admin') {
|
|
context.go('/login/admin');
|
|
} else {
|
|
// Par défaut, rediriger vers user si type non spécifié ou invalid
|
|
context.go('/login/user');
|
|
}
|
|
break;
|
|
case 'register':
|
|
// Pour register, le type n'est pas pris en compte
|
|
context.go('/register');
|
|
break;
|
|
default:
|
|
// Si action non reconnue, afficher les boutons normalement
|
|
setState(() {
|
|
_showButtons = true;
|
|
});
|
|
break;
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final theme = Theme.of(context);
|
|
|
|
return Scaffold(
|
|
body: Stack(
|
|
children: [
|
|
// Fond dégradé avec petits points blancs
|
|
AnimatedContainer(
|
|
duration: const Duration(milliseconds: 500),
|
|
decoration: BoxDecoration(
|
|
gradient: LinearGradient(
|
|
begin: Alignment.topCenter,
|
|
end: Alignment.bottomCenter,
|
|
colors: [Colors.white, Colors.blue.shade300],
|
|
),
|
|
),
|
|
child: CustomPaint(
|
|
painter: DotsPainter(),
|
|
child: const SizedBox(width: double.infinity, height: double.infinity),
|
|
),
|
|
),
|
|
|
|
// Contenu principal
|
|
SafeArea(
|
|
child: Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 40),
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
const Spacer(flex: 2),
|
|
|
|
// Logo avec animation
|
|
AnimatedBuilder(
|
|
animation: _scaleAnimation,
|
|
builder: (context, child) {
|
|
return Transform.scale(
|
|
scale: _scaleAnimation.value,
|
|
child: child,
|
|
);
|
|
},
|
|
child: Image.asset(
|
|
'assets/images/logo-geosector-1024.png',
|
|
height: 180,
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 24),
|
|
|
|
// Titre
|
|
AnimatedOpacity(
|
|
opacity: _isInitializing ? 0.9 : 1.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: Text(
|
|
'Geosector',
|
|
style: theme.textTheme.headlineLarge?.copyWith(
|
|
color: theme.colorScheme.primary,
|
|
fontWeight: FontWeight.bold,
|
|
letterSpacing: 1.2,
|
|
),
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 16),
|
|
|
|
// Sous-titre
|
|
AnimatedOpacity(
|
|
opacity: _isInitializing ? 0.8 : 1.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: Text(
|
|
'Une application puissante et intuitive de gestion de vos distributions de calendriers',
|
|
textAlign: TextAlign.center,
|
|
style: theme.textTheme.bodyLarge?.copyWith(
|
|
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
),
|
|
),
|
|
|
|
const Spacer(flex: 1),
|
|
|
|
// Indicateur de chargement
|
|
if ((_isInitializing || _isCleaningCache) && !_showLocationError) ...[
|
|
Padding(
|
|
padding: const EdgeInsets.symmetric(horizontal: 40),
|
|
child: Column(
|
|
children: [
|
|
// Barre de progression avec animation
|
|
Container(
|
|
decoration: BoxDecoration(
|
|
borderRadius: BorderRadius.circular(10),
|
|
boxShadow: [
|
|
BoxShadow(
|
|
color: theme.colorScheme.primary.withOpacity(0.2),
|
|
blurRadius: 8,
|
|
offset: const Offset(0, 2),
|
|
),
|
|
],
|
|
),
|
|
child: ClipRRect(
|
|
borderRadius: BorderRadius.circular(10),
|
|
child: TweenAnimationBuilder<double>(
|
|
duration: const Duration(milliseconds: 800),
|
|
curve: Curves.easeInOut,
|
|
tween: Tween(begin: 0.0, end: _progress),
|
|
builder: (context, value, child) {
|
|
return LinearProgressIndicator(
|
|
value: value,
|
|
backgroundColor: Colors.grey.withOpacity(0.15),
|
|
valueColor: AlwaysStoppedAnimation<Color>(
|
|
theme.colorScheme.primary,
|
|
),
|
|
minHeight: 12,
|
|
);
|
|
},
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 8),
|
|
// Pourcentage
|
|
Text(
|
|
'${(_progress * 100).round()}%',
|
|
style: theme.textTheme.bodySmall?.copyWith(
|
|
color: theme.colorScheme.primary,
|
|
fontWeight: FontWeight.w600,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
// Message de statut avec animation
|
|
AnimatedSwitcher(
|
|
duration: const Duration(milliseconds: 300),
|
|
child: Text(
|
|
_statusMessage,
|
|
key: ValueKey(_statusMessage),
|
|
style: theme.textTheme.bodyMedium?.copyWith(
|
|
color: theme.colorScheme.onSurface.withOpacity(0.7),
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
),
|
|
],
|
|
|
|
// Erreur de localisation
|
|
if (_showLocationError) ...[
|
|
Container(
|
|
padding: const EdgeInsets.all(16),
|
|
margin: const EdgeInsets.symmetric(horizontal: 20),
|
|
decoration: BoxDecoration(
|
|
color: Colors.red.shade50,
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: Colors.red.shade200),
|
|
),
|
|
child: Column(
|
|
children: [
|
|
Icon(
|
|
Icons.location_off,
|
|
size: 48,
|
|
color: Colors.red.shade700,
|
|
),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
'Autorisations GPS requises',
|
|
style: theme.textTheme.titleLarge?.copyWith(
|
|
color: Colors.red.shade700,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
const SizedBox(height: 8),
|
|
Text(
|
|
_locationErrorMessage ?? "L'application nécessite l'accès à votre position pour fonctionner correctement.",
|
|
textAlign: TextAlign.center,
|
|
style: theme.textTheme.bodyMedium?.copyWith(
|
|
color: Colors.red.shade700,
|
|
),
|
|
),
|
|
const SizedBox(height: 24),
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
// Bouton Réessayer
|
|
ElevatedButton.icon(
|
|
onPressed: () {
|
|
setState(() {
|
|
_showLocationError = false;
|
|
_isInitializing = true;
|
|
});
|
|
_startInitialization();
|
|
},
|
|
icon: const Icon(Icons.refresh),
|
|
label: const Text('Réessayer'),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.green,
|
|
foregroundColor: Colors.white,
|
|
),
|
|
),
|
|
const SizedBox(width: 16),
|
|
// Bouton Paramètres
|
|
OutlinedButton.icon(
|
|
onPressed: () async {
|
|
if (_locationErrorMessage?.contains('définitivement') ?? false) {
|
|
await LocationService.openAppSettings();
|
|
} else {
|
|
await LocationService.openLocationSettings();
|
|
}
|
|
},
|
|
icon: const Icon(Icons.settings),
|
|
label: const Text('Paramètres'),
|
|
style: OutlinedButton.styleFrom(
|
|
foregroundColor: Colors.red.shade700,
|
|
side: BorderSide(color: Colors.red.shade700),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
|
|
// Boutons (reste identique)
|
|
if (_showButtons) ...[
|
|
// Bouton Connexion Utilisateur
|
|
AnimatedOpacity(
|
|
opacity: _showButtons ? 1.0 : 0.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
context.go('/login/user');
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.green,
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 40,
|
|
vertical: 16,
|
|
),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(30),
|
|
),
|
|
elevation: 2,
|
|
),
|
|
child: const Text(
|
|
'Connexion Utilisateur',
|
|
style: TextStyle(
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
|
|
// Bouton Connexion Administrateur
|
|
AnimatedOpacity(
|
|
opacity: _showButtons ? 1.0 : 0.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
context.go('/login/admin');
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.red,
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 40,
|
|
vertical: 16,
|
|
),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(30),
|
|
),
|
|
elevation: 2,
|
|
),
|
|
child: const Text(
|
|
'Connexion Administrateur',
|
|
style: TextStyle(
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 32),
|
|
|
|
// Bouton d'inscription
|
|
AnimatedOpacity(
|
|
opacity: _showButtons ? 1.0 : 0.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: ElevatedButton(
|
|
onPressed: () {
|
|
context.go('/register');
|
|
},
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.blue,
|
|
foregroundColor: Colors.white,
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 40,
|
|
vertical: 16,
|
|
),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(30),
|
|
),
|
|
elevation: 2,
|
|
),
|
|
child: const Text(
|
|
'Pas encore inscrit ?',
|
|
style: TextStyle(
|
|
fontSize: 16,
|
|
fontWeight: FontWeight.bold,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 16),
|
|
|
|
// Lien vers le site web
|
|
AnimatedOpacity(
|
|
opacity: _showButtons ? 1.0 : 0.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: TextButton.icon(
|
|
onPressed: () {
|
|
String webUrl = 'https://geosector.fr';
|
|
|
|
if (kIsWeb) {
|
|
final host = Uri.base.host;
|
|
if (host.startsWith('dapp.')) {
|
|
webUrl = 'https://dev.geosector.fr';
|
|
} else if (host.startsWith('rapp.')) {
|
|
webUrl = 'https://rec.geosector.fr';
|
|
} else if (host.startsWith('app.')) {
|
|
webUrl = 'https://geosector.fr';
|
|
}
|
|
}
|
|
|
|
launchUrl(
|
|
Uri.parse(webUrl),
|
|
mode: LaunchMode.externalApplication,
|
|
);
|
|
},
|
|
icon: Icon(
|
|
Icons.language,
|
|
size: 18,
|
|
color: theme.colorScheme.primary,
|
|
),
|
|
label: Text(
|
|
'Site web Geosector',
|
|
style: TextStyle(
|
|
color: theme.colorScheme.primary,
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
|
|
const SizedBox(height: 8),
|
|
|
|
// Bouton de nettoyage du cache (Web uniquement)
|
|
if (kIsWeb)
|
|
AnimatedOpacity(
|
|
opacity: _showButtons ? 1.0 : 0.0,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: TextButton.icon(
|
|
onPressed: _isCleaningCache ? null : () async {
|
|
// Confirmation avant nettoyage
|
|
final confirm = await showDialog<bool>(
|
|
context: context,
|
|
builder: (context) => AlertDialog(
|
|
title: const Text('Nettoyer le cache ?'),
|
|
content: const Text(
|
|
'Cette action va :\n'
|
|
'• Supprimer toutes les données locales\n'
|
|
'• Préserver les requêtes en attente\n'
|
|
'• Forcer le rechargement de l\'application\n\n'
|
|
'Continuer ?'
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.of(context).pop(false),
|
|
child: const Text('Annuler'),
|
|
),
|
|
ElevatedButton(
|
|
onPressed: () => Navigator.of(context).pop(true),
|
|
style: ElevatedButton.styleFrom(
|
|
backgroundColor: Colors.orange,
|
|
),
|
|
child: const Text('Nettoyer'),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
|
|
if (confirm == true) {
|
|
await _performSelectiveCleanup(manual: true);
|
|
|
|
// Reset du cache des repositories après nettoyage
|
|
_resetAllRepositoriesCache();
|
|
|
|
// Forcer le rechargement complet de la page
|
|
if (kIsWeb) {
|
|
html.window.location.reload();
|
|
} else {
|
|
// Sur mobile, relancer l'initialisation normalement
|
|
_startInitialization();
|
|
}
|
|
}
|
|
},
|
|
icon: Icon(
|
|
Icons.cleaning_services,
|
|
size: 18,
|
|
color: _isCleaningCache ? Colors.grey : Colors.black87,
|
|
),
|
|
label: Text(
|
|
_isCleaningCache ? 'Nettoyage...' : 'Nettoyer le cache',
|
|
style: TextStyle(
|
|
color: _isCleaningCache ? Colors.grey : Colors.black87,
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
|
|
const Spacer(flex: 1),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
|
|
// Badge de version
|
|
if (_appVersion.isNotEmpty)
|
|
Positioned(
|
|
bottom: 16,
|
|
right: 16,
|
|
child: AnimatedOpacity(
|
|
opacity: _showButtons ? 0.7 : 0.5,
|
|
duration: const Duration(milliseconds: 500),
|
|
child: Container(
|
|
padding: const EdgeInsets.symmetric(
|
|
horizontal: 8,
|
|
vertical: 4,
|
|
),
|
|
decoration: BoxDecoration(
|
|
color: theme.colorScheme.primary.withOpacity(0.1),
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(
|
|
color: theme.colorScheme.primary,
|
|
width: 1,
|
|
),
|
|
),
|
|
child: Text(
|
|
'v$_appVersion',
|
|
style: theme.textTheme.bodySmall?.copyWith(
|
|
color: theme.colorScheme.primary,
|
|
fontSize: 10,
|
|
fontWeight: FontWeight.w500,
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|