Files
geo/app/lib/presentation/auth/splash_page.dart
pierre 599b9fcda0 feat: Gestion des secteurs et migration v3.0.4+304
- Ajout système complet de gestion des secteurs avec contours géographiques
- Import des contours départementaux depuis GeoJSON
- API REST pour la gestion des secteurs (/api/sectors)
- Service de géolocalisation pour déterminer les secteurs
- Migration base de données avec tables x_departements_contours et sectors_adresses
- Interface Flutter pour visualisation et gestion des secteurs
- Ajout thème sombre dans l'application
- Corrections diverses et optimisations

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-08-07 11:01:45 +02:00

700 lines
26 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 'dart:async';
import 'dart:math' as math;
import 'package:flutter/foundation.dart' show kIsWeb;
import 'package:package_info_plus/package_info_plus.dart';
import 'package:url_launcher/url_launcher.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;
Future<void> _getAppVersion() async {
try {
final packageInfo = await PackageInfo.fromPlatform();
if (mounted) {
setState(() {
_appVersion = packageInfo.version;
});
}
} catch (e) {
debugPrint('Erreur lors de la récupération de la version: $e');
if (mounted) {
setState(() {
_appVersion = AppInfoService.fullVersion.split(' ').last;
});
}
}
}
@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('🚀 Début de l\'initialisation complète de l\'application...');
// Étape 0: 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) {
// Si les permissions ne sont pas accordées, on arrête tout
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;
});
}
// Étape 2: Initialisation Hive - 15 à 60% (étape la plus longue)
await HiveService.instance.initializeAndResetHive();
if (mounted) {
setState(() {
_statusMessage = "Configuration du stockage...";
_progress = 0.45;
});
}
await Future.delayed(const Duration(milliseconds: 300)); // Simulation du temps de traitement
if (mounted) {
setState(() {
_statusMessage = "Préparation des données...";
_progress = 0.60;
});
}
// Étape 3: Ouverture des Box - 60 à 80%
await HiveService.instance.ensureBoxesAreOpen();
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) {
final diagnostic = HiveService.instance.getDiagnostic();
debugPrint('❌ Diagnostic des Box: $diagnostic');
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;
});
// 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 {
setState(() {
_showButtons = true;
});
}
}
debugPrint('✅ Initialisation complète de l\'application terminée avec succès');
} catch (e) {
debugPrint('❌ Erreur lors de l\'initialisation: $e');
if (mounted) {
setState(() {
_statusMessage = "Erreur de chargement - Veuillez redémarrer l'application";
_progress = 1.0;
_isInitializing = false;
_showButtons = true;
});
}
}
}
/// Gère la redirection automatique après l'initialisation
Future<void> _handleAutoRedirect() async {
// Petit délai pour voir le message "Application prête !"
await Future.delayed(const Duration(milliseconds: 300));
if (!mounted) return;
final action = widget.action?.toLowerCase();
final type = widget.type?.toLowerCase();
debugPrint('🔄 Redirection automatique: action=$action, type=$type');
// 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));
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 && !_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 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,
),
),
),
),
),
],
),
);
}
}