refactor power

This commit is contained in:
2026-04-07 11:55:01 +02:00
parent 130780cbb8
commit f4d3ec4bca
12 changed files with 157 additions and 74 deletions

View File

@@ -0,0 +1,80 @@
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:equatable/equatable.dart';
import 'package:flux/core/enums/enums.dart';
import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
import 'package:supabase_flutter/supabase_flutter.dart';
part 'session_events.dart';
part 'session_state.dart';
class SessionBloc extends Bloc<SessionEvent, SessionState> {
final SupabaseClient _supabase = GetIt.I.get<SupabaseClient>();
StreamSubscription<AuthState>? _authSubscription;
SessionBloc() : super(const SessionState.unknown()) {
on<AppStarted>((event, emit) {
// 1. Controlla la sessione attuale al boot
final session = _supabase.auth.currentSession;
if (session != null) {
add(UserChanged(session.user.id));
} else {
add(UserChanged(null));
}
// 2. Ascolta i cambiamenti futuri (login, logout, token scaduto)
_authSubscription = _supabase.auth.onAuthStateChange.listen((data) {
final userId = data.session?.user.id;
add(UserChanged(userId));
});
});
on<UserChanged>((event, emit) async {
if (event.userId == null) {
emit(SessionState.unauthenticated());
return;
}
// 1. Controlla se l'utente ha una Company
final company = await _supabase
.from('company')
.select()
.eq('user_id', event.userId!)
.maybeSingle();
if (company == null) {
emit(SessionState.authenticatedNoCompany(event.userId!));
return;
}
// 2. Controlla i negozi
final stores = await _supabase
.from('store')
.select()
.eq('company_id', company['id']);
if (stores.isEmpty) {
emit(SessionState.authenticatedNoStore(event.userId!, company['id']));
return;
}
// 3. Tutto ok, gestiamo le SharedPreferences per il negozio
final prefs = GetIt.I.get<SharedPreferences>();
String? lastStoreId = prefs.getString(PrefKeys.lastStore.value);
// Se non c'è nelle SharedPreferences, prendi il primo della lista
if (lastStoreId == null || !stores.any((s) => s['id'] == lastStoreId)) {
lastStoreId = stores.first['id'];
await prefs.setString('last_store_id', lastStoreId!);
}
});
}
@override
Future<void> close() {
_authSubscription?.cancel();
return super.close();
}
}
class SharedPreferencesKeys {}