620 lines
23 KiB
Dart
620 lines
23 KiB
Dart
import 'dart:async';
|
|
import 'dart:io';
|
|
|
|
import 'package:firebase_core/firebase_core.dart';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
import 'package:flutter_dotenv/flutter_dotenv.dart';
|
|
import 'package:flux/core/services/notification_service.dart';
|
|
import 'package:flux/core/utils/version_check_service.dart';
|
|
import 'package:flux/features/auth/bloc/auth_cubit.dart';
|
|
import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart';
|
|
import 'package:flux/features/notes/blocs/notes_cubit.dart';
|
|
import 'package:flux/features/operations/blocs/operation_list_cubit.dart';
|
|
import 'package:flux/features/settings/blocs/settings_cubit.dart';
|
|
import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart';
|
|
import 'package:flux/features/tracking/blocs/tracking_cubit.dart';
|
|
import 'package:flux/firebase_options.dart';
|
|
import 'package:flux/l10n/app_localizations.dart';
|
|
import 'package:flux/service_locator.dart';
|
|
import 'package:get_it/get_it.dart';
|
|
import 'package:go_router/go_router.dart';
|
|
import 'package:supabase_flutter/supabase_flutter.dart';
|
|
import 'package:flux/core/blocs/session/session_cubit.dart';
|
|
import 'package:flux/core/routes/app_router.dart';
|
|
import 'package:flux/core/theme/theme.dart';
|
|
import 'package:flux/core/theme/bloc/theme_bloc.dart';
|
|
import 'package:flux/features/customers/blocs/customers_list_cubit.dart';
|
|
import 'package:flux/features/master_data/products/blocs/product_cubit.dart';
|
|
import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart';
|
|
import 'package:flux/features/master_data/store/bloc/store_cubit.dart';
|
|
import 'package:flutter_web_plugins/url_strategy.dart';
|
|
import 'package:universal_html/html.dart' as html;
|
|
import 'package:url_launcher/url_launcher.dart';
|
|
import 'package:flux/core/utils/auto_update_service.dart';
|
|
|
|
String? initialRecoveryFragment;
|
|
void main() async {
|
|
WidgetsFlutterBinding.ensureInitialized();
|
|
|
|
// Scudo di Sicurezza Globale: Previene crash dell'app per eccezioni asincrone di rete/WebSocket non gestite
|
|
FlutterError.onError = (FlutterErrorDetails details) {
|
|
FlutterError.presentError(details);
|
|
debugPrint('FlutterError caught: ${details.exception}');
|
|
};
|
|
|
|
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
|
|
debugPrint('PlatformDispatcher error caught: $error');
|
|
return true; // Contrassegna l'errore come gestito ed evita il crash dell'app
|
|
};
|
|
|
|
try {
|
|
await dotenv.load(fileName: ".env");
|
|
} catch (e) {
|
|
debugPrint('⚠️ Impossibile caricare il file .env: $e');
|
|
}
|
|
await init();
|
|
final initialUri = Uri.base;
|
|
if (initialUri.fragment.contains('access_token=')) {
|
|
initialRecoveryFragment = initialUri.fragment;
|
|
}
|
|
// RIMUOVE IL CARATTERE # DAGLI URL WEB!
|
|
usePathUrlStrategy();
|
|
// Lo Scudo Ninja: Inizializziamo Firebase SOLO sulle piattaforme supportate
|
|
if (kIsWeb || Platform.isAndroid || Platform.isIOS || Platform.isMacOS) {
|
|
try {
|
|
await Firebase.initializeApp(
|
|
options: DefaultFirebaseOptions.currentPlatform,
|
|
);
|
|
await setupInteractedMessage();
|
|
} catch (e) {
|
|
debugPrint('Errore inizializzazione Firebase: $e');
|
|
}
|
|
}
|
|
runApp(
|
|
MultiBlocProvider(
|
|
providers: [
|
|
BlocProvider<AuthCubit>(create: (_) => sl<AuthCubit>()),
|
|
BlocProvider<ThemeBloc>(
|
|
create: (_) => sl<ThemeBloc>()..add(LoadThemeEvent()),
|
|
),
|
|
// Il Vigile Urbano viene inizializzato!
|
|
BlocProvider<SessionCubit>(create: (_) => sl<SessionCubit>()),
|
|
|
|
// Cubit delle feature
|
|
BlocProvider<StoreCubit>(create: (_) => sl<StoreCubit>()),
|
|
BlocProvider<CustomersListCubit>(
|
|
create: (_) => sl<CustomersListCubit>(),
|
|
),
|
|
BlocProvider<ProductsCubit>(create: (_) => sl<ProductsCubit>()),
|
|
BlocProvider<StaffCubit>(
|
|
create: (_) {
|
|
final cubit = sl<StaffCubit>();
|
|
final storeId = sl<SessionCubit>().state.currentStore?.id;
|
|
if (storeId != null) {
|
|
cubit.loadStaffForStore(storeId);
|
|
}
|
|
return cubit;
|
|
},
|
|
),
|
|
BlocProvider<OperationListCubit>(
|
|
create: (_) => sl<OperationListCubit>(),
|
|
),
|
|
BlocProvider<ProviderListCubit>(create: (_) => sl<ProviderListCubit>()),
|
|
BlocProvider<SettingsCubit>(create: (_) => sl<SettingsCubit>()),
|
|
BlocProvider<TicketListCubit>(create: (_) => sl<TicketListCubit>()),
|
|
BlocProvider<TrackingCubit>(create: (_) => sl<TrackingCubit>()),
|
|
BlocProvider<NotesCubit>(create: (_) => sl<NotesCubit>()),
|
|
],
|
|
child: const FluxApp(),
|
|
),
|
|
);
|
|
}
|
|
|
|
class FluxApp extends StatefulWidget {
|
|
const FluxApp({super.key});
|
|
|
|
@override
|
|
State<FluxApp> createState() => _FluxAppState();
|
|
}
|
|
|
|
class _FluxAppState extends State<FluxApp> {
|
|
late final GoRouter _router;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// Creiamo il router passandogli il Cubit per i redirect
|
|
_router = AppRouter.createRouter(context.read<SessionCubit>());
|
|
sl<SessionCubit>().setIsMobileDevice(isMobileDevice(context));
|
|
}
|
|
|
|
bool isMobileDevice(BuildContext context) {
|
|
if (kIsWeb) {
|
|
return false; // Il web non lo consideriamo "mobile nativo" per i deep link
|
|
}
|
|
return Platform.isAndroid || Platform.isIOS;
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
return BlocConsumer<SessionCubit, SessionState>(
|
|
listenWhen: (previous, current) =>
|
|
previous.status != SessionStatus.authenticated &&
|
|
current.status == SessionStatus.authenticated,
|
|
listener: (context, state) {
|
|
context.read<StoreCubit>().loadStores();
|
|
context.read<StaffCubit>().loadAllStaff();
|
|
},
|
|
builder: (context, sessionState) {
|
|
if (sessionState.status == SessionStatus.initial) {
|
|
return _buildLoadingScreen();
|
|
}
|
|
|
|
if (sessionState.status == SessionStatus.error) {
|
|
return _buildSessionErrorScreen(
|
|
state: sessionState,
|
|
context: context,
|
|
);
|
|
}
|
|
|
|
return BlocBuilder<ThemeBloc, ThemeState>(
|
|
builder: (context, themeState) {
|
|
return MaterialApp.router(
|
|
title: 'FLUX Gestionale',
|
|
debugShowCheckedModeBanner: false,
|
|
theme: fluxLightTheme,
|
|
darkTheme: fluxDarkTheme,
|
|
themeMode: themeState.currentTheme.themeMode,
|
|
routerConfig: _router,
|
|
localizationsDelegates: AppLocalizations.localizationsDelegates,
|
|
supportedLocales: AppLocalizations.supportedLocales,
|
|
locale: const Locale('it'),
|
|
|
|
// 🥷 ECCO LA MAGIA: Avvolgiamo tutta l'app nel nostro checker!
|
|
builder: (context, child) {
|
|
return GlobalUpdateChecker(child: child!);
|
|
},
|
|
);
|
|
},
|
|
);
|
|
},
|
|
);
|
|
}
|
|
|
|
Widget _buildLoadingScreen() {
|
|
return MaterialApp(
|
|
debugShowCheckedModeBanner: false,
|
|
home: Scaffold(
|
|
body: Center(
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
const Icon(Icons.bolt, size: 64, color: Colors.blue),
|
|
const SizedBox(height: 24),
|
|
const CircularProgressIndicator(),
|
|
const SizedBox(height: 16),
|
|
const Text(
|
|
"Inizializzazione sessione...",
|
|
style: TextStyle(
|
|
fontWeight: FontWeight.bold,
|
|
color: Colors.grey,
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
}
|
|
|
|
Widget _buildSessionErrorScreen({
|
|
required SessionState state,
|
|
required BuildContext context,
|
|
}) {
|
|
return MaterialApp(
|
|
home: Scaffold(
|
|
body: Center(
|
|
child: Padding(
|
|
padding: const EdgeInsets.all(24.0),
|
|
child: Column(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
const Icon(Icons.wifi_off_rounded, size: 64, color: Colors.grey),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
state.errorMessage ?? 'Errore nella connessione',
|
|
textAlign: TextAlign.center,
|
|
style: const TextStyle(fontSize: 16),
|
|
),
|
|
const SizedBox(height: 24),
|
|
ElevatedButton.icon(
|
|
onPressed: () {
|
|
// Il ninja riprova a lanciare l'inizializzazione
|
|
context.read<SessionCubit>().initializeSession();
|
|
},
|
|
icon: const Icon(Icons.refresh),
|
|
label: const Text("Riprova a connetterti"),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
);
|
|
}
|
|
|
|
// --- IL WIDGET GUARDIANO DEGLI AGGIORNAMENTI ---
|
|
class GlobalUpdateChecker extends StatefulWidget {
|
|
final Widget child;
|
|
const GlobalUpdateChecker({super.key, required this.child});
|
|
|
|
@override
|
|
State<GlobalUpdateChecker> createState() => _GlobalUpdateCheckerState();
|
|
}
|
|
|
|
class _GlobalUpdateCheckerState extends State<GlobalUpdateChecker>
|
|
with WidgetsBindingObserver {
|
|
UpdateInfo? _updateInfo;
|
|
bool _isDismissed = false;
|
|
String? _dismissedVersion;
|
|
StreamSubscription? _versionSubscription;
|
|
bool _isUpdating = false;
|
|
double _downloadProgress = 0.0;
|
|
String _statusMessage = "";
|
|
String? _errorMessage;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
// 🥷 1. Registriamo questo widget per ascoltare i cicli vitali dell'app
|
|
WidgetsBinding.instance.addObserver(this);
|
|
_startRealtimeVersionCheck();
|
|
}
|
|
|
|
@override
|
|
void dispose() {
|
|
// 🥷 2. Rimuoviamo l'observer quando il widget muore (mai, in questo caso, ma è buona norma)
|
|
WidgetsBinding.instance.removeObserver(this);
|
|
_stopRealtimeVersionCheck();
|
|
super.dispose();
|
|
}
|
|
|
|
// 🥷 3. IL VERO GESTORE DEL CICLO VITALE
|
|
@override
|
|
void didChangeAppLifecycleState(AppLifecycleState state) {
|
|
super.didChangeAppLifecycleState(state);
|
|
|
|
if (state == AppLifecycleState.resumed) {
|
|
// L'app è tornata attiva: riaccendiamo il radar
|
|
_startRealtimeVersionCheck();
|
|
} else if (state == AppLifecycleState.paused ||
|
|
state == AppLifecycleState.hidden) {
|
|
// L'app è andata in background: spegniamo il socket per evitare crash
|
|
_stopRealtimeVersionCheck();
|
|
}
|
|
}
|
|
|
|
void _startRealtimeVersionCheck() {
|
|
// Sicurezza: cancelliamo eventuali vecchi abbonamenti rimasti appesi
|
|
_stopRealtimeVersionCheck();
|
|
|
|
// Facciamo un check immediato non appena rientriamo in app
|
|
_checkVersion();
|
|
|
|
// Riapriamo il rubinetto di Supabase
|
|
_versionSubscription = GetIt.I<SupabaseClient>()
|
|
.from('app_config')
|
|
.stream(primaryKey: ['id'])
|
|
.listen(
|
|
(_) {
|
|
_checkVersion();
|
|
},
|
|
onError: (error, stackTrace) {
|
|
debugPrint('Realtime version check stream error: $error');
|
|
},
|
|
);
|
|
}
|
|
|
|
void _stopRealtimeVersionCheck() {
|
|
// Chiudiamo gentilmente il socket
|
|
_versionSubscription?.cancel();
|
|
_versionSubscription = null;
|
|
}
|
|
|
|
Future<void> _checkVersion() async {
|
|
final updateInfo = await VersionCheckService().checkUpdate();
|
|
|
|
if (mounted) {
|
|
setState(() {
|
|
_updateInfo = updateInfo;
|
|
// Se arriva una versione diversa da quella già rimandata, azzeriamo il dismiss
|
|
if (updateInfo != null &&
|
|
updateInfo.latestVersion != _dismissedVersion) {
|
|
_isDismissed = false;
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
Future<void> _startAutoUpdate() async {
|
|
final updateUrl = _updateInfo?.downloadUrl;
|
|
if (updateUrl == null || updateUrl.isEmpty) return;
|
|
|
|
setState(() {
|
|
_isUpdating = true;
|
|
_errorMessage = null;
|
|
_downloadProgress = 0.0;
|
|
_statusMessage = "Avvio aggiornamento in corso...";
|
|
});
|
|
|
|
try {
|
|
await AutoUpdateService.downloadAndApplyUpdate(
|
|
downloadUrl: updateUrl,
|
|
onProgress: (progress, status) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_downloadProgress = progress;
|
|
_statusMessage = status;
|
|
});
|
|
}
|
|
},
|
|
);
|
|
} catch (e) {
|
|
if (mounted) {
|
|
setState(() {
|
|
_isUpdating = false;
|
|
_errorMessage = "Errore durante l'aggiornamento automatico: $e";
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final updateInfo = _updateInfo;
|
|
final showOverlay = updateInfo != null &&
|
|
updateInfo.hasUpdate &&
|
|
(updateInfo.isMandatory || !_isDismissed);
|
|
|
|
if (!showOverlay) return widget.child;
|
|
|
|
final isMandatory = updateInfo.isMandatory;
|
|
|
|
return Stack(
|
|
children: [
|
|
widget.child,
|
|
Positioned.fill(
|
|
child: Container(
|
|
color: Colors.black.withValues(alpha: 0.85),
|
|
child: Center(
|
|
child: Material(
|
|
color: Colors.transparent,
|
|
child: Container(
|
|
margin: const EdgeInsets.all(24),
|
|
padding: const EdgeInsets.all(24),
|
|
constraints: const BoxConstraints(maxWidth: 440),
|
|
decoration: BoxDecoration(
|
|
color: Theme.of(context).scaffoldBackgroundColor,
|
|
borderRadius: BorderRadius.circular(16),
|
|
boxShadow: const [
|
|
BoxShadow(
|
|
color: Colors.black54,
|
|
blurRadius: 20,
|
|
offset: Offset(0, 10),
|
|
),
|
|
],
|
|
),
|
|
child: Column(
|
|
mainAxisSize: MainAxisSize.min,
|
|
children: [
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.center,
|
|
children: [
|
|
Icon(
|
|
isMandatory
|
|
? Icons.warning_amber_rounded
|
|
: (kIsWeb ? Icons.cached : Icons.system_update),
|
|
color:
|
|
isMandatory ? Colors.amber[700] : Colors.blue,
|
|
size: 32,
|
|
),
|
|
const SizedBox(width: 12),
|
|
Expanded(
|
|
child: Text(
|
|
isMandatory
|
|
? "Aggiornamento Obbligatorio"
|
|
: (kIsWeb
|
|
? "Aggiornamento Disponibile"
|
|
: "Nuova Versione Disponibile"),
|
|
style: Theme.of(context)
|
|
.textTheme
|
|
.titleLarge
|
|
?.copyWith(fontWeight: FontWeight.bold),
|
|
),
|
|
),
|
|
if (!isMandatory && !_isUpdating)
|
|
IconButton(
|
|
icon: const Icon(Icons.close),
|
|
tooltip: "Chiudi e rimanda",
|
|
onPressed: () {
|
|
setState(() {
|
|
_isDismissed = true;
|
|
_dismissedVersion =
|
|
updateInfo.latestVersion;
|
|
});
|
|
},
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 16),
|
|
Text(
|
|
kIsWeb
|
|
? "È stata rilasciata una nuova versione dell'applicazione (${updateInfo.latestVersion}). Ricarica la pagina per scaricare il nuovo codice."
|
|
: (isMandatory
|
|
? "La versione attuale non è più supportata (minima richiesta: ${updateInfo.minVersion}). È necessario aggiornare all'ultima versione (${updateInfo.latestVersion}) per continuare a lavorare."
|
|
: "È disponibile la nuova versione ${updateInfo.latestVersion}. Puoi aggiornare subito oppure rimandare."),
|
|
textAlign: TextAlign.center,
|
|
style: const TextStyle(fontSize: 15),
|
|
),
|
|
const SizedBox(height: 24),
|
|
if (_errorMessage != null) ...[
|
|
Container(
|
|
padding: const EdgeInsets.all(12),
|
|
decoration: BoxDecoration(
|
|
color: Colors.red.withValues(alpha: 0.1),
|
|
borderRadius: BorderRadius.circular(8),
|
|
border: Border.all(
|
|
color: Colors.red.withValues(alpha: 0.3),
|
|
),
|
|
),
|
|
child: Text(
|
|
_errorMessage!,
|
|
style: const TextStyle(
|
|
color: Colors.red,
|
|
fontSize: 13,
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
),
|
|
const SizedBox(height: 16),
|
|
],
|
|
if (_isUpdating) ...[
|
|
ClipRRect(
|
|
borderRadius: BorderRadius.circular(8),
|
|
child: LinearProgressIndicator(
|
|
value: _downloadProgress > 0
|
|
? _downloadProgress
|
|
: null,
|
|
minHeight: 10,
|
|
),
|
|
),
|
|
const SizedBox(height: 12),
|
|
Text(
|
|
_statusMessage,
|
|
style: TextStyle(
|
|
fontSize: 13,
|
|
color: Theme.of(context)
|
|
.colorScheme
|
|
.onSurface
|
|
.withValues(alpha: 0.7),
|
|
),
|
|
textAlign: TextAlign.center,
|
|
),
|
|
] else if (kIsWeb) ...[
|
|
FilledButton.icon(
|
|
icon: const Icon(Icons.refresh),
|
|
label: const Text("RICARICA ORA"),
|
|
style: FilledButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 50),
|
|
),
|
|
onPressed: () {
|
|
// Hard reload aggirando la cache!
|
|
html.window.location.reload();
|
|
},
|
|
),
|
|
if (!isMandatory) ...[
|
|
const SizedBox(height: 10),
|
|
OutlinedButton(
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 44),
|
|
),
|
|
onPressed: () {
|
|
setState(() {
|
|
_isDismissed = true;
|
|
_dismissedVersion =
|
|
updateInfo.latestVersion;
|
|
});
|
|
},
|
|
child: const Text("PIÙ TARDI"),
|
|
),
|
|
],
|
|
] else if (AutoUpdateService.isAutoUpdateSupported) ...[
|
|
FilledButton.icon(
|
|
icon: const Icon(Icons.system_update_alt),
|
|
label: const Text("AGGIORNA ORA"),
|
|
style: FilledButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 50),
|
|
backgroundColor: Colors.blue,
|
|
),
|
|
onPressed: _startAutoUpdate,
|
|
),
|
|
if (!isMandatory) ...[
|
|
const SizedBox(height: 10),
|
|
OutlinedButton(
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 44),
|
|
),
|
|
onPressed: () {
|
|
setState(() {
|
|
_isDismissed = true;
|
|
_dismissedVersion =
|
|
updateInfo.latestVersion;
|
|
});
|
|
},
|
|
child: const Text("PIÙ TARDI"),
|
|
),
|
|
],
|
|
] else ...[
|
|
FilledButton.icon(
|
|
icon: const Icon(Icons.download),
|
|
label: const Text("SCARICA AGGIORNAMENTO"),
|
|
style: FilledButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 50),
|
|
backgroundColor: Colors.blue,
|
|
),
|
|
onPressed: () async {
|
|
final url = Uri.parse(updateInfo.downloadUrl);
|
|
await launchUrl(
|
|
url,
|
|
mode: LaunchMode.externalApplication,
|
|
);
|
|
},
|
|
),
|
|
if (!isMandatory) ...[
|
|
const SizedBox(height: 10),
|
|
OutlinedButton(
|
|
style: OutlinedButton.styleFrom(
|
|
minimumSize: const Size(double.infinity, 44),
|
|
),
|
|
onPressed: () {
|
|
setState(() {
|
|
_isDismissed = true;
|
|
_dismissedVersion =
|
|
updateInfo.latestVersion;
|
|
});
|
|
},
|
|
child: const Text("PIÙ TARDI"),
|
|
),
|
|
],
|
|
],
|
|
if (!_isUpdating &&
|
|
AutoUpdateService.isAutoUpdateSupported &&
|
|
_errorMessage != null) ...[
|
|
const SizedBox(height: 10),
|
|
TextButton.icon(
|
|
icon: const Icon(Icons.open_in_browser, size: 16),
|
|
label: const Text("Scarica manualmente dal browser"),
|
|
onPressed: () async {
|
|
final url = Uri.parse(updateInfo.downloadUrl);
|
|
await launchUrl(
|
|
url,
|
|
mode: LaunchMode.externalApplication,
|
|
);
|
|
},
|
|
),
|
|
],
|
|
],
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
}
|