From 2c02dfcf8ba81da7dd95be4d56e89e4f3c044d3b Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Fri, 9 Oct 2026 12:02:48 +0200 Subject: [PATCH] sistemati bug --- .env.example | 2 + lib/core/routes/app_router.dart | 7 + .../shared_forms/attachments_section.dart | 165 +++- .../dashboard_daily_ricontatti_cubit.dart | 237 +++++ .../dashboard_daily_ricontatti_state.dart | 64 ++ .../staff_daily_ricontatti_summary.dart | 73 ++ .../ui/dashboard_daily_ricontatti_card.dart | 869 ++++++++++++++++++ .../dashboard_store_ticket_list_cubit.dart | 12 + lib/features/home/ui/home_screen.dart | 17 + .../data/operations_repository.dart | 55 ++ .../tickets/data/ticket_repository.dart | 17 +- lib/main.dart | 18 +- .../dashboard_daily_ricontatti_test.dart | 125 +++ 13 files changed, 1645 insertions(+), 16 deletions(-) create mode 100644 .env.example create mode 100644 lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart create mode 100644 lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart create mode 100644 lib/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart create mode 100644 lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart create mode 100644 test/features/home/dashboard_daily_ricontatti/dashboard_daily_ricontatti_test.dart diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..47a4d45 --- /dev/null +++ b/.env.example @@ -0,0 +1,2 @@ +SUPABASE_URL=https://pvqpjloswwvtfoxbkfbh.supabase.co +SUPABASE_PUBLISHABLE_KEY=sb_publishable_mcuEyVYGNSvRJQZgXlpLcA_SAJyyplj diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 9efcef0..f0936f5 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -18,6 +18,7 @@ import 'package:flux/features/customers/models/customer_model.dart'; import 'package:flux/features/customers/ui/customer_detail_screen.dart'; import 'package:flux/features/customers/ui/customer_form_screen.dart'; import 'package:flux/features/customers/ui/customers_list_screen.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart'; import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart'; import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart'; import 'package:flux/features/home/dashboard_store_operation_list/bloc/dashboard_store_operation_list_cubit.dart'; @@ -204,6 +205,12 @@ class AppRouter { storeId: sessionCubit.state.currentStore?.id, ), ), + BlocProvider( + create: (context) => DashboardDailyRicontattiCubit( + companyId: sessionCubit.state.company?.id, + storeId: sessionCubit.state.currentStore?.id, + ), + ), ], child: const HomeScreen(), ); diff --git a/lib/core/widgets/shared_forms/attachments_section.dart b/lib/core/widgets/shared_forms/attachments_section.dart index aee991c..5ad4197 100644 --- a/lib/core/widgets/shared_forms/attachments_section.dart +++ b/lib/core/widgets/shared_forms/attachments_section.dart @@ -787,12 +787,56 @@ class _SharedAttachmentsSectionState extends State { ], const SizedBox(width: 12), - // Loader di upload + // Indicatori di stato nell'action bar if (state.status == AttachmentsStatus.uploading) - const SizedBox( - width: 24, - height: 24, - child: CircularProgressIndicator(strokeWidth: 2), + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const SizedBox( + width: 16, + height: 16, + child: CircularProgressIndicator(strokeWidth: 2), + ), + const SizedBox(width: 8), + Text( + 'Caricamento file...', + style: TextStyle( + fontSize: 13, + color: theme.colorScheme.primary, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ) + else if (state.status == AttachmentsStatus.loading && + allFiles.isNotEmpty) + Padding( + padding: const EdgeInsets.symmetric(horizontal: 8.0), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator( + strokeWidth: 2, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(width: 6), + Text( + 'Aggiornamento...', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.primary, + fontStyle: FontStyle.italic, + ), + ), + ], + ), ), // Azioni visibili SOLO se c'è una selezione! @@ -880,8 +924,115 @@ class _SharedAttachmentsSectionState extends State { ), const SizedBox(height: 16), - // 3. GRIGLIA DEI FILE - if (allFiles.isEmpty) + // 3. GRIGLIA DEI FILE O STATO DI CARICAMENTO + if (state.status == AttachmentsStatus.loading || + (state.status == AttachmentsStatus.initial && + widget.parentId != null && + widget.parentId!.isNotEmpty)) + Container( + width: double.infinity, + padding: const EdgeInsets.symmetric( + vertical: 36, + horizontal: 24, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues( + alpha: 0.35, + ), + border: Border.all( + color: theme.dividerColor.withValues(alpha: 0.6), + style: BorderStyle.solid, + ), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + SizedBox( + width: 32, + height: 32, + child: CircularProgressIndicator( + strokeWidth: 3, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(height: 16), + Text( + 'Caricamento allegati in corso...', + style: TextStyle( + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurface, + fontSize: 15, + ), + ), + const SizedBox(height: 6), + Text( + 'Sincronizzazione documenti in archivio', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant.withValues( + alpha: 0.8, + ), + ), + ), + ], + ), + ) + else if (state.status == AttachmentsStatus.failure && + allFiles.isEmpty) + Container( + width: double.infinity, + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: theme.colorScheme.errorContainer.withValues( + alpha: 0.25, + ), + border: Border.all( + color: theme.colorScheme.error.withValues(alpha: 0.5), + ), + borderRadius: BorderRadius.circular(12), + ), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.error_outline, + size: 36, + color: theme.colorScheme.error, + ), + const SizedBox(height: 8), + Text( + 'Errore durante il recupero degli allegati', + style: TextStyle( + fontWeight: FontWeight.bold, + color: theme.colorScheme.error, + ), + ), + if (state.error != null) ...[ + const SizedBox(height: 4), + Text( + state.error!, + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.error, + ), + textAlign: TextAlign.center, + ), + ], + const SizedBox(height: 12), + TextButton.icon( + onPressed: () { + context.read().add( + LoadAttachmentsEvent(parentId: widget.parentId), + ); + }, + icon: const Icon(Icons.refresh), + label: const Text('Riprova'), + ), + ], + ), + ) + else if (allFiles.isEmpty) Container( width: double.infinity, padding: const EdgeInsets.all(32), diff --git a/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart b/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart new file mode 100644 index 0000000..658b55f --- /dev/null +++ b/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart @@ -0,0 +1,237 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart'; +import 'package:flux/features/master_data/staff/data/staff_repository.dart'; +import 'package:flux/features/operations/data/operations_repository.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:get_it/get_it.dart'; + +import 'dashboard_daily_ricontatti_state.dart'; + +class DashboardDailyRicontattiCubit extends Cubit { + final OperationsRepository _operationsRepository; + final StaffRepository _staffRepository; + + String? companyId; + String? storeId; + + StreamSubscription? _operationsSubscription; + Timer? _pollingTimer; + + DashboardDailyRicontattiCubit({ + this.companyId, + this.storeId, + OperationsRepository? operationsRepository, + StaffRepository? staffRepository, + }) : _operationsRepository = + operationsRepository ?? GetIt.I.get(), + _staffRepository = staffRepository ?? GetIt.I.get(), + super( + DashboardDailyRicontattiState( + date: DateTime.now(), + ), + ); + + void updateContext({ + String? newCompanyId, + String? newStoreId, + }) { + bool changed = false; + if (newCompanyId != null && newCompanyId != companyId) { + companyId = newCompanyId; + changed = true; + } + if (newStoreId != null && newStoreId != storeId) { + storeId = newStoreId; + changed = true; + } + + if (changed) { + refresh(); + } + } + + void startListening() { + emit(state.copyWith(status: DashboardDailyRicontattiStatus.loading)); + stopListening(); + + _loadDailyRicontattiSilently(); + + // 1. Ascolto notifiche di creazione/modifica operazioni in real-time + _operationsSubscription = + _operationsRepository.onOperationsChanged.listen((_) { + _loadDailyRicontattiSilently(); + }); + + // 2. Polling periodico ogni 30 secondi + _pollingTimer = Timer.periodic(const Duration(seconds: 30), (_) { + _loadDailyRicontattiSilently(); + }); + } + + void stopListening() { + _operationsSubscription?.cancel(); + _operationsSubscription = null; + _pollingTimer?.cancel(); + _pollingTimer = null; + } + + void refresh() { + _loadDailyRicontattiSilently(); + } + + Future _loadDailyRicontattiSilently() async { + if (companyId == null || storeId == null) { + if (!isClosed) { + emit( + state.copyWith( + status: DashboardDailyRicontattiStatus.initial, + summaries: [], + totalRicontattiToday: 0, + totalRicontattiMonth: 0, + ), + ); + } + return; + } + + try { + final now = DateTime.now(); + final todayStart = DateTime(now.year, now.month, now.day, 0, 0, 0); + final todayEnd = DateTime(now.year, now.month, now.day, 23, 59, 59, 999); + + // 1. Recupero staff del negozio + final allStaff = await _staffRepository.getStaffMembers( + companyId!, + storeId: storeId, + ); + + final activeStaff = allStaff.where((s) => s.isActive).toList(); + + // 2. Recupero conteggi mensili per addetto del negozio + final monthlyCountsByStaff = + await _operationsRepository.getMonthlyRicontattiCountsByStaff( + companyId: companyId!, + storeId: storeId!, + month: now, + ); + + int grandMonthTotal = 0; + for (final mVal in monthlyCountsByStaff.values) { + grandMonthTotal += mVal; + } + + // 3. Recupero operazioni create oggi nel negozio + final paginatedOps = await _operationsRepository.fetchPaginatedOperations( + companyId: companyId!, + storeId: storeId, + dateRange: DateTimeRange(start: todayStart, end: todayEnd), + page: 1, + itemsPerPage: 150, + onlyShowInDashboard: false, + ); + + // 4. Filtro per tipo Ricontatto + final ricontattiOps = paginatedOps.operations.where((op) { + return op.details.any((d) => d.type == OperationType.ricontatto); + }).toList(); + + // 5. Raggruppamento per addetto + final List summaries = []; + final Set processedStaffIds = {}; + int grandTotal = 0; + + for (final staff in activeStaff) { + final staffId = staff.id ?? ''; + processedStaffIds.add(staffId); + + final staffOps = ricontattiOps.where((op) => op.staffId == staffId).toList(); + + int staffCount = 0; + for (final op in staffOps) { + final countInOp = op.details.where((d) => d.type == OperationType.ricontatto).length; + staffCount += countInOp > 0 ? countInOp : 1; + } + + grandTotal += staffCount; + final staffMonthCount = monthlyCountsByStaff[staffId] ?? 0; + + summaries.add( + StaffDailyRicontattiSummary( + staffId: staffId, + staffName: staff.name, + jobTitle: staff.jobTitle, + systemRole: staff.systemRole, + count: staffCount, + monthCount: staffMonthCount, + operations: staffOps, + ), + ); + } + + // 6. Verifica se ci sono operazioni attribuite a staff non presente nella lista + for (final op in ricontattiOps) { + final opStaffId = op.staffId ?? ''; + if (opStaffId.isNotEmpty && !processedStaffIds.contains(opStaffId)) { + processedStaffIds.add(opStaffId); + final staffOps = ricontattiOps.where((o) => o.staffId == opStaffId).toList(); + + int staffCount = 0; + for (final o in staffOps) { + final countInOp = o.details.where((d) => d.type == OperationType.ricontatto).length; + staffCount += countInOp > 0 ? countInOp : 1; + } + grandTotal += staffCount; + final staffMonthCount = monthlyCountsByStaff[opStaffId] ?? 0; + + summaries.add( + StaffDailyRicontattiSummary( + staffId: opStaffId, + staffName: op.staffDisplayName ?? 'Operatore', + count: staffCount, + monthCount: staffMonthCount, + operations: staffOps, + ), + ); + } + } + + // 7. Ordinamento: per numero di ricontatti oggi decrescente, poi per mese decrescente, poi per nome + summaries.sort((a, b) { + final countCmp = b.count.compareTo(a.count); + if (countCmp != 0) return countCmp; + final monthCmp = b.monthCount.compareTo(a.monthCount); + if (monthCmp != 0) return monthCmp; + return a.staffName.toLowerCase().compareTo(b.staffName.toLowerCase()); + }); + + if (isClosed) return; + + emit( + state.copyWith( + status: DashboardDailyRicontattiStatus.success, + summaries: summaries, + totalRicontattiToday: grandTotal, + totalRicontattiMonth: grandMonthTotal, + date: now, + errorMessage: null, + ), + ); + } catch (e) { + if (isClosed) return; + emit( + state.copyWith( + status: DashboardDailyRicontattiStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + + @override + Future close() { + stopListening(); + return super.close(); + } +} diff --git a/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart b/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart new file mode 100644 index 0000000..a2bdb99 --- /dev/null +++ b/lib/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart @@ -0,0 +1,64 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart'; + +enum DashboardDailyRicontattiStatus { initial, loading, success, failure } + +class DashboardDailyRicontattiState extends Equatable { + final DashboardDailyRicontattiStatus status; + final List summaries; + final int totalRicontattiToday; + final int totalRicontattiMonth; + final DateTime date; + final String? errorMessage; + + const DashboardDailyRicontattiState({ + this.status = DashboardDailyRicontattiStatus.initial, + this.summaries = const [], + this.totalRicontattiToday = 0, + this.totalRicontattiMonth = 0, + required this.date, + this.errorMessage, + }); + + /// Numero di addetti che hanno raggiunto l'obiettivo (>= 2) + int get staffWithGoal => summaries.where((s) => s.hasReachedGoal).length; + + /// Numero di addetti che hanno registrato almeno 1 ricontatto (= 1) + int get staffWithOne => summaries.where((s) => s.hasStarted).length; + + /// Numero di addetti a 0 + int get staffAtZero => summaries.where((s) => s.isZero).length; + + /// Totale addetti monitorati + int get activeStaffCount => summaries.length; + + DashboardDailyRicontattiState copyWith({ + DashboardDailyRicontattiStatus? status, + List? summaries, + int? totalRicontattiToday, + int? totalRicontattiMonth, + DateTime? date, + String? errorMessage, + }) { + return DashboardDailyRicontattiState( + status: status ?? this.status, + summaries: summaries ?? this.summaries, + totalRicontattiToday: + totalRicontattiToday ?? this.totalRicontattiToday, + totalRicontattiMonth: + totalRicontattiMonth ?? this.totalRicontattiMonth, + date: date ?? this.date, + errorMessage: errorMessage, + ); + } + + @override + List get props => [ + status, + summaries, + totalRicontattiToday, + totalRicontattiMonth, + date, + errorMessage, + ]; +} diff --git a/lib/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart b/lib/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart new file mode 100644 index 0000000..d36028a --- /dev/null +++ b/lib/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart @@ -0,0 +1,73 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/operations/models/operation_model.dart'; + +/// Modello di riepilogo giornaliero dei ricontatti per singolo addetto. +class StaffDailyRicontattiSummary extends Equatable { + final String staffId; + final String staffName; + final String? jobTitle; + final SystemRole systemRole; + final int count; + final int monthCount; + final List operations; + + const StaffDailyRicontattiSummary({ + required this.staffId, + required this.staffName, + this.jobTitle, + this.systemRole = SystemRole.user, + required this.count, + this.monthCount = 0, + this.operations = const [], + }); + + /// Ha raggiunto l'obiettivo consigliato (almeno 2 ricontatti al giorno) + bool get hasReachedGoal => count >= 2; + + /// Ha iniziato la raccolta (1 ricontatto preso) + bool get hasStarted => count == 1; + + /// Non ha ancora registrato alcun ricontatto oggi + bool get isZero => count == 0; + + StaffDailyRicontattiSummary copyWith({ + String? staffId, + String? staffName, + String? jobTitle, + SystemRole? systemRole, + int? count, + int? monthCount, + List? operations, + }) { + return StaffDailyRicontattiSummary( + staffId: staffId ?? this.staffId, + staffName: staffName ?? this.staffName, + jobTitle: jobTitle ?? this.jobTitle, + systemRole: systemRole ?? this.systemRole, + count: count ?? this.count, + monthCount: monthCount ?? this.monthCount, + operations: operations ?? this.operations, + ); + } + + factory StaffDailyRicontattiSummary.empty() { + return const StaffDailyRicontattiSummary( + staffId: '', + staffName: '', + count: 0, + monthCount: 0, + ); + } + + @override + List get props => [ + staffId, + staffName, + jobTitle, + systemRole, + count, + monthCount, + operations, + ]; +} diff --git a/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart b/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart new file mode 100644 index 0000000..3d1cc62 --- /dev/null +++ b/lib/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart @@ -0,0 +1,869 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/routes/routes.dart'; +import 'package:flux/core/theme/theme.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +class DashboardDailyRicontattiCard extends StatelessWidget { + const DashboardDailyRicontattiCard({super.key}); + + @override + Widget build(BuildContext context) { + // Visibile solo ai manager o admin + final staff = context.watch().state.currentStaffMember; + final isManager = staff?.systemRole == SystemRole.manager || + staff?.systemRole == SystemRole.admin; + + if (!isManager) { + return const SizedBox.shrink(); + } + + return BlocBuilder( + builder: (context, state) { + final theme = Theme.of(context); + + return Padding( + padding: const EdgeInsets.fromLTRB(24.0, 0, 24.0, 24.0), + child: Container( + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(20), + border: Border.all( + color: Colors.amber.shade600.withValues(alpha: 0.35), + width: 1.5, + ), + boxShadow: [ + BoxShadow( + color: Colors.amber.shade700.withValues(alpha: 0.06), + blurRadius: 18, + offset: const Offset(0, 6), + ), + ], + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + _buildHeader(context, theme, state), + Divider( + height: 1, + color: theme.dividerColor.withValues(alpha: 0.15), + ), + if (state.status == DashboardDailyRicontattiStatus.loading && + state.summaries.isEmpty) + _buildLoading(theme) + else if (state.status == DashboardDailyRicontattiStatus.failure) + _buildError(context, theme, state) + else if (state.summaries.isEmpty) + _buildEmpty(theme) + else ...[ + _buildOverviewStats(context, theme, state), + Padding( + padding: const EdgeInsets.fromLTRB(18, 0, 18, 18), + child: _buildStaffGrid(context, theme, state.summaries), + ), + ], + ], + ), + ), + ); + }, + ); + } + + Widget _buildHeader( + BuildContext context, + ThemeData theme, + DashboardDailyRicontattiState state, + ) { + return Padding( + padding: const EdgeInsets.all(18.0), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: [ + Colors.amber.shade600, + Colors.orange.shade700, + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(14), + boxShadow: [ + BoxShadow( + color: Colors.amber.shade700.withValues(alpha: 0.3), + blurRadius: 8, + offset: const Offset(0, 3), + ), + ], + ), + child: const Icon( + Icons.event_repeat_rounded, + color: Colors.white, + size: 24, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Flexible( + child: Text( + 'FOCUS RICONTATTI DI OGGI', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w900, + letterSpacing: 0.5, + ), + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: Colors.amber.shade100, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + 'MANAGER', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w800, + color: Colors.amber.shade900, + letterSpacing: 0.4, + ), + ), + ), + ], + ), + const SizedBox(height: 3), + Text( + 'Raccolta situazioni da ricontattare & bollette (chi sta facendo e chi no)', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + const SizedBox(width: 12), + // Total today & month pill badge + Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 8), + decoration: BoxDecoration( + color: Colors.amber.shade500.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.amber.shade600.withValues(alpha: 0.4), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + '${state.totalRicontattiToday}', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w900, + color: Colors.amber.shade900, + ), + ), + const SizedBox(width: 5), + Text( + 'oggi', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + color: Colors.amber.shade800, + ), + ), + const SizedBox(width: 6), + Text( + '(mese: ${state.totalRicontattiMonth})', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w800, + color: Colors.amber.shade900.withValues(alpha: 0.85), + ), + ), + ], + ), + ), + const SizedBox(width: 6), + IconButton( + tooltip: 'Aggiorna ora', + icon: const Icon(Icons.refresh_rounded, size: 20), + onPressed: () => + context.read().refresh(), + ), + ], + ), + ); + } + + Widget _buildOverviewStats( + BuildContext context, + ThemeData theme, + DashboardDailyRicontattiState state, + ) { + final hasZeros = state.staffAtZero > 0; + + return Padding( + padding: const EdgeInsets.fromLTRB(18, 14, 18, 14), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 12, + runSpacing: 8, + children: [ + _buildStatChip( + icon: Icons.check_circle_rounded, + color: Colors.green.shade600, + bgColor: Colors.green.shade50, + label: '>= 2 Ricontatti', + count: state.staffWithGoal, + ), + _buildStatChip( + icon: Icons.hourglass_top_rounded, + color: Colors.blue.shade600, + bgColor: Colors.blue.shade50, + label: '1 Ricontatto', + count: state.staffWithOne, + ), + _buildStatChip( + icon: Icons.warning_amber_rounded, + color: Colors.deepOrange.shade600, + bgColor: Colors.deepOrange.shade50, + label: '0 Ricontatti', + count: state.staffAtZero, + ), + ], + ), + if (hasZeros) ...[ + const SizedBox(height: 10), + Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: Colors.deepOrange.shade50.withValues(alpha: 0.7), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: Colors.deepOrange.shade200, + ), + ), + child: Row( + children: [ + Icon( + Icons.info_outline_rounded, + size: 16, + color: Colors.deepOrange.shade800, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + '${state.staffAtZero} ${state.staffAtZero == 1 ? "addetto non ha" : "addetti non hanno"} ancora raccolto alcun ricontatto oggi.', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.deepOrange.shade900, + ), + ), + ), + ], + ), + ), + ], + ], + ), + ); + } + + Widget _buildStatChip({ + required IconData icon, + required Color color, + required Color bgColor, + required String label, + required int count, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: color.withValues(alpha: 0.3)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: 6), + Text( + label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: color, + ), + ), + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: color, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + '$count', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + color: Colors.white, + ), + ), + ), + ], + ), + ); + } + + Widget _buildStaffGrid( + BuildContext context, + ThemeData theme, + List summaries, + ) { + return LayoutBuilder( + builder: (context, constraints) { + // Calcola quante colonne in base alla larghezza disponibile + final double width = constraints.maxWidth; + final int crossAxisCount = width > 1100 + ? 4 + : width > 750 + ? 3 + : width > 480 + ? 2 + : 1; + + return GridView.builder( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: summaries.length, + gridDelegate: SliverGridDelegateWithFixedCrossAxisCount( + crossAxisCount: crossAxisCount, + mainAxisSpacing: 10, + crossAxisSpacing: 10, + mainAxisExtent: 104, + ), + itemBuilder: (context, index) { + final summary = summaries[index]; + return _StaffItemCard(summary: summary); + }, + ); + }, + ); + } + + Widget _buildLoading(ThemeData theme) { + return const Padding( + padding: EdgeInsets.all(32.0), + child: Center( + child: SizedBox( + width: 28, + height: 28, + child: CircularProgressIndicator(strokeWidth: 2.5), + ), + ), + ); + } + + Widget _buildError( + BuildContext context, + ThemeData theme, + DashboardDailyRicontattiState state, + ) { + return Padding( + padding: const EdgeInsets.all(24.0), + child: Center( + child: Column( + children: [ + Icon(Icons.error_outline, color: theme.colorScheme.error, size: 32), + const SizedBox(height: 8), + Text( + 'Impossibile caricare i dati dei ricontatti', + style: TextStyle(color: theme.colorScheme.error), + ), + const SizedBox(height: 8), + TextButton.icon( + onPressed: () => + context.read().refresh(), + icon: const Icon(Icons.refresh), + label: const Text('Riprova'), + ), + ], + ), + ), + ); + } + + Widget _buildEmpty(ThemeData theme) { + return const Padding( + padding: EdgeInsets.all(24.0), + child: Center( + child: Text( + 'Nessun addetto attivo registrato per questo negozio.', + style: TextStyle(fontStyle: FontStyle.italic), + ), + ), + ); + } +} + +class _StaffItemCard extends StatelessWidget { + final StaffDailyRicontattiSummary summary; + + const _StaffItemCard({required this.summary}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + // Stile in base al conteggio + final bool hasGoal = summary.hasReachedGoal; + final bool hasOne = summary.hasStarted; + final bool isZero = summary.isZero; + + final Color primaryColor = hasGoal + ? Colors.green.shade600 + : hasOne + ? Colors.blue.shade600 + : Colors.grey.shade500; + + final Color cardBg = hasGoal + ? Colors.green.shade50.withValues(alpha: 0.3) + : hasOne + ? Colors.blue.shade50.withValues(alpha: 0.3) + : theme.colorScheme.surface; + + final Color borderColor = hasGoal + ? Colors.green.shade400 + : hasOne + ? Colors.blue.shade300 + : theme.dividerColor.withValues(alpha: 0.25); + + final String initials = _getInitials(summary.staffName); + + return InkWell( + onTap: () => _handleTap(context), + borderRadius: BorderRadius.circular(14), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: cardBg, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: borderColor, + width: isZero ? 1.0 : 1.5, + ), + ), + child: Row( + children: [ + // Avatar con iniziali + CircleAvatar( + radius: 20, + backgroundColor: primaryColor.withValues(alpha: 0.15), + child: Text( + initials, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.w800, + color: primaryColor, + ), + ), + ), + const SizedBox(width: 10), + // Nome e stato + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Text( + summary.staffName, + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.w700, + color: isZero + ? context.primaryText.withValues(alpha: 0.75) + : context.primaryText, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + const SizedBox(height: 3), + _buildStatusChip(hasGoal, hasOne, isZero), + ], + ), + ), + const SizedBox(width: 8), + // Grande numero conteggio e riepilogo mese tra parentesi + Column( + mainAxisAlignment: MainAxisAlignment.center, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + '${summary.count}', + style: TextStyle( + fontSize: 24, + fontWeight: FontWeight.w900, + height: 1.0, + color: hasGoal + ? Colors.green.shade700 + : hasOne + ? Colors.blue.shade700 + : Colors.grey.shade400, + ), + ), + const SizedBox(width: 4), + Text( + 'oggi', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: hasGoal + ? Colors.green.shade700 + : hasOne + ? Colors.blue.shade700 + : Colors.grey.shade500, + ), + ), + ], + ), + const SizedBox(height: 3), + Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.6), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + '(mese: ${summary.monthCount})', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.85), + ), + ), + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildStatusChip(bool hasGoal, bool hasOne, bool isZero) { + if (hasGoal) { + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(Icons.star_rounded, size: 13, color: Colors.green.shade700), + const SizedBox(width: 3), + Text( + 'Obiettivo preso', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: Colors.green.shade700, + ), + ), + ], + ); + } + + if (hasOne) { + return Text( + '1 raccolto', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Colors.blue.shade700, + ), + ); + } + + return Text( + '0 ricontatti', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Colors.deepOrange.shade600, + ), + ); + } + + String _getInitials(String name) { + final parts = name.trim().split(RegExp(r'\s+')); + if (parts.isEmpty || parts[0].isEmpty) return '?'; + if (parts.length == 1) return parts[0][0].toUpperCase(); + return '${parts[0][0]}${parts[1][0]}'.toUpperCase(); + } + + void _handleTap(BuildContext context) { + if (summary.operations.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + '${summary.staffName} non ha ancora registrato ricontatti oggi (${summary.monthCount} nel mese).', + ), + duration: const Duration(seconds: 2), + behavior: SnackBarBehavior.floating, + ), + ); + return; + } + + // Mostra bottom sheet di dettaglio con le operazioni prese oggi dall'addetto + showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (sheetContext) => _StaffOperationsSheet(summary: summary), + ); + } +} + +class _StaffOperationsSheet extends StatelessWidget { + final StaffDailyRicontattiSummary summary; + + const _StaffOperationsSheet({required this.summary}); + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final timeFormat = DateFormat('HH:mm'); + + return Container( + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), + ), + padding: EdgeInsets.only( + top: 16, + left: 20, + right: 20, + bottom: MediaQuery.of(context).viewInsets.bottom + 24, + ), + constraints: BoxConstraints( + maxHeight: MediaQuery.of(context).size.height * 0.75, + ), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Center( + child: Container( + width: 40, + height: 4, + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: theme.dividerColor.withValues(alpha: 0.3), + borderRadius: BorderRadius.circular(2), + ), + ), + ), + Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.amber.shade100, + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.person_rounded, + color: Colors.amber.shade900, + size: 22, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + summary.staffName, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + '${summary.count} ${summary.count == 1 ? "ricontatto oggi" : "ricontatti oggi"} • (${summary.monthCount} nel mese)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + onPressed: () => Navigator.of(context).pop(), + icon: const Icon(Icons.close), + ), + ], + ), + const SizedBox(height: 16), + Divider(height: 1, color: theme.dividerColor.withValues(alpha: 0.2)), + const SizedBox(height: 12), + Flexible( + child: ListView.separated( + shrinkWrap: true, + itemCount: summary.operations.length, + separatorBuilder: (context, _) => Divider( + height: 16, + color: theme.dividerColor.withValues(alpha: 0.1), + ), + itemBuilder: (context, index) { + final op = summary.operations[index]; + final ricontattoDetails = op.details + .where((d) => d.type == OperationType.ricontatto) + .toList(); + + final timeStr = op.createdAt != null + ? timeFormat.format(op.createdAt!) + : '--:--'; + + return InkWell( + borderRadius: BorderRadius.circular(12), + onTap: () { + Navigator.of(context).pop(); + context.pushNamed( + Routes.operationForm, + extra: (createdBy: null, operation: op), + pathParameters: {'id': op.id!}, + ); + }, + child: Padding( + padding: const EdgeInsets.symmetric( + vertical: 8.0, + horizontal: 4.0, + ), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + timeStr, + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w700, + ), + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + op.customer?.name ?? 'Cliente non specificato', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + ), + ), + const SizedBox(height: 4), + Wrap( + spacing: 6, + runSpacing: 4, + children: ricontattoDetails.map((detail) { + final label = detail.subType != null && + detail.subType!.isNotEmpty + ? detail.subType! + : 'Ricontatto'; + return Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: Colors.amber.shade100, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + label, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: Colors.amber.shade900, + ), + ), + ); + }).toList(), + ), + if (op.note.trim().isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + op.note, + style: TextStyle( + fontSize: 12, + fontStyle: FontStyle.italic, + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ], + ), + ), + const SizedBox(width: 8), + const Icon( + Icons.chevron_right_rounded, + size: 20, + color: Colors.grey, + ), + ], + ), + ), + ); + }, + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart b/lib/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart index bd50814..113678d 100644 --- a/lib/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart +++ b/lib/features/home/dashboard_store_ticket_list/blocs/dashboard_store_ticket_list_cubit.dart @@ -79,6 +79,18 @@ class DashboardStoreTicketListCubit Future _loadTicketsSilently() async { try { + if (companyId == null || companyId!.isEmpty) { + if (!isClosed) { + emit( + state.copyWith( + status: DashboardStoreTicketListStatus.initial, + tickets: [], + errorMessage: null, + ), + ); + } + return; + } final tickets = await _repository.fetchTickets( companyId: companyId!, storeId: storeId, diff --git a/lib/features/home/ui/home_screen.dart b/lib/features/home/ui/home_screen.dart index f462bfd..7b4285a 100644 --- a/lib/features/home/ui/home_screen.dart +++ b/lib/features/home/ui/home_screen.dart @@ -6,6 +6,8 @@ import 'package:flux/core/routes/routes.dart'; import 'package:flux/core/theme/theme.dart'; import 'package:flux/core/utils/extensions.dart'; import 'package:flux/core/widgets/staff_selector_modal.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_cubit.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/ui/dashboard_daily_ricontatti_card.dart'; import 'package:flux/features/home/dashboard_expiring_contracts/bloc/dashboard_expiring_contracts_cubit.dart'; import 'package:flux/features/home/dashboard_expiring_contracts/ui/dashboard_expiring_contracts_card.dart'; import 'package:flux/features/home/dashboard_note_list/blocs/dashboard_note_list_cubit.dart'; @@ -79,6 +81,7 @@ class _HomeScreenState extends State { context.read().stopListening(); context.read().stopListening(); context.read().stopListening(); + context.read().stopListening(); } void _startListeners() { @@ -88,12 +91,17 @@ class _HomeScreenState extends State { newStoreId: sessionState.currentStore?.id, newStaffId: sessionState.currentStaffMember?.id, ); + context.read().updateContext( + newCompanyId: sessionState.company?.id, + newStoreId: sessionState.currentStore?.id, + ); context.read().startListening(); context.read().startListening(); context.read().startListening(); context.read().startListening(); context.read().startListening(); context.read().startListening(); + context.read().startListening(); } @override @@ -137,6 +145,10 @@ class _HomeScreenState extends State { newStoreId: sessionState.currentStore?.id, newStaffId: sessionState.currentStaffMember?.id, ); + context.read().updateContext( + newCompanyId: sessionState.company?.id, + newStoreId: sessionState.currentStore?.id, + ); }, child: CustomScrollView( slivers: [ @@ -148,6 +160,11 @@ class _HomeScreenState extends State { ), ), + // --- HERO FOCUS RICONTATTI DEL GIORNO (SOLO MANAGER) --- + const SliverToBoxAdapter( + child: DashboardDailyRicontattiCard(), + ), + // --- QUICK ACTIONS: AZIONI RAPIDE --- SliverToBoxAdapter( child: Padding( diff --git a/lib/features/operations/data/operations_repository.dart b/lib/features/operations/data/operations_repository.dart index 4314169..1abefae 100644 --- a/lib/features/operations/data/operations_repository.dart +++ b/lib/features/operations/data/operations_repository.dart @@ -4,6 +4,7 @@ import 'package:flux/core/enums_and_consts/consts.dart'; import 'package:flux/features/master_data/store/models/store_model.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; import 'package:flux/features/operations/models/operation_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; import 'package:flux/features/operations/models/paginated_operations.dart'; import 'package:flux/service_locator.dart'; import 'package:supabase_flutter/supabase_flutter.dart'; @@ -314,4 +315,58 @@ class OperationsRepository { } return earliest; } + + /// Recupera il conteggio dei ricontatti registrati nel mese per ciascun addetto del negozio + Future> getMonthlyRicontattiCountsByStaff({ + required String companyId, + required String storeId, + required DateTime month, + }) async { + try { + final monthStart = DateTime(month.year, month.month, 1, 0, 0, 0); + final monthEnd = DateTime(month.year, month.month + 1, 0, 23, 59, 59, 999); + + final response = await _supabase + .from(Tables.operations) + .select(''' + id, + staff_id, + ${Tables.operationDetails}( + type + ) + ''') + .eq('company_id', companyId) + .eq('store_id', storeId) + .neq('status', 'failure') + .gte('created_at', monthStart.toIso8601String()) + .lte('created_at', monthEnd.toIso8601String()); + + final operations = response as List; + final Map staffCounts = {}; + + for (final op in operations) { + final staffId = op['staff_id'] as String?; + if (staffId == null || staffId.isEmpty) continue; + + final details = op[Tables.operationDetails] as List? ?? []; + int ricontattiInOp = 0; + for (final detail in details) { + final typeVal = detail['type']?.toString(); + if (typeVal != null && + OperationType.fromValue(typeVal) == OperationType.ricontatto) { + ricontattiInOp++; + } + } + + if (ricontattiInOp > 0) { + staffCounts[staffId] = (staffCounts[staffId] ?? 0) + ricontattiInOp; + } + } + + return staffCounts; + } catch (e) { + debugPrint('Errore nel recupero conteggi ricontatti del mese: $e'); + return {}; + } + } } diff --git a/lib/features/tickets/data/ticket_repository.dart b/lib/features/tickets/data/ticket_repository.dart index 47ab81c..cee148e 100644 --- a/lib/features/tickets/data/ticket_repository.dart +++ b/lib/features/tickets/data/ticket_repository.dart @@ -49,8 +49,14 @@ class TicketRepository { assigned_to:${Tables.staffMembers}!ticket_assigned_to_id_fkey (*), target_model:${Tables.models}!ticket_model_id_1_fkey (*), source_model:${Tables.models}!ticket_model_id_2_fkey (*) - ''') - .eq('store_id', GetIt.I.get().state.currentStore!.id!); + '''); + + final currentStoreId = + GetIt.I.get().state.currentStore?.id; + if (currentStoreId == null) { + return []; + } + query = query.eq('store_id', currentStoreId); // Filtro Range Date if (dateRange != null) { @@ -191,12 +197,15 @@ class TicketRepository { } } - /// Stream dei ticket che necessitano attenzione (es. in scadenza oggi o in ritardo) Stream> getAttentionNeededTicketsStream() { + final storeId = GetIt.I.get().state.currentStore?.id; + if (storeId == null) { + return const Stream.empty(); + } return _supabase .from(_tableName) .stream(primaryKey: ['id']) - .eq('store_id', GetIt.I.get().state.currentStore!.id!) + .eq('store_id', storeId) // Purtroppo lo stream accetta solo filtri base, quindi ci facciamo // mandare i dati e li filtriamo con la potenza di Dart! .limit(300) diff --git a/lib/main.dart b/lib/main.dart index 1c60212..c7b71d0 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -49,7 +49,11 @@ void main() async { return true; // Contrassegna l'errore come gestito ed evita il crash dell'app }; - await dotenv.load(fileName: ".env"); + 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=')) { @@ -85,10 +89,14 @@ void main() async { ), BlocProvider(create: (_) => sl()), BlocProvider( - create: (_) => sl() - ..loadStaffForStore( - GetIt.I.get().state.currentStore!.id!, - ), + create: (_) { + final cubit = sl(); + final storeId = sl().state.currentStore?.id; + if (storeId != null) { + cubit.loadStaffForStore(storeId); + } + return cubit; + }, ), BlocProvider( create: (_) => sl(), diff --git a/test/features/home/dashboard_daily_ricontatti/dashboard_daily_ricontatti_test.dart b/test/features/home/dashboard_daily_ricontatti/dashboard_daily_ricontatti_test.dart new file mode 100644 index 0000000..16539ad --- /dev/null +++ b/test/features/home/dashboard_daily_ricontatti/dashboard_daily_ricontatti_test.dart @@ -0,0 +1,125 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/blocs/dashboard_daily_ricontatti_state.dart'; +import 'package:flux/features/home/dashboard_daily_ricontatti/models/staff_daily_ricontatti_summary.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; + +void main() { + group('StaffDailyRicontattiSummary', () { + test('correctly evaluates hasReachedGoal, hasStarted, isZero', () { + const summaryZero = StaffDailyRicontattiSummary( + staffId: '1', + staffName: 'Mario Rossi', + count: 0, + ); + expect(summaryZero.isZero, isTrue); + expect(summaryZero.hasStarted, isFalse); + expect(summaryZero.hasReachedGoal, isFalse); + + const summaryOne = StaffDailyRicontattiSummary( + staffId: '2', + staffName: 'Luigi Bianchi', + count: 1, + ); + expect(summaryOne.isZero, isFalse); + expect(summaryOne.hasStarted, isTrue); + expect(summaryOne.hasReachedGoal, isFalse); + + const summaryTwo = StaffDailyRicontattiSummary( + staffId: '3', + staffName: 'Anna Verdi', + count: 2, + ); + expect(summaryTwo.isZero, isFalse); + expect(summaryTwo.hasStarted, isFalse); + expect(summaryTwo.hasReachedGoal, isTrue); + + const summaryFive = StaffDailyRicontattiSummary( + staffId: '4', + staffName: 'Paolo Neri', + count: 5, + ); + expect(summaryFive.isZero, isFalse); + expect(summaryFive.hasStarted, isFalse); + expect(summaryFive.hasReachedGoal, isTrue); + }); + + test('copyWith updates fields as expected', () { + const original = StaffDailyRicontattiSummary( + staffId: '1', + staffName: 'Mario', + count: 0, + systemRole: SystemRole.user, + ); + + final updated = original.copyWith( + count: 3, + monthCount: 15, + systemRole: SystemRole.manager, + ); + + expect(updated.count, equals(3)); + expect(updated.monthCount, equals(15)); + expect(updated.systemRole, equals(SystemRole.manager)); + expect(updated.staffName, equals('Mario')); + expect(updated.staffId, equals('1')); + }); + }); + + group('DashboardDailyRicontattiState', () { + test('computes staffWithGoal, staffWithOne, staffAtZero correctly', () { + final state = DashboardDailyRicontattiState( + date: DateTime(2026, 10, 9), + summaries: const [ + StaffDailyRicontattiSummary( + staffId: '1', + staffName: 'Mario', + count: 3, // >= 2 + monthCount: 18, + ), + StaffDailyRicontattiSummary( + staffId: '2', + staffName: 'Luigi', + count: 2, // >= 2 + monthCount: 12, + ), + StaffDailyRicontattiSummary( + staffId: '3', + staffName: 'Anna', + count: 1, // == 1 + monthCount: 9, + ), + StaffDailyRicontattiSummary( + staffId: '4', + staffName: 'Paolo', + count: 0, // == 0 + monthCount: 5, + ), + StaffDailyRicontattiSummary( + staffId: '5', + staffName: 'Giulia', + count: 0, // == 0 + monthCount: 0, + ), + ], + totalRicontattiToday: 6, + totalRicontattiMonth: 44, + ); + + expect(state.activeStaffCount, equals(5)); + expect(state.staffWithGoal, equals(2)); + expect(state.staffWithOne, equals(1)); + expect(state.staffAtZero, equals(2)); + expect(state.totalRicontattiToday, equals(6)); + expect(state.totalRicontattiMonth, equals(44)); + }); + }); + + group('OperationType.ricontatto', () { + test('resolves from string accurately', () { + expect(OperationType.fromValue('ricontatto'), equals(OperationType.ricontatto)); + expect(OperationType.fromValue('Ricontatto'), equals(OperationType.ricontatto)); + expect(OperationType.fromValue('RICONTATTO'), equals(OperationType.ricontatto)); + }); + }); +}