From 57a4dc6f684dc0499dce164069c23716c3cec08b Mon Sep 17 00:00:00 2001 From: Mark-cachy Date: Sat, 21 Nov 2026 10:23:04 +0100 Subject: [PATCH] filtri avanzati operazioni --- lib/core/routes/app_router.dart | 12 +- .../ui/dashboard_target_hero_card.dart | 162 +++-- .../blocs/operation_list_cubit.dart | 84 ++- .../blocs/operation_list_state.dart | 84 ++- .../data/operations_repository.dart | 64 +- .../models/operation_filter_params.dart | 221 ++++++ .../operations/ui/operation_list_screen.dart | 470 ++++++++++--- .../ui/widgets/operation_filter_sheet.dart | 649 ++++++++++++++++++ .../targets/ui/target_detail_screen.dart | 380 ++++++---- pubspec.yaml | 2 +- .../blocs/operation_list_filter_test.dart | 95 +++ .../models/operation_filter_params_test.dart | 143 ++++ 12 files changed, 2045 insertions(+), 321 deletions(-) create mode 100644 lib/features/operations/models/operation_filter_params.dart create mode 100644 lib/features/operations/ui/widgets/operation_filter_sheet.dart create mode 100644 test/features/operations/blocs/operation_list_filter_test.dart create mode 100644 test/features/operations/models/operation_filter_params_test.dart diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 0567775..62c0570 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -48,6 +48,7 @@ import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart'; import 'package:flux/features/operations/blocs/operation_form_cubit.dart'; import 'package:flux/features/operations/models/operation_model.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; import 'package:flux/features/operations/ui/financing_form_screen.dart'; import 'package:flux/features/operations/ui/operation_form_screen.dart'; import 'package:flux/features/operations/ui/operation_list_screen.dart'; @@ -317,7 +318,16 @@ class AppRouter { GoRoute( path: '/operations', name: Routes.operations, - builder: (context, state) => const OperationListScreen(), + builder: (context, state) { + final params = state.extra is OperationFilterParams + ? state.extra as OperationFilterParams + : OperationFilterParams.fromQueryParams( + state.uri.queryParameters, + ); + return OperationListScreen( + initialFilters: params.isNotEmpty ? params : null, + ); + }, ), GoRoute( path: '/tickets', diff --git a/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart b/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart index 885439f..dde705f 100644 --- a/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart +++ b/lib/features/home/dashboard_target_progress/ui/dashboard_target_hero_card.dart @@ -5,6 +5,7 @@ import 'package:flux/core/routes/routes.dart'; import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_cubit.dart'; import 'package:flux/features/home/dashboard_target_progress/blocs/dashboard_target_progress_state.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; import 'package:flux/features/targets/models/target_progress_model.dart'; import 'package:go_router/go_router.dart'; @@ -524,6 +525,29 @@ class _DashboardTargetHeroCardState extends State { ); } + void _navigateToOperationsForCategory( + CategoryProgress category, { + bool isManager = false, + }) { + final state = context.read().state; + final target = state.target; + if (target == null) return; + + final staffId = isManager ? null : state.currentStaffId; + + final params = OperationFilterParams.fromTargetCategory( + categoryKey: category.key, + categoryLabel: category.label, + target: target, + staffId: staffId, + ); + + context.pushNamed( + Routes.operations, + extra: params, + ); + } + Widget _buildCategoryDailyPacingCard( ThemeData theme, CategoryProgress category, { @@ -534,67 +558,89 @@ class _DashboardTargetHeroCardState extends State { final isAchieved = category.isAchieved; final hasS2 = category.targetS2 > 0; - return Container( - padding: const EdgeInsets.all(12), - decoration: BoxDecoration( - color: theme.colorScheme.surface, + return Material( + color: Colors.transparent, + child: InkWell( borderRadius: BorderRadius.circular(14), - border: Border.all( - color: pacingTheme.border.withValues(alpha: 0.7), - width: 1.2, + onTap: () => _navigateToOperationsForCategory( + category, + isManager: isManager, ), - boxShadow: [ - BoxShadow( - color: pacingTheme.primary.withValues(alpha: 0.04), - blurRadius: 8, - offset: const Offset(0, 2), - ), - ], - ), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Header tessera: Nome metrica + Pillola di stato - Row( - children: [ - Expanded( - child: Text( - category.label.toUpperCase(), - style: const TextStyle( - fontSize: 11, - fontWeight: FontWeight.w800, - letterSpacing: 0.3, - ), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - ), - const SizedBox(width: 4), - Container( - padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), - decoration: BoxDecoration( - color: pacingTheme.background, - borderRadius: BorderRadius.circular(6), - border: Border.all(color: pacingTheme.border, width: 0.8), - ), - child: Text( - isAchieved - ? 'Preso! 🎉' - : (category.status == TargetPacingStatus.inLineS1 || - category.status == TargetPacingStatus.inLineS2 - ? 'In linea ✅' - : (category.status == TargetPacingStatus.recoverable - ? 'Da spingere ⚡' - : 'In ritardo 🔴')), - style: TextStyle( - fontSize: 9, - fontWeight: FontWeight.w900, - color: pacingTheme.text, - ), - ), + child: Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: pacingTheme.border.withValues(alpha: 0.7), + width: 1.2, + ), + boxShadow: [ + BoxShadow( + color: pacingTheme.primary.withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), ), ], ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Header tessera: Nome metrica + Pillola di stato + Row( + children: [ + Expanded( + child: Text( + category.label.toUpperCase(), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w800, + letterSpacing: 0.3, + ), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + ), + const SizedBox(width: 4), + Container( + padding: + const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: pacingTheme.background, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: pacingTheme.border, width: 0.8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + isAchieved + ? 'Preso! 🎉' + : (category.status == TargetPacingStatus.inLineS1 || + category.status == + TargetPacingStatus.inLineS2 + ? 'In linea ✅' + : (category.status == + TargetPacingStatus.recoverable + ? 'Da spingere ⚡' + : 'In ritardo 🔴')), + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.w900, + color: pacingTheme.text, + ), + ), + const SizedBox(width: 3), + Icon( + Icons.arrow_forward_ios, + size: 8, + color: pacingTheme.text, + ), + ], + ), + ), + ], + ), const Spacer(), @@ -757,7 +803,9 @@ class _DashboardTargetHeroCardState extends State { ], ], ), - ); + ), + ), +); } Widget _buildInLineSummaryBanner( diff --git a/lib/features/operations/blocs/operation_list_cubit.dart b/lib/features/operations/blocs/operation_list_cubit.dart index 6b5aec0..067c320 100644 --- a/lib/features/operations/blocs/operation_list_cubit.dart +++ b/lib/features/operations/blocs/operation_list_cubit.dart @@ -5,7 +5,9 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/features/operations/data/operations_repository.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; import 'package:flux/features/operations/models/operation_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; import 'package:get_it/get_it.dart'; part 'operation_list_state.dart'; @@ -40,6 +42,11 @@ class OperationListCubit extends Cubit { itemsPerPage: state.itemsPerPage, searchTerm: state.searchTerm, dateRange: state.dateRange, + detailType: state.detailType, + subType: state.subType, + categoryKey: state.categoryKey, + staffId: state.staffId, + storeId: state.storeId, ); if (currentFetchId != _fetchId) return; @@ -85,6 +92,11 @@ class OperationListCubit extends Cubit { itemsPerPage: state.itemsPerPage, searchTerm: state.searchTerm, dateRange: state.dateRange, + detailType: state.detailType, + subType: state.subType, + categoryKey: state.categoryKey, + staffId: state.staffId, + storeId: state.storeId, ); if (currentFetchId != _fetchId) return; @@ -112,13 +124,74 @@ class OperationListCubit extends Cubit { } } - void updateFilters({String? text, DateTimeRange? range}) { + /// Applica un set completo di parametri di filtro (es. proveniente da una card Obiettivo) + void applyFilterParams(OperationFilterParams params) { emit( state.copyWith( - // 🥷 FORZIAMO IL TIPO: Diciamo a Dart che il risultato del ternario è proprio una funzione - searchTerm: text != null ? () => text : null, - dateRange: range != null ? () => range : null, + searchTerm: () => params.searchTerm, + dateRange: () => params.dateRange, + detailType: () => params.detailType, + subType: () => params.subType, + categoryKey: () => params.categoryKey, + categoryLabel: () => params.categoryLabel, + staffId: () => params.staffId, + staffDisplayName: () => params.staffDisplayName, + storeId: () => params.storeId, + currentPage: 1, + hasReachedMax: false, + ), + ); + loadSpecificPageDesktop(1); + } + + void updateFilters({ + String? text, + DateTimeRange? range, + OperationType? detailType, + String? subType, + String? categoryKey, + String? categoryLabel, + String? staffId, + String? staffDisplayName, + String? storeId, + bool clearText = false, + bool clearRange = false, + bool clearDetailType = false, + bool clearSubType = false, + bool clearCategory = false, + bool clearStaff = false, + bool clearStore = false, + }) { + emit( + state.copyWith( + searchTerm: clearText + ? () => null + : (text != null ? () => text : null), + dateRange: clearRange + ? () => null + : (range != null ? () => range : null), + detailType: clearDetailType + ? () => null + : (detailType != null ? () => detailType : null), + subType: clearSubType + ? () => null + : (subType != null ? () => subType : null), + categoryKey: clearCategory + ? () => null + : (categoryKey != null ? () => categoryKey : null), + categoryLabel: clearCategory + ? () => null + : (categoryLabel != null ? () => categoryLabel : null), + staffId: clearStaff + ? () => null + : (staffId != null ? () => staffId : null), + staffDisplayName: clearStaff + ? () => null + : (staffDisplayName != null ? () => staffDisplayName : null), + storeId: clearStore + ? () => null + : (storeId != null ? () => storeId : null), currentPage: 1, // Reset obbligatorio alla prima pagina hasReachedMax: false, ), @@ -129,10 +202,7 @@ class OperationListCubit extends Cubit { } void clearFilters() { - // Invece di un const vuoto che potrebbe bruciarti l'impostazione itemsPerPage, - // creiamo uno stato pulito ma manteniamo la preferenza di paginazione. emit(OperationListState(itemsPerPage: state.itemsPerPage)); - loadSpecificPageDesktop(1); } diff --git a/lib/features/operations/blocs/operation_list_state.dart b/lib/features/operations/blocs/operation_list_state.dart index 19e499f..4b9da4a 100644 --- a/lib/features/operations/blocs/operation_list_state.dart +++ b/lib/features/operations/blocs/operation_list_state.dart @@ -13,9 +13,16 @@ class OperationListState extends Equatable { final int totalItems; final bool hasReachedMax; - // 🥷 I FILTRI MANCANTI (Riparati!) + // Filtri Avanzati final String? searchTerm; final DateTimeRange? dateRange; + final OperationType? detailType; + final String? subType; + final String? categoryKey; + final String? categoryLabel; + final String? staffId; + final String? staffDisplayName; + final String? storeId; const OperationListState({ this.status = OperationListStatus.initial, @@ -27,11 +34,54 @@ class OperationListState extends Equatable { this.hasReachedMax = false, this.searchTerm, this.dateRange, + this.detailType, + this.subType, + this.categoryKey, + this.categoryLabel, + this.staffId, + this.staffDisplayName, + this.storeId, }); int get totalPages => (totalItems / itemsPerPage).ceil(); - // 🥷 COPYWITH AVANZATO: Gestisce lo sbiancamento dei filtri alla perfezione + bool get hasActiveFilters => + (searchTerm != null && searchTerm!.trim().isNotEmpty) || + dateRange != null || + detailType != null || + (subType != null && subType!.trim().isNotEmpty) || + categoryKey != null || + staffId != null || + storeId != null; + + int get activeFiltersCount { + int count = 0; + if (searchTerm != null && searchTerm!.trim().isNotEmpty) count++; + if (dateRange != null) count++; + if (detailType != null) count++; + if (subType != null && subType!.trim().isNotEmpty && categoryKey == null) { + count++; + } + if (categoryKey != null) count++; + if (staffId != null) count++; + if (storeId != null) count++; + return count; + } + + OperationFilterParams toFilterParams() { + return OperationFilterParams( + searchTerm: searchTerm, + dateRange: dateRange, + detailType: detailType, + subType: subType, + categoryKey: categoryKey, + categoryLabel: categoryLabel, + staffId: staffId, + staffDisplayName: staffDisplayName, + storeId: storeId, + ); + } + OperationListState copyWith({ OperationListStatus? status, List? operations, @@ -40,9 +90,15 @@ class OperationListState extends Equatable { int? itemsPerPage, int? totalItems, bool? hasReachedMax, - String? Function()? searchTerm, // Callback per gestire il null esplicito - DateTimeRange? Function()? - dateRange, // Callback per gestire il null esplicito + String? Function()? searchTerm, + DateTimeRange? Function()? dateRange, + OperationType? Function()? detailType, + String? Function()? subType, + String? Function()? categoryKey, + String? Function()? categoryLabel, + String? Function()? staffId, + String? Function()? staffDisplayName, + String? Function()? storeId, }) { return OperationListState( status: status ?? this.status, @@ -52,10 +108,17 @@ class OperationListState extends Equatable { itemsPerPage: itemsPerPage ?? this.itemsPerPage, totalItems: totalItems ?? this.totalItems, hasReachedMax: hasReachedMax ?? this.hasReachedMax, - - // Se passi la funzione la eseguiamo, altrimenti teniamo il valore corrente searchTerm: searchTerm != null ? searchTerm() : this.searchTerm, dateRange: dateRange != null ? dateRange() : this.dateRange, + detailType: detailType != null ? detailType() : this.detailType, + subType: subType != null ? subType() : this.subType, + categoryKey: categoryKey != null ? categoryKey() : this.categoryKey, + categoryLabel: + categoryLabel != null ? categoryLabel() : this.categoryLabel, + staffId: staffId != null ? staffId() : this.staffId, + staffDisplayName: + staffDisplayName != null ? staffDisplayName() : this.staffDisplayName, + storeId: storeId != null ? storeId() : this.storeId, ); } @@ -70,5 +133,12 @@ class OperationListState extends Equatable { hasReachedMax, searchTerm, dateRange, + detailType, + subType, + categoryKey, + categoryLabel, + staffId, + staffDisplayName, + storeId, ]; } diff --git a/lib/features/operations/data/operations_repository.dart b/lib/features/operations/data/operations_repository.dart index 1abefae..a9b1691 100644 --- a/lib/features/operations/data/operations_repository.dart +++ b/lib/features/operations/data/operations_repository.dart @@ -54,6 +54,10 @@ class OperationsRepository { String? storeId, String? staffId, String? providerId, + OperationType? detailType, + String? subType, + String? categoryKey, + bool? isBusiness, required int page, int itemsPerPage = 20, String? searchTerm, @@ -67,6 +71,12 @@ class OperationsRepository { final from = (page - 1) * itemsPerPage; final to = from + itemsPerPage - 1; + final hasDetailFilter = detailType != null || + (subType != null && subType.trim().isNotEmpty) || + (categoryKey != null && categoryKey != 'business'); + + final detailJoin = hasDetailFilter ? '!inner' : ''; + var query = _supabase .from(Tables.operations) .select(''' @@ -75,7 +85,7 @@ class OperationsRepository { ${Tables.stores}(*), ${Tables.staffMembers}(*), ${Tables.attachments}(*), - ${Tables.operationDetails}( + ${Tables.operationDetails}$detailJoin( *, ${Tables.providers}(*), ${Tables.models}(*) @@ -87,25 +97,63 @@ class OperationsRepository { query = query.eq('show_in_dashboard', true); } + // Se veniamo da una categoria target, escludiamo le operazioni annullate/scartate + if (categoryKey != null) { + query = query.neq('status', 'failure'); + } + // Filtro Range Date if (dateRange != null) { + final start = dateRange.start; + final end = (dateRange.end.hour == 0 && dateRange.end.minute == 0) + ? DateTime( + dateRange.end.year, + dateRange.end.month, + dateRange.end.day, + 23, + 59, + 59, + 999, + ) + : dateRange.end; query = query - .gte('created_at', dateRange.start.toIso8601String()) - .lte('created_at', dateRange.end.toIso8601String()); + .gte('created_at', start.toIso8601String()) + .lte('created_at', end.toIso8601String()); } - if (storeId != null) { - query = query.or('store_id.eq.$storeId,store_id.is.null'); + if (storeId != null && storeId.isNotEmpty) { + if (categoryKey != null) { + query = query.eq('store_id', storeId); + } else { + query = query.or('store_id.eq.$storeId,store_id.is.null'); + } } - if (staffId != null) { - query = query.or('staff_id.eq.$staffId,staff_id.is.null'); + if (staffId != null && staffId.isNotEmpty) { + query = query.eq('staff_id', staffId); } - if (providerId != null) { + if (providerId != null && providerId.isNotEmpty) { query = query.or('provider_id.eq.$providerId,provider_id.is.null'); } + // Filtro per Dettaglio Operazione / Categoria + if (categoryKey == 'business' || isBusiness == true) { + query = query.or( + 'is_business.eq.true,${Tables.operationDetails}.type.eq.Business', + ); + } else { + if (detailType != null) { + query = query.eq('${Tables.operationDetails}.type', detailType.value); + } + if (subType != null && subType.trim().isNotEmpty) { + query = query.ilike( + '${Tables.operationDetails}.sub_type', + '%${subType.trim()}%', + ); + } + } + if (searchTerm != null && searchTerm.trim().isNotEmpty) { final cleanTerm = searchTerm.trim().replaceAll(',', ' '); List matchingCustomerIds = []; diff --git a/lib/features/operations/models/operation_filter_params.dart b/lib/features/operations/models/operation_filter_params.dart new file mode 100644 index 0000000..bb7da86 --- /dev/null +++ b/lib/features/operations/models/operation_filter_params.dart @@ -0,0 +1,221 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:flux/features/targets/models/target_model.dart'; + +/// Parametri per il filtraggio avanzato delle operazioni +class OperationFilterParams extends Equatable { + final String? searchTerm; + final DateTimeRange? dateRange; + final OperationType? detailType; + final String? subType; + final String? categoryKey; + final String? categoryLabel; + final String? staffId; + final String? staffDisplayName; + final String? storeId; + + const OperationFilterParams({ + this.searchTerm, + this.dateRange, + this.detailType, + this.subType, + this.categoryKey, + this.categoryLabel, + this.staffId, + this.staffDisplayName, + this.storeId, + }); + + factory OperationFilterParams.empty() => const OperationFilterParams(); + + bool get isEmpty => + (searchTerm == null || searchTerm!.trim().isEmpty) && + dateRange == null && + detailType == null && + (subType == null || subType!.trim().isEmpty) && + categoryKey == null && + staffId == null && + storeId == null; + + bool get isNotEmpty => !isEmpty; + + /// Costruisce i filtri a partire da una categoria di target (es. clic da card obiettivo MNP, Calcio, ecc.) + factory OperationFilterParams.fromTargetCategory({ + required String categoryKey, + required String categoryLabel, + required TargetModel target, + String? staffId, + String? staffDisplayName, + }) { + OperationType? detailType; + String? subType; + + switch (categoryKey) { + case 'mnp': + detailType = OperationType.mnp; + break; + case 'unica': + detailType = OperationType.unica; + break; + case 'nip': + detailType = OperationType.nip; + break; + case 'al': + detailType = OperationType.al; + break; + case 'telepass': + detailType = OperationType.telepass; + break; + case 'fin': + detailType = OperationType.fin; + break; + case 'upselling': + detailType = OperationType.upselling; + break; + case 'cb': + detailType = OperationType.cb; + break; + case 'ricontatti': + detailType = OperationType.ricontatto; + break; + case 'calcio': + detailType = OperationType.entertainment; + subType = 'calcio'; + break; + case 'contenuti': + detailType = OperationType.entertainment; + break; + case 'business': + detailType = OperationType.business; + break; + case 'energiaTim': + case 'energiaAltri': + detailType = OperationType.energy; + break; + } + + return OperationFilterParams( + categoryKey: categoryKey, + categoryLabel: categoryLabel, + detailType: detailType, + subType: subType, + dateRange: DateTimeRange( + start: target.startDay, + end: target.endDay, + ), + storeId: target.storeId, + staffId: staffId, + staffDisplayName: staffDisplayName, + ); + } + + /// Estrae i parametri dai queryParameters di GoRouter + factory OperationFilterParams.fromQueryParams(Map query) { + if (query.isEmpty) return const OperationFilterParams(); + + DateTimeRange? range; + final startStr = query['startDate']; + final endStr = query['endDate']; + if (startStr != null && endStr != null) { + try { + final start = DateTime.parse(startStr); + final end = DateTime.parse(endStr); + range = DateTimeRange(start: start, end: end); + } catch (_) {} + } + + final typeStr = query['type'] ?? query['detailType']; + final opType = OperationType.fromValue(typeStr); + + return OperationFilterParams( + searchTerm: query['search'] ?? query['searchTerm'], + dateRange: range, + detailType: opType, + subType: query['subType'], + categoryKey: query['categoryKey'], + categoryLabel: query['categoryLabel'], + staffId: query['staffId'], + staffDisplayName: query['staffDisplayName'], + storeId: query['storeId'], + ); + } + + Map toQueryParams() { + final map = {}; + if (searchTerm != null && searchTerm!.isNotEmpty) { + map['search'] = searchTerm!; + } + if (dateRange != null) { + map['startDate'] = dateRange!.start.toIso8601String(); + map['endDate'] = dateRange!.end.toIso8601String(); + } + if (detailType != null) { + map['type'] = detailType!.value; + } + if (subType != null && subType!.isNotEmpty) { + map['subType'] = subType!; + } + if (categoryKey != null) { + map['categoryKey'] = categoryKey!; + } + if (categoryLabel != null) { + map['categoryLabel'] = categoryLabel!; + } + if (staffId != null) { + map['staffId'] = staffId!; + } + if (staffDisplayName != null) { + map['staffDisplayName'] = staffDisplayName!; + } + if (storeId != null) { + map['storeId'] = storeId!; + } + return map; + } + + OperationFilterParams copyWith({ + String? searchTerm, + DateTimeRange? dateRange, + OperationType? detailType, + String? subType, + String? categoryKey, + String? categoryLabel, + String? staffId, + String? staffDisplayName, + String? storeId, + bool clearSearch = false, + bool clearRange = false, + bool clearDetailType = false, + bool clearSubType = false, + bool clearCategory = false, + bool clearStaff = false, + bool clearStore = false, + }) { + return OperationFilterParams( + searchTerm: clearSearch ? null : (searchTerm ?? this.searchTerm), + dateRange: clearRange ? null : (dateRange ?? this.dateRange), + detailType: clearDetailType ? null : (detailType ?? this.detailType), + subType: clearSubType ? null : (subType ?? this.subType), + categoryKey: clearCategory ? null : (categoryKey ?? this.categoryKey), + categoryLabel: clearCategory ? null : (categoryLabel ?? this.categoryLabel), + staffId: clearStaff ? null : (staffId ?? this.staffId), + staffDisplayName: + clearStaff ? null : (staffDisplayName ?? this.staffDisplayName), + storeId: clearStore ? null : (storeId ?? this.storeId), + ); + } + + @override + List get props => [ + searchTerm, + dateRange, + detailType, + subType, + categoryKey, + categoryLabel, + staffId, + staffDisplayName, + storeId, + ]; +} diff --git a/lib/features/operations/ui/operation_list_screen.dart b/lib/features/operations/ui/operation_list_screen.dart index 4e9aa9d..d86a0d4 100644 --- a/lib/features/operations/ui/operation_list_screen.dart +++ b/lib/features/operations/ui/operation_list_screen.dart @@ -6,12 +6,16 @@ import 'package:flux/core/widgets/staff_selector_modal.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/operations/blocs/operation_list_cubit.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; import 'package:flux/features/operations/models/operation_model.dart'; import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:flux/features/operations/ui/widgets/operation_filter_sheet.dart'; import 'package:go_router/go_router.dart'; class OperationListScreen extends StatefulWidget { - const OperationListScreen({super.key}); + final OperationFilterParams? initialFilters; + + const OperationListScreen({super.key, this.initialFilters}); @override State createState() => _OperationListScreenState(); @@ -34,18 +38,43 @@ class _OperationListScreenState extends State { super.initState(); _scrollController.addListener(_onScroll); - // Primo caricamento: partiamo da pagina 1 - // (Il Cubit deciderà se fare il boot iniziale o se c'era già roba in cache) + // Primo caricamento: partiamo da pagina 1 o applichiamo filtri iniziali WidgetsBinding.instance.addPostFrameCallback((_) { - final isDesktop = MediaQuery.sizeOf(context).width >= 900; - if (isDesktop) { - context.read().loadSpecificPageDesktop(1); + final cubit = context.read(); + if (widget.initialFilters != null && widget.initialFilters!.isNotEmpty) { + if (widget.initialFilters!.searchTerm != null && + widget.initialFilters!.searchTerm!.isNotEmpty) { + _searchController.text = widget.initialFilters!.searchTerm!; + _showSearchBar = true; + } + cubit.applyFilterParams(widget.initialFilters!); } else { - context.read().loadNextPageMobile(refresh: true); + final isDesktop = MediaQuery.sizeOf(context).width >= 900; + if (isDesktop) { + cubit.loadSpecificPageDesktop(1); + } else { + cubit.loadNextPageMobile(refresh: true); + } } }); } + @override + void didUpdateWidget(covariant OperationListScreen oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.initialFilters != oldWidget.initialFilters && + widget.initialFilters != null) { + if (widget.initialFilters!.searchTerm != null && + widget.initialFilters!.searchTerm!.isNotEmpty) { + _searchController.text = widget.initialFilters!.searchTerm!; + _showSearchBar = true; + } + context + .read() + .applyFilterParams(widget.initialFilters!); + } + } + void _onScroll() { final isDesktop = MediaQuery.sizeOf(context).width >= 900; // 🥷 COMPORTAMENTO IBRIDO: Lo scroll infinito si attiva SOLO su mobile @@ -138,120 +167,72 @@ class _OperationListScreenState extends State { actions: [ IconButton( icon: Icon(_showSearchBar ? Icons.close : Icons.search), + tooltip: _showSearchBar ? 'Chiudi ricerca' : 'Cerca', onPressed: () { setState(() { _showSearchBar = !_showSearchBar; if (!_showSearchBar) { _debounce?.cancel(); _searchController.clear(); - context.read().clearFilters(); + context.read().updateFilters( + clearText: true, + ); } }); }, ), - if (!isDesktop) // Il pull-to-refresh c'è già su mobile, su desktop mettiamo un tasto manuale - IconButton( - icon: const Icon(Icons.filter_list), - onPressed: () { - // TODO: Bottone Filtri Avanzati (es. DateRange Picker) - }, - ), + BlocBuilder( + builder: (context, state) { + return IconButton( + icon: state.hasActiveFilters + ? Badge( + label: Text('${state.activeFiltersCount}'), + child: const Icon(Icons.filter_list), + ) + : const Icon(Icons.filter_list), + tooltip: 'Filtri avanzati', + onPressed: () => _openFilterModal(context, state), + ); + }, + ), + BlocBuilder( + builder: (context, state) { + if (!state.hasActiveFilters) { + return const SizedBox.shrink(); + } + return IconButton( + icon: const Icon(Icons.filter_alt_off), + tooltip: 'Azzera filtri', + onPressed: () { + _searchController.clear(); + setState(() => _showSearchBar = false); + context.read().clearFilters(); + }, + ); + }, + ), + IconButton( + icon: const Icon(Icons.refresh), + tooltip: 'Ricarica', + onPressed: () { + context.read().refreshCurrentPage(); + }, + ), ], ), // --- CORPO RESPONSIVO --- body: BlocBuilder( builder: (context, state) { - if (state.status == OperationListStatus.loading && - state.operations.isEmpty) { - return const Center(child: CircularProgressIndicator()); - } + return Column( + children: [ + // Barra orizzontale filtri attivi (se presenti) + _buildActiveFiltersBar(context, state), - if (state.operations.isEmpty) { - return Center( - child: Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - const Text("Nessuna pratica trovata."), - const SizedBox(height: 12), - ElevatedButton( - onPressed: () => isDesktop - ? context - .read() - .loadSpecificPageDesktop(1) - : context.read().loadNextPageMobile( - refresh: true, - ), - child: const Text("Ricarica"), - ), - ], + Expanded( + child: _buildBodyContent(context, state, isDesktop), ), - ); - } - - // 🥷 SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style - if (isDesktop) { - return Column( - children: [ - Expanded( - child: GridView.builder( - controller: _scrollController, - padding: const EdgeInsets.all(16), - gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( - maxCrossAxisExtent: - 420, // Larghezza bilanciata per le card su desktop - mainAxisExtent: - 185, // Altezza controllata per evitare buchi bianchi - crossAxisSpacing: 16, - mainAxisSpacing: 16, - ), - itemCount: state.operations.length, - itemBuilder: (context, index) { - final operation = state.operations[index]; - return _buildResponsiveCard(operation); - }, - ), - ), - _buildDesktopPaginationFooter( - state, - ), // La barra in fondo stile Gmail - ], - ); - } - - // 🥷 SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh - return RefreshIndicator( - onRefresh: () => context - .read() - .loadNextPageMobile(refresh: true), - child: ListView.builder( - controller: _scrollController, - padding: const EdgeInsets.only( - bottom: 80, - left: 8, - right: 8, - top: 8, - ), - itemCount: state.hasReachedMax - ? state.operations.length - : state.operations.length + 1, - itemBuilder: (context, index) { - if (index >= state.operations.length) { - return const Center( - child: Padding( - padding: EdgeInsets.all(16.0), - child: CircularProgressIndicator(strokeWidth: 2), - ), - ); - } - - final operation = state.operations[index]; - return Padding( - padding: const EdgeInsets.symmetric(vertical: 4.0), - child: _buildResponsiveCard(operation), - ); - }, - ), + ], ); }, ), @@ -273,6 +254,289 @@ class _OperationListScreenState extends State { ); } + void _openFilterModal(BuildContext context, OperationListState state) { + OperationFilterSheet.show( + context, + currentFilters: state.toFilterParams(), + onApply: (newParams) { + context.read().applyFilterParams(newParams); + }, + onReset: () { + _searchController.clear(); + setState(() => _showSearchBar = false); + context.read().clearFilters(); + }, + ); + } + + Widget _buildActiveFiltersBar( + BuildContext context, + OperationListState state, + ) { + if (!state.hasActiveFilters) return const SizedBox.shrink(); + + final theme = Theme.of(context); + final cubit = context.read(); + + return Container( + width: double.infinity, + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.25), + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6), + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + Padding( + padding: const EdgeInsets.only(right: 6.0), + child: ActionChip( + visualDensity: VisualDensity.compact, + avatar: const Icon( + Icons.filter_alt_off, + size: 14, + color: Colors.redAccent, + ), + label: const Text( + 'Azzera tutto', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.redAccent, + ), + ), + backgroundColor: Colors.redAccent.withValues(alpha: 0.08), + side: BorderSide( + color: Colors.redAccent.withValues(alpha: 0.3), + ), + onPressed: () { + _searchController.clear(); + setState(() => _showSearchBar = false); + cubit.clearFilters(); + }, + ), + ), + if (state.categoryLabel != null || state.detailType != null) ...[ + Padding( + padding: const EdgeInsets.only(right: 6.0), + child: Chip( + visualDensity: VisualDensity.compact, + avatar: Icon( + state.detailType?.icon ?? Icons.category, + size: 14, + color: state.detailType?.color ?? theme.colorScheme.primary, + ), + label: Text( + state.categoryLabel != null + ? 'Obiettivo: ${state.categoryLabel}' + : (state.subType != null && state.subType!.isNotEmpty + ? '${state.detailType!.shortLabel} (${state.subType})' + : state.detailType!.shortLabel), + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + deleteIcon: const Icon(Icons.close, size: 14), + onDeleted: () => cubit.updateFilters( + clearDetailType: true, + clearSubType: true, + clearCategory: true, + ), + ), + ), + ], + if (state.staffDisplayName != null || state.staffId != null) ...[ + Padding( + padding: const EdgeInsets.only(right: 6.0), + child: Chip( + visualDensity: VisualDensity.compact, + avatar: const Icon(Icons.person, size: 14), + label: Text( + 'Addetto: ${state.staffDisplayName ?? 'Selezionato'}', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + deleteIcon: const Icon(Icons.close, size: 14), + onDeleted: () => cubit.updateFilters(clearStaff: true), + ), + ), + ], + if (state.dateRange != null) ...[ + Padding( + padding: const EdgeInsets.only(right: 6.0), + child: Chip( + visualDensity: VisualDensity.compact, + avatar: const Icon(Icons.date_range, size: 14), + label: Text( + '${_formatDate(state.dateRange!.start)} - ${_formatDate(state.dateRange!.end)}', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + deleteIcon: const Icon(Icons.close, size: 14), + onDeleted: () => cubit.updateFilters(clearRange: true), + ), + ), + ], + if (state.searchTerm != null && + state.searchTerm!.trim().isNotEmpty) ...[ + Padding( + padding: const EdgeInsets.only(right: 6.0), + child: Chip( + visualDensity: VisualDensity.compact, + avatar: const Icon(Icons.search, size: 14), + label: Text( + '"${state.searchTerm}"', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + deleteIcon: const Icon(Icons.close, size: 14), + onDeleted: () { + _searchController.clear(); + cubit.updateFilters(clearText: true); + }, + ), + ), + ], + ], + ), + ), + ); + } + + Widget _buildBodyContent( + BuildContext context, + OperationListState state, + bool isDesktop, + ) { + if (state.status == OperationListStatus.loading && + state.operations.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + + if (state.operations.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon( + state.hasActiveFilters + ? Icons.filter_list_off + : Icons.inbox_outlined, + size: 48, + color: Colors.grey.shade400, + ), + const SizedBox(height: 12), + Text( + state.hasActiveFilters + ? 'Nessuna operazione trovata con i filtri attuali.' + : 'Nessuna pratica trovata.', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 15, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 12), + if (state.hasActiveFilters) + ElevatedButton.icon( + icon: const Icon(Icons.filter_alt_off, size: 18), + label: const Text('Azzera filtri'), + onPressed: () { + _searchController.clear(); + setState(() => _showSearchBar = false); + context.read().clearFilters(); + }, + ) + else + ElevatedButton( + onPressed: () => isDesktop + ? context + .read() + .loadSpecificPageDesktop(1) + : context.read().loadNextPageMobile( + refresh: true, + ), + child: const Text('Ricarica'), + ), + ], + ), + ), + ); + } + + // SCENARIO DESKTOP: Griglia + Barra di Paginazione Gmail-Style + if (isDesktop) { + return Column( + children: [ + Expanded( + child: GridView.builder( + controller: _scrollController, + padding: const EdgeInsets.all(16), + gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent( + maxCrossAxisExtent: 420, + mainAxisExtent: 185, + crossAxisSpacing: 16, + mainAxisSpacing: 16, + ), + itemCount: state.operations.length, + itemBuilder: (context, index) { + final operation = state.operations[index]; + return _buildResponsiveCard(operation); + }, + ), + ), + _buildDesktopPaginationFooter(state), + ], + ); + } + + // SCENARIO MOBILE: ListView con Infinite Scroll e Pull-to-Refresh + return RefreshIndicator( + onRefresh: () => context + .read() + .loadNextPageMobile(refresh: true), + child: ListView.builder( + controller: _scrollController, + padding: const EdgeInsets.only( + bottom: 80, + left: 8, + right: 8, + top: 8, + ), + itemCount: state.hasReachedMax + ? state.operations.length + : state.operations.length + 1, + itemBuilder: (context, index) { + if (index >= state.operations.length) { + return const Center( + child: Padding( + padding: EdgeInsets.all(16.0), + child: CircularProgressIndicator(strokeWidth: 2), + ), + ); + } + + final operation = state.operations[index]; + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: _buildResponsiveCard(operation), + ); + }, + ), + ); + } + + String _formatDate(DateTime dt) { + return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}'; + } + // --- COSTRUZIONE DELLA COMPONENTISTICA DETTAGLIATA --- Widget _buildResponsiveCard(OperationModel operation) { diff --git a/lib/features/operations/ui/widgets/operation_filter_sheet.dart b/lib/features/operations/ui/widgets/operation_filter_sheet.dart new file mode 100644 index 0000000..b489a2c --- /dev/null +++ b/lib/features/operations/ui/widgets/operation_filter_sheet.dart @@ -0,0 +1,649 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/master_data/staff/blocs/staff_cubit.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; + +/// BottomSheet per impostare i filtri avanzati della lista operazioni +class OperationFilterSheet extends StatefulWidget { + final OperationFilterParams currentFilters; + final ValueChanged onApply; + final VoidCallback onReset; + + const OperationFilterSheet({ + super.key, + required this.currentFilters, + required this.onApply, + required this.onReset, + }); + + static Future show( + BuildContext context, { + required OperationFilterParams currentFilters, + required ValueChanged onApply, + required VoidCallback onReset, + }) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + backgroundColor: Colors.transparent, + builder: (_) => OperationFilterSheet( + currentFilters: currentFilters, + onApply: onApply, + onReset: onReset, + ), + ); + } + + @override + State createState() => _OperationFilterSheetState(); +} + +class _OperationFilterSheetState extends State { + OperationType? _selectedType; + late TextEditingController _subTypeController; + StaffMemberModel? _selectedStaff; + DateTimeRange? _selectedDateRange; + + @override + void initState() { + super.initState(); + _selectedType = widget.currentFilters.detailType; + _subTypeController = TextEditingController( + text: widget.currentFilters.subType ?? '', + ); + _selectedDateRange = widget.currentFilters.dateRange; + + // Inizializza l'addetto se presente + if (widget.currentFilters.staffId != null) { + final staffState = context.read().state; + final staffList = staffState.storeStaff.isNotEmpty + ? staffState.storeStaff + : staffState.allStaff; + for (final s in staffList) { + if (s.id == widget.currentFilters.staffId) { + _selectedStaff = s; + break; + } + } + } + } + + @override + void dispose() { + _subTypeController.dispose(); + super.dispose(); + } + + void _setDatePreset(String preset) { + final now = DateTime.now(); + switch (preset) { + case 'today': + final start = DateTime(now.year, now.month, now.day, 0, 0, 0); + final end = DateTime(now.year, now.month, now.day, 23, 59, 59); + setState(() => _selectedDateRange = DateTimeRange(start: start, end: end)); + break; + case 'last7': + final start = DateTime(now.year, now.month, now.day - 6, 0, 0, 0); + final end = DateTime(now.year, now.month, now.day, 23, 59, 59); + setState(() => _selectedDateRange = DateTimeRange(start: start, end: end)); + break; + case 'thisMonth': + final start = DateTime(now.year, now.month, 1, 0, 0, 0); + final end = DateTime(now.year, now.month + 1, 0, 23, 59, 59); + setState(() => _selectedDateRange = DateTimeRange(start: start, end: end)); + break; + case 'lastMonth': + final start = DateTime(now.year, now.month - 1, 1, 0, 0, 0); + final end = DateTime(now.year, now.month, 0, 23, 59, 59); + setState(() => _selectedDateRange = DateTimeRange(start: start, end: end)); + break; + case 'all': + setState(() => _selectedDateRange = null); + break; + } + } + + Future _pickCustomDateRange() async { + final now = DateTime.now(); + final picked = await showDateRangePicker( + context: context, + initialDateRange: _selectedDateRange ?? + DateTimeRange( + start: DateTime(now.year, now.month, 1), + end: DateTime(now.year, now.month, now.day), + ), + firstDate: DateTime(2020), + lastDate: DateTime(now.year + 5), + ); + + if (picked != null) { + setState(() { + _selectedDateRange = DateTimeRange( + start: DateTime( + picked.start.year, + picked.start.month, + picked.start.day, + 0, + 0, + 0, + ), + end: DateTime( + picked.end.year, + picked.end.month, + picked.end.day, + 23, + 59, + 59, + ), + ); + }); + } + } + + void _apply() { + final subText = _subTypeController.text.trim(); + final params = widget.currentFilters.copyWith( + detailType: _selectedType, + subType: subText.isNotEmpty ? subText : null, + staffId: _selectedStaff?.id, + staffDisplayName: _selectedStaff?.name, + dateRange: _selectedDateRange, + clearDetailType: _selectedType == null, + clearSubType: subText.isEmpty, + clearStaff: _selectedStaff == null, + clearRange: _selectedDateRange == null, + // Se l'utente ha modificato manualmente tipo o sottotipo, svuotiamo categoryKey specifica + clearCategory: _selectedType != widget.currentFilters.detailType, + ); + + widget.onApply(params); + Navigator.of(context).pop(); + } + + void _reset() { + widget.onReset(); + Navigator.of(context).pop(); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final mediaQuery = MediaQuery.of(context); + + return DraggableScrollableSheet( + initialChildSize: 0.85, + minChildSize: 0.5, + maxChildSize: 0.95, + expand: false, + builder: (_, scrollController) { + return Container( + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: const BorderRadius.vertical(top: Radius.circular(24)), + ), + child: Column( + children: [ + // Maniglia top + Center( + child: Container( + width: 40, + height: 4, + margin: const EdgeInsets.only(top: 12, bottom: 8), + decoration: BoxDecoration( + color: theme.dividerColor, + borderRadius: BorderRadius.circular(2), + ), + ), + ), + + // Header + Padding( + padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 8), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + Icon( + Icons.tune, + color: theme.colorScheme.primary, + size: 22, + ), + const SizedBox(width: 8), + Text( + 'Filtri Avanzati', + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ], + ), + TextButton.icon( + onPressed: _reset, + icon: const Icon(Icons.filter_alt_off, size: 18), + label: const Text('Azzera tutto'), + style: TextButton.styleFrom( + foregroundColor: Colors.redAccent, + ), + ), + ], + ), + ), + const Divider(height: 1), + + // Corpo con i filtri + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.all(20), + children: [ + // 1. TIPO SERVIZIO / DETTAGLIO + _buildSectionTitle( + theme, + title: 'Tipo di Servizio / Dettaglio', + icon: Icons.category_outlined, + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Tutti'), + selected: _selectedType == null, + onSelected: (selected) { + if (selected) { + setState(() { + _selectedType = null; + _subTypeController.clear(); + }); + } + }, + ), + ...OperationType.values.map((type) { + final isSelected = _selectedType == type; + return ChoiceChip( + avatar: Icon( + type.icon, + size: 16, + color: isSelected ? Colors.white : type.color, + ), + label: Text(type.shortLabel), + selected: isSelected, + selectedColor: type.color, + labelStyle: TextStyle( + color: isSelected ? Colors.white : null, + fontWeight: + isSelected ? FontWeight.bold : FontWeight.normal, + ), + onSelected: (selected) { + setState(() { + _selectedType = selected ? type : null; + if (!selected) _subTypeController.clear(); + }); + }, + ); + }), + ], + ), + const SizedBox(height: 24), + + // 2. SOTTOTIPO / SPECIFICA (se applicabile) + if (_selectedType != null) ...[ + _buildSectionTitle( + theme, + title: 'Sottotipo / Offerta specifica', + icon: Icons.subdirectory_arrow_right, + ), + const SizedBox(height: 10), + if (_selectedType == OperationType.entertainment) ...[ + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Tutti i contenuti'), + selected: _subTypeController.text.isEmpty, + onSelected: (sel) { + if (sel) { + setState(() => _subTypeController.clear()); + } + }, + ), + ...EntertainmentSubtypes.all.map((sub) { + final isSel = _subTypeController.text + .trim() + .toLowerCase() == + sub.toLowerCase(); + return ChoiceChip( + avatar: sub == EntertainmentSubtypes.calcio + ? const Icon(Icons.sports_soccer, size: 15) + : (sub == EntertainmentSubtypes.cinemaTv + ? const Icon(Icons.movie_outlined, size: 15) + : null), + label: Text(sub), + selected: isSel, + onSelected: (sel) { + setState(() { + _subTypeController.text = sel ? sub : ''; + }); + }, + ); + }), + ], + ), + const SizedBox(height: 10), + ] else if (_selectedType == OperationType.energy) ...[ + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Tutte le forniture'), + selected: _subTypeController.text.isEmpty, + onSelected: (sel) { + if (sel) { + setState(() => _subTypeController.clear()); + } + }, + ), + ...EnergySubtypes.all.map((sub) { + final isSel = _subTypeController.text + .trim() + .toLowerCase() == + sub.toLowerCase(); + return ChoiceChip( + label: Text(sub), + selected: isSel, + onSelected: (sel) { + setState(() { + _subTypeController.text = sel ? sub : ''; + }); + }, + ); + }), + ], + ), + const SizedBox(height: 10), + ] else if (_selectedType == OperationType.ricontatto) ...[ + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Tutti i ricontatti'), + selected: _subTypeController.text.isEmpty, + onSelected: (sel) { + if (sel) { + setState(() => _subTypeController.clear()); + } + }, + ), + ...RicontattoSubtypes.all.map((sub) { + final isSel = _subTypeController.text + .trim() + .toLowerCase() == + sub.toLowerCase(); + return ChoiceChip( + label: Text(sub), + selected: isSel, + onSelected: (sel) { + setState(() { + _subTypeController.text = sel ? sub : ''; + }); + }, + ); + }), + ], + ), + const SizedBox(height: 10), + ], + TextField( + controller: _subTypeController, + decoration: InputDecoration( + labelText: 'Filtro testuale sottotipo (opzionale)', + hintText: 'Es. DAZN, TIMVISION, Luce...', + prefixIcon: const Icon(Icons.search, size: 18), + suffixIcon: _subTypeController.text.isNotEmpty + ? IconButton( + icon: const Icon(Icons.clear, size: 18), + onPressed: () => setState( + () => _subTypeController.clear(), + ), + ) + : null, + border: OutlineInputBorder( + borderRadius: BorderRadius.circular(10), + ), + contentPadding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 10, + ), + ), + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 24), + ], + + // 3. COLLABORATORE / ADDETTO + _buildSectionTitle( + theme, + title: 'Collaboratore / Addetto', + icon: Icons.person_outline, + ), + const SizedBox(height: 10), + BlocBuilder( + builder: (context, staffState) { + final rawList = staffState.storeStaff.isNotEmpty + ? staffState.storeStaff + : staffState.allStaff; + final activeStaff = + rawList.where((s) => s.isActive).toList(); + + return Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ChoiceChip( + label: const Text('Tutti gli addetti'), + selected: _selectedStaff == null, + onSelected: (sel) { + if (sel) setState(() => _selectedStaff = null); + }, + ), + ...activeStaff.map((staff) { + final isSel = _selectedStaff?.id == staff.id; + return ChoiceChip( + avatar: CircleAvatar( + radius: 10, + backgroundColor: isSel + ? Colors.white + : theme.colorScheme.primary.withValues( + alpha: 0.2, + ), + child: Text( + staff.name.isNotEmpty + ? staff.name[0].toUpperCase() + : '?', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: isSel + ? theme.colorScheme.primary + : theme.colorScheme.primary, + ), + ), + ), + label: Text(staff.name), + selected: isSel, + onSelected: (sel) { + setState(() { + _selectedStaff = sel ? staff : null; + }); + }, + ); + }), + ], + ); + }, + ), + const SizedBox(height: 24), + + // 4. RANGE DATE / PERIODO + _buildSectionTitle( + theme, + title: 'Periodo / Data Creazione', + icon: Icons.calendar_month_outlined, + ), + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + ActionChip( + avatar: const Icon(Icons.all_inclusive, size: 16), + label: const Text('Sempre'), + backgroundColor: _selectedDateRange == null + ? theme.colorScheme.primaryContainer + : null, + onPressed: () => _setDatePreset('all'), + ), + ActionChip( + label: const Text('Oggi'), + onPressed: () => _setDatePreset('today'), + ), + ActionChip( + label: const Text('Ultimi 7 gg'), + onPressed: () => _setDatePreset('last7'), + ), + ActionChip( + label: const Text('Questo mese'), + onPressed: () => _setDatePreset('thisMonth'), + ), + ActionChip( + label: const Text('Mese scorso'), + onPressed: () => _setDatePreset('lastMonth'), + ), + ActionChip( + avatar: const Icon(Icons.date_range, size: 16), + label: const Text('Personalizzato...'), + onPressed: _pickCustomDateRange, + ), + ], + ), + if (_selectedDateRange != null) ...[ + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 10, + ), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer + .withValues(alpha: 0.35), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: theme.colorScheme.primary.withValues( + alpha: 0.3, + ), + ), + ), + child: Row( + children: [ + Icon( + Icons.check_circle_outline, + size: 18, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Dal ${_formatDate(_selectedDateRange!.start)} al ${_formatDate(_selectedDateRange!.end)}', + style: TextStyle( + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurface, + fontSize: 13, + ), + ), + ), + IconButton( + icon: const Icon(Icons.close, size: 18), + onPressed: () => + setState(() => _selectedDateRange = null), + tooltip: 'Rimuovi filtro data', + ), + ], + ), + ), + ], + ], + ), + ), + + // Footer con bottoni di conferma + Container( + padding: EdgeInsets.fromLTRB( + 20, + 12, + 20, + 12 + mediaQuery.viewPadding.bottom, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + border: Border( + top: BorderSide(color: theme.dividerColor.withValues(alpha: 0.5)), + ), + ), + child: Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Annulla'), + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: ElevatedButton.icon( + icon: const Icon(Icons.done), + label: const Text('Applica Filtri'), + onPressed: _apply, + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); + } + + Widget _buildSectionTitle( + ThemeData theme, { + required String title, + required IconData icon, + }) { + return Row( + children: [ + Icon(icon, size: 18, color: theme.colorScheme.primary), + const SizedBox(width: 6), + Text( + title, + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurface, + ), + ), + ], + ); + } + + String _formatDate(DateTime dt) { + return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}'; + } +} diff --git a/lib/features/targets/ui/target_detail_screen.dart b/lib/features/targets/ui/target_detail_screen.dart index f949db2..b9614b2 100644 --- a/lib/features/targets/ui/target_detail_screen.dart +++ b/lib/features/targets/ui/target_detail_screen.dart @@ -1,6 +1,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/routes/routes.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; import 'package:flux/features/targets/blocs/target_detail_cubit.dart'; import 'package:flux/features/targets/blocs/target_detail_state.dart'; import 'package:flux/features/targets/models/target_model.dart'; @@ -453,6 +454,25 @@ class _TargetDetailScreenState extends State ); } + void _navigateToOperationsForCategory( + CategoryProgress cat, { + String? staffId, + String? staffName, + }) { + final params = OperationFilterParams.fromTargetCategory( + categoryKey: cat.key, + categoryLabel: cat.label, + target: widget.target, + staffId: staffId, + staffDisplayName: staffName, + ); + + context.pushNamed( + Routes.operations, + extra: params, + ); + } + Widget _buildCategoryCard( ThemeData theme, CategoryProgress cat, @@ -492,98 +512,142 @@ class _TargetDetailScreenState extends State ), child: ClipRRect( borderRadius: BorderRadius.circular(16), - child: Container( - // Bordo laterale sinistro spesso 6px: VERDE, VERDINO, ROSA, ROSSO! - decoration: BoxDecoration( - border: Border( - left: BorderSide( - color: hasTargets ? pacingTheme.primary : Colors.grey.shade400, - width: 6, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(16), + onTap: () => _navigateToOperationsForCategory(cat), + child: Container( + // Bordo laterale sinistro spesso 6px: VERDE, VERDINO, ROSA, ROSSO! + decoration: BoxDecoration( + border: Border( + left: BorderSide( + color: hasTargets ? pacingTheme.primary : Colors.grey.shade400, + width: 6, + ), + ), ), - ), - ), - padding: const EdgeInsets.all(16.0), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // Intestazione: Categoria + Status Badge Cromatico + Volume ENORME - Row( - crossAxisAlignment: CrossAxisAlignment.center, + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, children: [ - Expanded( - child: Wrap( - crossAxisAlignment: WrapCrossAlignment.center, - spacing: 10, - runSpacing: 6, - children: [ - Text( - cat.label, - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + // Intestazione: Categoria + Status Badge Cromatico + Volume ENORME + Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded( + child: Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 10, + runSpacing: 6, + children: [ + Text( + cat.label, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: pacingTheme.background, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: pacingTheme.border, width: 1.2), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(pacingTheme.icon, size: 14, color: pacingTheme.text), + const SizedBox(width: 5), + Text( + statusLabel, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: pacingTheme.text, + ), + ), + ], + ), + ), + ], ), - Container( - padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), - decoration: BoxDecoration( - color: pacingTheme.background, - borderRadius: BorderRadius.circular(8), - border: Border.all(color: pacingTheme.border, width: 1.2), - ), - child: Row( + ), + + // Realizzato vs S1 / S2: GRANDE e BEN VISIBILE + Tasto Apri + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Row( mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, children: [ - Icon(pacingTheme.icon, size: 14, color: pacingTheme.text), - const SizedBox(width: 5), Text( - statusLabel, + '${cat.actualPieces}', style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.bold, - color: pacingTheme.text, + fontSize: 24, + fontWeight: FontWeight.w900, + color: isDoneS1 ? const Color(0xFF15803D) : theme.colorScheme.onSurface, ), ), + Text( + ' / ${cat.targetS1}', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + if (cat.targetS2 > 0) ...[ + const SizedBox(width: 6), + Text( + '(Sfida: ${cat.targetS2})', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: isDoneS2 ? const Color(0xFF15803D) : Colors.purple.shade700, + ), + ), + ], ], ), - ), - ], - ), - ), - - // Realizzato vs S1 / S2: GRANDE e BEN VISIBILE - Row( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.baseline, - textBaseline: TextBaseline.alphabetic, - children: [ - Text( - '${cat.actualPieces}', - style: TextStyle( - fontSize: 24, - fontWeight: FontWeight.w900, - color: isDoneS1 ? const Color(0xFF15803D) : theme.colorScheme.onSurface, - ), - ), - Text( - ' / ${cat.targetS1}', - style: TextStyle( - fontSize: 15, - fontWeight: FontWeight.bold, - color: theme.colorScheme.onSurfaceVariant, - ), - ), - if (cat.targetS2 > 0) ...[ - const SizedBox(width: 6), - Text( - '(Sfida: ${cat.targetS2})', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - color: isDoneS2 ? const Color(0xFF15803D) : Colors.purple.shade700, + const SizedBox(width: 10), + Tooltip( + message: 'Vedi operazioni (${cat.actualPieces})', + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 6, + ), + decoration: BoxDecoration( + color: pacingTheme.primary.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: pacingTheme.primary.withValues(alpha: 0.3), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.list_alt, + size: 15, + color: pacingTheme.primary, + ), + const SizedBox(width: 4), + Icon( + Icons.arrow_forward_ios, + size: 11, + color: pacingTheme.primary, + ), + ], + ), + ), ), - ), - ], + ], + ), ], ), - ], - ), const SizedBox(height: 12), // Barra di avanzamento @@ -689,7 +753,9 @@ class _TargetDetailScreenState extends State ), ), ), - ); + ), + ), +); } // ========================================== @@ -969,7 +1035,12 @@ class _TargetDetailScreenState extends State ), const SizedBox(height: 10), ...sp.categories.values.where((c) => c.targetS1 > 0 || c.targetS2 > 0).map((c) { - return _buildStaffCategoryRow(theme, c); + return _buildStaffCategoryRow( + theme, + c, + staffId: it.staffId, + staffName: staffName, + ); }), ], ), @@ -988,14 +1059,18 @@ class _TargetDetailScreenState extends State ); } - Widget _buildStaffCategoryRow(ThemeData theme, CategoryProgress c) { + Widget _buildStaffCategoryRow( + ThemeData theme, + CategoryProgress c, { + String? staffId, + String? staffName, + }) { final isDoneS1 = c.actualPieces >= c.targetS1; final isDoneS2 = c.targetS2 > 0 && c.actualPieces >= c.targetS2; final pacingTheme = PacingTheme.of(c.status); return Container( margin: const EdgeInsets.only(bottom: 8.0), - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), decoration: BoxDecoration( color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.3), borderRadius: BorderRadius.circular(10), @@ -1003,67 +1078,98 @@ class _TargetDetailScreenState extends State left: BorderSide(color: pacingTheme.primary, width: 4), ), ), - child: Row( - children: [ - Expanded( - flex: 3, - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, + child: Material( + color: Colors.transparent, + child: InkWell( + borderRadius: BorderRadius.circular(10), + onTap: () => _navigateToOperationsForCategory( + c, + staffId: staffId, + staffName: staffName, + ), + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + child: Row( children: [ - Text( - c.label, - style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold), - ), - Text( - pacingTheme.label, - style: TextStyle( - fontSize: 10, - fontWeight: FontWeight.w600, - color: pacingTheme.primary, + Expanded( + flex: 3, + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + c.label, + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + Text( + pacingTheme.label, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w600, + color: pacingTheme.primary, + ), + ), + ], ), ), + Expanded( + flex: 2, + child: Text( + '${c.actualPieces} / ${c.targetS1}${c.targetS2 > 0 ? ' (S2: ${c.targetS2})' : ''}', + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + ), + Expanded( + flex: 2, + child: Text( + 'Med: ${c.actualDailyRate.toStringAsFixed(1)}/gg', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + Expanded( + flex: 2, + child: Container( + padding: + const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: pacingTheme.background, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: pacingTheme.border), + ), + child: Text( + isDoneS2 + ? 'S2 OK 🚀' + : (isDoneS1 + ? 'S1 OK 🎉' + : 'Req: ${c.requiredDailyRateS1.toStringAsFixed(1)}/gg'), + textAlign: TextAlign.center, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: pacingTheme.text, + ), + ), + ), + ), + const SizedBox(width: 6), + Icon( + Icons.arrow_forward_ios, + size: 12, + color: Colors.grey.shade500, + ), ], ), ), - Expanded( - flex: 2, - child: Text( - '${c.actualPieces} / ${c.targetS1}${c.targetS2 > 0 ? ' (S2: ${c.targetS2})' : ''}', - style: const TextStyle(fontSize: 13, fontWeight: FontWeight.bold), - ), - ), - Expanded( - flex: 2, - child: Text( - 'Med: ${c.actualDailyRate.toStringAsFixed(1)}/gg', - style: TextStyle(fontSize: 12, color: theme.colorScheme.primary, fontWeight: FontWeight.bold), - ), - ), - Expanded( - flex: 2, - child: Container( - padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), - decoration: BoxDecoration( - color: pacingTheme.background, - borderRadius: BorderRadius.circular(6), - border: Border.all(color: pacingTheme.border), - ), - child: Text( - isDoneS2 - ? 'S2 OK 🚀' - : (isDoneS1 - ? 'S1 OK 🎉' - : 'Req: ${c.requiredDailyRateS1.toStringAsFixed(1)}/gg'), - textAlign: TextAlign.center, - style: TextStyle( - fontSize: 11, - fontWeight: FontWeight.bold, - color: pacingTheme.text, - ), - ), - ), - ), - ], + ), ), ); } diff --git a/pubspec.yaml b/pubspec.yaml index 0213da1..3ced0ea 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.5.6+90 +version: 2.5.7+91 environment: sdk: ^3.11.3 diff --git a/test/features/operations/blocs/operation_list_filter_test.dart b/test/features/operations/blocs/operation_list_filter_test.dart new file mode 100644 index 0000000..003ab23 --- /dev/null +++ b/test/features/operations/blocs/operation_list_filter_test.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/operations/blocs/operation_list_cubit.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; + +void main() { + group('OperationListState filter properties', () { + test('hasActiveFilters returns false on default initial state', () { + const state = OperationListState(); + expect(state.hasActiveFilters, isFalse); + expect(state.activeFiltersCount, 0); + }); + + test('hasActiveFilters returns true when any filter is set', () { + const withSearch = OperationListState(searchTerm: 'Mario'); + expect(withSearch.hasActiveFilters, isTrue); + expect(withSearch.activeFiltersCount, 1); + + final withDate = OperationListState( + dateRange: DateTimeRange( + start: DateTime(2026, 11, 1), + end: DateTime(2026, 11, 30), + ), + ); + expect(withDate.hasActiveFilters, isTrue); + expect(withDate.activeFiltersCount, 1); + + const withType = OperationListState(detailType: OperationType.telepass); + expect(withType.hasActiveFilters, isTrue); + expect(withType.activeFiltersCount, 1); + + const withStaff = OperationListState( + staffId: 'staff-1', + staffDisplayName: 'Marco', + ); + expect(withStaff.hasActiveFilters, isTrue); + expect(withStaff.activeFiltersCount, 1); + + const withMultiple = OperationListState( + searchTerm: 'Test', + detailType: OperationType.mnp, + staffId: 'staff-1', + ); + expect(withMultiple.hasActiveFilters, isTrue); + expect(withMultiple.activeFiltersCount, 3); + }); + + test('toFilterParams accurately exports state into OperationFilterParams', () { + final state = OperationListState( + searchTerm: 'Cliente', + detailType: OperationType.mnp, + subType: 'Vodafone', + staffId: 'staff-42', + staffDisplayName: 'Alessandro', + categoryKey: 'mnp', + categoryLabel: 'MNP', + storeId: 'store-1', + dateRange: DateTimeRange( + start: DateTime(2026, 11, 1), + end: DateTime(2026, 11, 30), + ), + ); + + final OperationFilterParams params = state.toFilterParams(); + expect(params.searchTerm, 'Cliente'); + expect(params.detailType, OperationType.mnp); + expect(params.subType, 'Vodafone'); + expect(params.staffId, 'staff-42'); + expect(params.staffDisplayName, 'Alessandro'); + expect(params.categoryKey, 'mnp'); + expect(params.storeId, 'store-1'); + expect(params.dateRange, state.dateRange); + }); + + test('copyWith can clear individual filters with explicit callbacks', () { + final state = OperationListState( + searchTerm: 'Test', + detailType: OperationType.mnp, + staffId: 'staff-1', + ); + + final cleared = state.copyWith( + searchTerm: () => null, + detailType: () => null, + ); + + expect(cleared.searchTerm, isNull); + expect(cleared.detailType, isNull); + expect(cleared.staffId, 'staff-1'); + expect(cleared.hasActiveFilters, isTrue); + expect(cleared.activeFiltersCount, 1); + }); + }); +} diff --git a/test/features/operations/models/operation_filter_params_test.dart b/test/features/operations/models/operation_filter_params_test.dart new file mode 100644 index 0000000..6fb1094 --- /dev/null +++ b/test/features/operations/models/operation_filter_params_test.dart @@ -0,0 +1,143 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/features/operations/models/operation_filter_params.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:flux/features/targets/models/target_model.dart'; + +void main() { + group('OperationFilterParams Tests', () { + test('empty() produces an empty params instance', () { + final empty = OperationFilterParams.empty(); + expect(empty.isEmpty, isTrue); + expect(empty.isNotEmpty, isFalse); + expect(empty.detailType, isNull); + expect(empty.staffId, isNull); + expect(empty.dateRange, isNull); + expect(empty.searchTerm, isNull); + }); + + test('fromTargetCategory maps MNP category accurately', () { + final target = TargetModel.empty( + companyId: 'comp-1', + storeId: 'store-1', + startDay: DateTime(2026, 11, 1), + endDay: DateTime(2026, 11, 30, 23, 59, 59), + ); + + final params = OperationFilterParams.fromTargetCategory( + categoryKey: 'mnp', + categoryLabel: 'MNP', + target: target, + staffId: 'staff-99', + staffDisplayName: 'Marco', + ); + + expect(params.categoryKey, 'mnp'); + expect(params.categoryLabel, 'MNP'); + expect(params.detailType, OperationType.mnp); + expect(params.subType, isNull); + expect(params.storeId, 'store-1'); + expect(params.staffId, 'staff-99'); + expect(params.staffDisplayName, 'Marco'); + expect(params.dateRange?.start, target.startDay); + expect(params.dateRange?.end, target.endDay); + expect(params.isNotEmpty, isTrue); + }); + + test('fromTargetCategory maps Calcio category to entertainment with calcio subtype', () { + final target = TargetModel.empty( + companyId: 'comp-1', + storeId: 'store-1', + ); + + final params = OperationFilterParams.fromTargetCategory( + categoryKey: 'calcio', + categoryLabel: 'Calcio', + target: target, + ); + + expect(params.categoryKey, 'calcio'); + expect(params.detailType, OperationType.entertainment); + expect(params.subType, 'calcio'); + }); + + test('fromTargetCategory maps Contenuti, Unica, Telepass, etc.', () { + final target = TargetModel.empty(); + + final contenuti = OperationFilterParams.fromTargetCategory( + categoryKey: 'contenuti', + categoryLabel: 'Contenuti', + target: target, + ); + expect(contenuti.detailType, OperationType.entertainment); + + final unica = OperationFilterParams.fromTargetCategory( + categoryKey: 'unica', + categoryLabel: 'TIM Unica', + target: target, + ); + expect(unica.detailType, OperationType.unica); + + final telepass = OperationFilterParams.fromTargetCategory( + categoryKey: 'telepass', + categoryLabel: 'Telepass', + target: target, + ); + expect(telepass.detailType, OperationType.telepass); + + final energy = OperationFilterParams.fromTargetCategory( + categoryKey: 'energiaTim', + categoryLabel: 'Energia TIM', + target: target, + ); + expect(energy.detailType, OperationType.energy); + }); + + test('toQueryParams and fromQueryParams serialization round-trip', () { + final original = OperationFilterParams( + searchTerm: 'Mario Rossi', + dateRange: DateTimeRange( + start: DateTime(2026, 11, 1), + end: DateTime(2026, 11, 30), + ), + detailType: OperationType.telepass, + subType: 'Base', + categoryKey: 'telepass', + categoryLabel: 'Telepass', + staffId: 'staff-1', + staffDisplayName: 'Luca', + storeId: 'store-1', + ); + + final query = original.toQueryParams(); + final reconstructed = OperationFilterParams.fromQueryParams(query); + + expect(reconstructed.searchTerm, original.searchTerm); + expect(reconstructed.detailType, original.detailType); + expect(reconstructed.subType, original.subType); + expect(reconstructed.categoryKey, original.categoryKey); + expect(reconstructed.staffId, original.staffId); + expect(reconstructed.staffDisplayName, original.staffDisplayName); + expect(reconstructed.storeId, original.storeId); + expect(reconstructed.dateRange?.start, original.dateRange?.start); + expect(reconstructed.dateRange?.end, original.dateRange?.end); + }); + + test('copyWith properly updates and clears individual filters', () { + final initial = OperationFilterParams( + searchTerm: 'Test', + detailType: OperationType.mnp, + staffId: 's-1', + ); + + final updated = initial.copyWith( + searchTerm: 'New Test', + clearDetailType: true, + ); + + expect(updated.searchTerm, 'New Test'); + expect(updated.detailType, isNull); + expect(updated.staffId, 's-1'); + }); + }); +}