diff --git a/lib/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart b/lib/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart index 7cda1a0..c21abad 100644 --- a/lib/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart +++ b/lib/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart @@ -1,7 +1,6 @@ import 'dart:async'; import 'package:equatable/equatable.dart'; -import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/features/operations/data/operations_repository.dart'; import 'package:flux/features/operations/models/operation_model.dart'; @@ -15,6 +14,8 @@ class DashboardStoreOperationListCubit final String? companyId; final String? storeId; StreamSubscription? _operationsSubscription; + Timer? _pollingTimer; + DashboardStoreOperationListCubit({ required this.companyId, required this.storeId, @@ -31,31 +32,37 @@ class DashboardStoreOperationListCubit // Primo caricamento _loadOperationsSilently(); - // Inizio ascolto campanello - try { - _operationsSubscription = _repository - .watchStoreOperations(storeId: storeId!, limit: 10) - .listen((_) { - // Quando il campanello suona (qualcosa è cambiato a DB), ricarichiamo! - _loadOperationsSilently(); - }); - } on Exception catch (e) { - debugPrint(e.toString()); - } + // 1. Ascolto notifiche locali di mutazione in memoria (reattività istantanea) + _operationsSubscription = _repository.onOperationsChanged.listen((_) { + _loadOperationsSilently(); + }); + + // 2. Polling programmato ogni 30 secondi per sincronizzazione di fondo + _pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) { + _loadOperationsSilently(); + }); } void stopListening() { _operationsSubscription?.cancel(); _operationsSubscription = null; + _pollingTimer?.cancel(); + _pollingTimer = null; + } + + void refresh() { + _loadOperationsSilently(); } void _loadOperationsSilently() async { try { + if (companyId == null || storeId == null) return; final paginatedData = await _repository.fetchPaginatedOperations( companyId: companyId!, storeId: storeId!, page: 1, itemsPerPage: 20, + onlyShowInDashboard: true, ); if (isClosed) return; emit( diff --git a/lib/features/master_data/providers/blocs/provider_form_cubit.dart b/lib/features/master_data/providers/blocs/provider_form_cubit.dart index a5e612d..af0aa0a 100644 --- a/lib/features/master_data/providers/blocs/provider_form_cubit.dart +++ b/lib/features/master_data/providers/blocs/provider_form_cubit.dart @@ -126,11 +126,61 @@ class ProviderFormCubit extends Cubit { } Future addLocationLocal(ProviderLocationModel location) async { + List currentLocations = List.from( + state.localLocations, + ); + + final bool shouldBeMain = location.isMain || currentLocations.isEmpty; + + if (shouldBeMain) { + currentLocations = currentLocations + .map((loc) => loc.copyWith(isMain: false)) + .toList(); + } + + currentLocations.add(location.copyWith(isMain: shouldBeMain)); + emit(state.copyWith(localLocations: currentLocations)); + } + + void updateLocationLocal(int index, ProviderLocationModel location) { final currentLocations = List.from( state.localLocations, ); - currentLocations.add(location); - emit(state.copyWith(localLocations: currentLocations)); + if (index < 0 || index >= currentLocations.length) return; + + bool shouldBeMain = location.isMain; + if (!shouldBeMain && currentLocations.length == 1) { + shouldBeMain = true; + } + + final List updatedList = []; + for (int i = 0; i < currentLocations.length; i++) { + if (i == index) { + updatedList.add(location.copyWith(isMain: shouldBeMain)); + } else { + updatedList.add( + shouldBeMain + ? currentLocations[i].copyWith(isMain: false) + : currentLocations[i], + ); + } + } + emit(state.copyWith(localLocations: updatedList)); + } + + void setMainLocationLocal(int index) { + final currentLocations = List.from( + state.localLocations, + ); + if (index < 0 || index >= currentLocations.length) return; + + final updatedList = currentLocations.asMap().entries.map((entry) { + final idx = entry.key; + final loc = entry.value; + return loc.copyWith(isMain: idx == index); + }).toList(); + + emit(state.copyWith(localLocations: updatedList)); } void removeLocationLocal(int index) { @@ -138,7 +188,13 @@ class ProviderFormCubit extends Cubit { state.localLocations, ); if (index >= 0 && index < currentLocations.length) { - currentLocations.removeAt(index); + final removedLoc = currentLocations.removeAt(index); + if (removedLoc.id != null && removedLoc.id!.isNotEmpty) { + _repository.deleteLocation(removedLoc.id!); + } + if (removedLoc.isMain && currentLocations.isNotEmpty) { + currentLocations[0] = currentLocations[0].copyWith(isMain: true); + } emit(state.copyWith(localLocations: currentLocations)); } } diff --git a/lib/features/master_data/providers/data/provider_repository.dart b/lib/features/master_data/providers/data/provider_repository.dart index ac986ff..af984f2 100644 --- a/lib/features/master_data/providers/data/provider_repository.dart +++ b/lib/features/master_data/providers/data/provider_repository.dart @@ -76,6 +76,12 @@ class ProviderRepository { // 4. Gestione Sedi (Locations) Future saveLocation(ProviderLocationModel location) async { + if (location.isMain && location.providerId.isNotEmpty) { + await _supabase + .from(Tables.providerLocations) + .update({'is_main': false}) + .eq('provider_id', location.providerId); + } await _supabase.from(Tables.providerLocations).upsert(location.toMap()); } diff --git a/lib/features/master_data/providers/ui/provider_form_screen.dart b/lib/features/master_data/providers/ui/provider_form_screen.dart index c7f713b..a0bea11 100644 --- a/lib/features/master_data/providers/ui/provider_form_screen.dart +++ b/lib/features/master_data/providers/ui/provider_form_screen.dart @@ -383,11 +383,47 @@ class _ProviderFormScreenState extends State { itemBuilder: (context, index) { final loc = state.localLocations[index]; return ListTile( - leading: Icon( - loc.isMain ? Icons.star : Icons.location_on, - color: loc.isMain ? Colors.amber : null, + onTap: () async { + final providerFormCubit = context.read(); + final res = await showDialog( + context: context, + builder: (context) => ProviderLocationDialog(initialLocation: loc), + ); + if (res != null) { + providerFormCubit.updateLocationLocal(index, res); + } + }, + leading: IconButton( + tooltip: loc.isMain ? 'Sede predefinita' : 'Imposta come predefinita', + icon: Icon( + loc.isMain ? Icons.star : Icons.star_border, + color: loc.isMain ? Colors.amber : Colors.grey, + ), + onPressed: () => context + .read() + .setMainLocationLocal(index), + ), + title: Row( + children: [ + Expanded(child: Text(loc.name)), + if (loc.isMain) + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: Colors.amber.withValues(alpha: 0.2), + borderRadius: BorderRadius.circular(4), + ), + child: const Text( + 'Predefinita', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.amber, + ), + ), + ), + ], ), - title: Text(loc.name), subtitle: Text( '${loc.address}, ${loc.city} (${loc.province})', ), diff --git a/lib/features/operations/blocs/operation_form_cubit.dart b/lib/features/operations/blocs/operation_form_cubit.dart index 846cba2..317d152 100644 --- a/lib/features/operations/blocs/operation_form_cubit.dart +++ b/lib/features/operations/blocs/operation_form_cubit.dart @@ -104,6 +104,7 @@ class OperationFormCubit extends Cubit { try { OperationModel operationToSave = state.operation.copyWith( status: targetStatus, + showInDashboard: true, ); if (operationToSave.reference.isEmpty) { if (operationToSave.customer != null && diff --git a/lib/features/operations/blocs/operation_list_cubit.dart b/lib/features/operations/blocs/operation_list_cubit.dart index ec2d775..6b5aec0 100644 --- a/lib/features/operations/blocs/operation_list_cubit.dart +++ b/lib/features/operations/blocs/operation_list_cubit.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; @@ -12,10 +14,19 @@ class OperationListCubit extends Cubit { final OperationsRepository _repository = GetIt.I(); final SessionCubit _sessionCubit = GetIt.I(); - OperationListCubit() : super(const OperationListState()); - + StreamSubscription? _operationsSubscription; int _fetchId = 0; + OperationListCubit() : super(const OperationListState()) { + _operationsSubscription = _repository.onOperationsChanged.listen((_) { + refreshCurrentPage(); + }); + } + + void refreshCurrentPage() { + loadSpecificPageDesktop(state.currentPage); + } + // 🥷 MOTORE 1: DESKTOP (Sostituisce la lista) Future loadSpecificPageDesktop(int page) async { final currentFetchId = ++_fetchId; @@ -124,4 +135,10 @@ class OperationListCubit extends Cubit { loadSpecificPageDesktop(1); } + + @override + Future close() { + _operationsSubscription?.cancel(); + return super.close(); + } } diff --git a/lib/features/operations/data/operations_repository.dart b/lib/features/operations/data/operations_repository.dart index fc67cf2..47a1627 100644 --- a/lib/features/operations/data/operations_repository.dart +++ b/lib/features/operations/data/operations_repository.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flux/core/enums_and_consts/consts.dart'; import 'package:flux/features/master_data/store/models/store_model.dart'; @@ -10,6 +11,17 @@ import 'package:supabase_flutter/supabase_flutter.dart'; class OperationsRepository { final SupabaseClient _supabase = sl(); + final StreamController _operationsChangedController = + StreamController.broadcast(); + + Stream get onOperationsChanged => _operationsChangedController.stream; + + void notifyOperationsChanged() { + if (!_operationsChangedController.isClosed) { + _operationsChangedController.add(null); + } + } + Future getOperationById(String id) async { try { final response = await _supabase @@ -45,6 +57,7 @@ class OperationsRepository { int itemsPerPage = 20, String? searchTerm, DateTimeRange? dateRange, + bool onlyShowInDashboard = false, }) async { try { // Calcoliamo il range di partenza e fine per Supabase @@ -69,6 +82,10 @@ class OperationsRepository { ''') .eq('company_id', companyId); + if (onlyShowInDashboard) { + query = query.eq('show_in_dashboard', true); + } + // Filtro Range Date if (dateRange != null) { query = query @@ -161,6 +178,7 @@ class OperationsRepository { staffId: createdById, companyId: currentStore.companyId, status: OperationStatus.success, + showInDashboard: false, ) .toMap(), ) @@ -169,6 +187,7 @@ class OperationsRepository { ${Tables.staffMembers}(*) ''') .single(); + notifyOperationsChanged(); return OperationModel.fromMap(res); } on Exception catch (e) { debugPrint('ERRORE CREAZIONE OPERAZIONE: $e'); @@ -179,6 +198,7 @@ class OperationsRepository { Future deleteOperation(String id) async { try { await _supabase.from(Tables.operations).delete().eq('id', id); + notifyOperationsChanged(); } catch (e) { debugPrint('ERRORE CANCELLAZIONE OPERAZIONE: $e'); throw Exception('Errore nella cancellazione dell\'operazione: $e'); @@ -225,6 +245,7 @@ class OperationsRepository { .from(Tables.operationDetails) .upsert(detailToSave.toMap()); } + notifyOperationsChanged(); } catch (e) { debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e'); throw Exception('Errore nel salvataggio dell\'operazione: $e'); diff --git a/lib/features/operations/models/operation_model.dart b/lib/features/operations/models/operation_model.dart index ff63812..3301781 100644 --- a/lib/features/operations/models/operation_model.dart +++ b/lib/features/operations/models/operation_model.dart @@ -126,6 +126,7 @@ class OperationModel extends Equatable { return OperationModel( id: null, createdAt: null, + showInDashboard: false, companyId: '', details: const [], ); diff --git a/pubspec.yaml b/pubspec.yaml index 19b17b2..fa59f13 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 1.3.4+50 +version: 1.3.5+51 environment: sdk: ^3.11.3