diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 56abf3d..8868f6f 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -65,6 +65,8 @@ import 'package:flux/features/targets/blocs/target_form_cubit.dart'; import 'package:flux/features/targets/blocs/target_list_cubit.dart'; import 'package:flux/features/targets/data/targets_repository.dart'; import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/blocs/target_detail_cubit.dart'; +import 'package:flux/features/targets/ui/target_detail_screen.dart'; import 'package:flux/features/targets/ui/target_form_screen.dart'; import 'package:flux/features/targets/ui/target_list_screen.dart'; import 'package:flux/features/master_data/staff/data/staff_repository.dart'; @@ -344,6 +346,7 @@ class AppRouter { create: (context) => TargetFormCubit( targetsRepository: sl(), staffRepository: sl(), + staffCubit: context.read(), )..init( initialTarget: existingTarget, companyId: companyId, @@ -353,6 +356,17 @@ class AppRouter { ); }, ), + GoRoute( + path: '/targets/detail', + name: Routes.targetDetail, + builder: (context, state) { + final target = state.extra as TargetModel; + return BlocProvider( + create: (context) => TargetDetailCubit(target: target)..init(), + child: TargetDetailScreen(target: target), + ); + }, + ), GoRoute( path: '/providers/form', name: Routes.providerForm, diff --git a/lib/core/utils/working_days_helper.dart b/lib/core/utils/working_days_helper.dart new file mode 100644 index 0000000..2aeda8a --- /dev/null +++ b/lib/core/utils/working_days_helper.dart @@ -0,0 +1,134 @@ +/// Enum con le festività nazionali italiane +enum ItalianHoliday { + capodanno(day: 1, month: 1, label: 'Capodanno'), + epifania(day: 6, month: 1, label: 'Epifania'), + liberazione(day: 25, month: 4, label: 'Festa della Liberazione'), + lavoro(day: 1, month: 5, label: 'Festa dei Lavoratori'), + repubblica(day: 2, month: 6, label: 'Festa della Repubblica'), + ferragosto(day: 15, month: 8, label: 'Ferragosto'), + ognissanti(day: 1, month: 11, label: 'Tutti i Santi'), + immacolata(day: 8, month: 12, label: 'Immacolata Concezione'), + natale(day: 25, month: 12, label: 'Natale'), + santoStefano(day: 26, month: 12, label: 'Santo Stefano'); + + final int day; + final int month; + final String label; + + const ItalianHoliday({ + required this.day, + required this.month, + required this.label, + }); + + /// Verifica se una determinata data corrisponde alla festività fissa + bool matches(DateTime date) => date.day == day && date.month == month; +} + +/// Helper per determinare se un giorno è lavorativo ed effettuare il conteggio dei giorni +class WorkingDaysHelper { + WorkingDaysHelper._(); + + /// Verifica se la data è domenica o festività nazionale italiana (fissa o Pasquetta) + static bool isWorkingDay(DateTime date) { + // 1. Domenica esclusa + if (date.weekday == DateTime.sunday) { + return false; + } + + // 2. Festività fisse + for (final holiday in ItalianHoliday.values) { + if (holiday.matches(date)) { + return false; + } + } + + // 3. Pasquetta (Lunedì dell'Angelo) + final easterMonday = calculateEasterMonday(date.year); + if (date.year == easterMonday.year && + date.month == easterMonday.month && + date.day == easterMonday.day) { + return false; + } + + return true; + } + + /// Calcola la data del Lunedì dell'Angelo (Pasquetta) tramite l'algoritmo di Meeus/Jones/Butcher + static DateTime calculateEasterMonday(int year) { + final a = year % 19; + final b = year ~/ 100; + final c = year % 100; + final d = b ~/ 4; + final e = b % 4; + final f = (b + 8) ~/ 25; + final g = (b - f + 1) ~/ 3; + final h = (19 * a + b - d - g + 15) % 30; + final i = c ~/ 4; + final k = c % 4; + final l = (32 + 2 * e + 2 * i - h - k) % 7; + final m = (a + 11 * h + 22 * l) ~/ 451; + final month = (h + l - 7 * m + 114) ~/ 31; + final day = ((h + l - 7 * m + 114) % 31) + 1; + + final easterSunday = DateTime(year, month, day); + // Pasquetta è il giorno successivo a Pasqua + return easterSunday.add(const Duration(days: 1)); + } + + /// Conta i giorni lavorativi compresi tra [start] e [end] (inclusi) + static int countWorkingDays(DateTime start, DateTime end) { + if (start.isAfter(end)) return 0; + + int count = 0; + DateTime current = DateTime(start.year, start.month, start.day); + final targetEnd = DateTime(end.year, end.month, end.day); + + while (!current.isAfter(targetEnd)) { + if (isWorkingDay(current)) { + count++; + } + current = current.add(const Duration(days: 1)); + } + + return count; + } + + /// Calcola la ripartizione dei giorni lavorativi per un periodo target: + /// - [total]: giorni lavorativi totali del periodo + /// - [elapsed]: giorni lavorativi trascorsi fino ad oggi (minimo 1 se il periodo è iniziato) + /// - [remaining]: giorni lavorativi rimanenti da oggi (incluso oggi se è giorno lavorativo) a fine periodo + static ({int total, int elapsed, int remaining}) calculateWorkingDaysPeriod({ + required DateTime start, + required DateTime end, + DateTime? now, + }) { + final today = now ?? DateTime.now(); + final cleanToday = DateTime(today.year, today.month, today.day); + final cleanStart = DateTime(start.year, start.month, start.day); + final cleanEnd = DateTime(end.year, end.month, end.day); + + final total = countWorkingDays(cleanStart, cleanEnd); + + // Se siamo prima dell'inizio del periodo + if (cleanToday.isBefore(cleanStart)) { + return (total: total, elapsed: 0, remaining: total); + } + + // Se siamo oltre la fine del periodo + if (cleanToday.isAfter(cleanEnd)) { + return (total: total, elapsed: total, remaining: 0); + } + + // Siamo all'interno del periodo + // Giorni trascorsi: dall'inizio fino a oggi + final elapsedDays = countWorkingDays(cleanStart, cleanToday); + final remainingDays = countWorkingDays(cleanToday, cleanEnd); + + return ( + total: total > 0 ? total : 1, + elapsed: elapsedDays > 0 ? elapsedDays : 1, + remaining: remainingDays > 0 ? remainingDays : 1, + ); + } +} diff --git a/lib/features/targets/blocs/target_detail_cubit.dart b/lib/features/targets/blocs/target_detail_cubit.dart new file mode 100644 index 0000000..4b06856 --- /dev/null +++ b/lib/features/targets/blocs/target_detail_cubit.dart @@ -0,0 +1,75 @@ +import 'dart:async'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/operations/data/operations_repository.dart'; +import 'package:flux/features/targets/blocs/target_detail_state.dart'; +import 'package:flux/features/targets/data/target_progress_service.dart'; +import 'package:flux/features/targets/data/targets_repository.dart'; +import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/service_locator.dart'; + +class TargetDetailCubit extends Cubit { + final TargetProgressService _progressService; + final TargetsRepository _targetsRepository; + final OperationsRepository _operationsRepository; + StreamSubscription? _targetsSub; + StreamSubscription? _operationsSub; + + TargetDetailCubit({ + required TargetModel target, + TargetProgressService? progressService, + TargetsRepository? targetsRepository, + OperationsRepository? operationsRepository, + }) : _progressService = progressService ?? sl(), + _targetsRepository = targetsRepository ?? sl(), + _operationsRepository = operationsRepository ?? sl(), + super( + TargetDetailState( + target: target, + status: TargetDetailStatus.initial, + ), + ) { + _targetsSub = _targetsRepository.onTargetsChanged.listen((_) { + refresh(); + }); + _operationsSub = _operationsRepository.onOperationsChanged.listen((_) { + refresh(); + }); + } + + @override + Future close() { + _targetsSub?.cancel(); + _operationsSub?.cancel(); + return super.close(); + } + + Future init() async { + emit(state.copyWith(status: TargetDetailStatus.loading)); + await refresh(); + } + + Future refresh() async { + try { + final progress = await _progressService.calculateTargetProgress( + target: state.target, + ); + emit( + state.copyWith( + progress: progress, + status: TargetDetailStatus.ready, + ), + ); + } catch (e) { + emit( + state.copyWith( + status: TargetDetailStatus.failure, + errorMessage: 'Errore durante il calcolo dell\'avanzamento: $e', + ), + ); + } + } + + void setActiveTab(int index) { + emit(state.copyWith(activeTab: index)); + } +} diff --git a/lib/features/targets/blocs/target_detail_state.dart b/lib/features/targets/blocs/target_detail_state.dart new file mode 100644 index 0000000..a86030c --- /dev/null +++ b/lib/features/targets/blocs/target_detail_state.dart @@ -0,0 +1,46 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; + +enum TargetDetailStatus { initial, loading, ready, failure } + +class TargetDetailState extends Equatable { + final TargetDetailStatus status; + final TargetModel target; + final TargetProgressModel? progress; + final int activeTab; + final String? errorMessage; + + const TargetDetailState({ + this.status = TargetDetailStatus.initial, + required this.target, + this.progress, + this.activeTab = 0, + this.errorMessage, + }); + + TargetDetailState copyWith({ + TargetDetailStatus? status, + TargetModel? target, + TargetProgressModel? progress, + int? activeTab, + String? errorMessage, + }) { + return TargetDetailState( + status: status ?? this.status, + target: target ?? this.target, + progress: progress ?? this.progress, + activeTab: activeTab ?? this.activeTab, + errorMessage: errorMessage, + ); + } + + @override + List get props => [ + status, + target, + progress, + activeTab, + errorMessage, + ]; +} diff --git a/lib/features/targets/blocs/target_form_cubit.dart b/lib/features/targets/blocs/target_form_cubit.dart index 5c3806d..964ce48 100644 --- a/lib/features/targets/blocs/target_form_cubit.dart +++ b/lib/features/targets/blocs/target_form_cubit.dart @@ -1,5 +1,6 @@ import 'package:flutter/foundation.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/data/staff_repository.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/targets/blocs/target_form_state.dart'; @@ -11,12 +12,15 @@ import 'package:flux/features/targets/models/target_model.dart'; class TargetFormCubit extends Cubit { final TargetsRepository _targetsRepository; final StaffRepository _staffRepository; + final StaffCubit _staffCubit; TargetFormCubit({ required TargetsRepository targetsRepository, required StaffRepository staffRepository, + required StaffCubit staffCubit, }) : _targetsRepository = targetsRepository, _staffRepository = staffRepository, + _staffCubit = staffCubit, super( TargetFormState( target: TargetModel.empty(), @@ -94,13 +98,56 @@ class TargetFormCubit extends Cubit { String storeId, ) async { try { - final allStaff = await _staffRepository.getStaffMembers( - companyId, - storeId: storeId, - ); - return allStaff.where((s) => s.isActive).toList(); - } catch (_) { - return []; + // 1. Assicuriamoci che StaffCubit abbia caricato i dati di base + if (_staffCubit.state.allStaff.isEmpty && + _staffCubit.state.status != StaffStatus.loading) { + await _staffCubit.loadAllStaff(); + } + + // 2. Chiediamo a StaffCubit di caricare lo staff per questo specifico negozio + if (storeId.isNotEmpty) { + await _staffCubit.loadStaffForStore(storeId); + } + + // 3. Verifichiamo se StaffCubit ha addetti per questo negozio + List staff = + storeId.isNotEmpty ? (_staffCubit.state.staffByStore[storeId] ?? []) : []; + + // 4. Se la lista è vuota, proviamo la query diretta sulla tabella di giunzione + if (staff.isEmpty && storeId.isNotEmpty) { + staff = await _staffRepository.getStaffMembersInStore(storeId); + } + + // 5. Se trovati addetti assegnati al negozio, ritorniamo quelli attivi + final activeStoreStaff = staff.where((s) => s.isActive).toList(); + if (activeStoreStaff.isNotEmpty) { + return activeStoreStaff; + } + + // 6. Fallback: controlliamo se in allStaff di StaffCubit qualcuno ha questo store associato + final matchedInAllStaff = _staffCubit.state.allStaff.where((s) { + return s.isActive && + (s.assignedStoreIds.contains(storeId) || + s.assignedStores.any((st) => st.id == storeId)); + }).toList(); + + if (matchedInAllStaff.isNotEmpty) { + return matchedInAllStaff; + } + + // 7. Se non c'è ancora alcuna assegnazione specifica (es. singolo store aziendale), + // usiamo tutti gli addetti attivi presenti in StaffCubit + final allCompanyStaff = _staffCubit.state.allStaff.where((s) => s.isActive).toList(); + if (allCompanyStaff.isNotEmpty) { + return allCompanyStaff; + } + + // 8. Fallback estremo: query al repository + final repoStaff = await _staffRepository.getStaffMembers(companyId); + return repoStaff.where((s) => s.isActive).toList(); + } catch (e) { + debugPrint('Errore nel recupero dello staff per store $storeId: $e'); + return _staffCubit.state.allStaff.where((s) => s.isActive).toList(); } } @@ -182,49 +229,72 @@ class TargetFormCubit extends Cubit { emit(state.copyWith(individualTargets: updated)); } - /// Distribuisce equamente le metriche del target di negozio tra tutti gli addetti - void distributeMetricsEqually() { - final staffCount = state.individualTargets.length; - if (staffCount == 0) return; + /// Distribuisce le metriche del target di negozio tra gli addetti specificati tramite mappa dei pesi. + /// [staffWeights] mappa staffId -> peso (es. 1.0 per full-time, 0.5 per part-time). + /// Gli addetti con peso <= 0 o esclusi vengono azzerati. + void distributeMetrics({ + required Map staffWeights, + }) { + final activeEntries = staffWeights.entries.where((e) => e.value > 0).toList(); + if (activeEntries.isEmpty) return; + + final totalWeight = activeEntries.fold(0.0, (sum, e) => sum + e.value); + if (totalWeight <= 0) return; final m = state.target.metrics; - int div(int val) => (val / staffCount).floor(); - final distributedMetrics = TargetMetrics( - mnp1: div(m.mnp1), - mnp2: div(m.mnp2), - unica1: div(m.unica1), - unica2: div(m.unica2), - nip1: div(m.nip1), - nip2: div(m.nip2), - business1: div(m.business1), - business2: div(m.business2), - contenuti1: div(m.contenuti1), - contenuti2: div(m.contenuti2), - calcio1: div(m.calcio1), - calcio2: div(m.calcio2), - fin1: div(m.fin1), - fin2: div(m.fin2), - upselling1: div(m.upselling1), - upselling2: div(m.upselling2), - cb1: div(m.cb1), - cb2: div(m.cb2), - al1: div(m.al1), - al2: div(m.al2), - telepass1: div(m.telepass1), - telepass2: div(m.telepass2), - energiaTim: div(m.energiaTim), - energiaAltri: div(m.energiaAltri), - ); + final updated = state.individualTargets.map((it) { + final weight = staffWeights[it.staffId] ?? 0.0; + if (weight <= 0) { + return it.copyWith(metrics: const TargetMetrics()); + } - final updated = - state.individualTargets.map((it) { - return it.copyWith(metrics: distributedMetrics); - }).toList(); + final ratio = weight / totalWeight; + int calc(int val) => (val * ratio).floor(); + + final distributedMetrics = TargetMetrics( + mnp1: calc(m.mnp1), + mnp2: calc(m.mnp2), + unica1: calc(m.unica1), + unica2: calc(m.unica2), + nip1: calc(m.nip1), + nip2: calc(m.nip2), + business1: calc(m.business1), + business2: calc(m.business2), + contenuti1: calc(m.contenuti1), + contenuti2: calc(m.contenuti2), + calcio1: calc(m.calcio1), + calcio2: calc(m.calcio2), + fin1: calc(m.fin1), + fin2: calc(m.fin2), + upselling1: calc(m.upselling1), + upselling2: calc(m.upselling2), + cb1: calc(m.cb1), + cb2: calc(m.cb2), + al1: calc(m.al1), + al2: calc(m.al2), + telepass1: calc(m.telepass1), + telepass2: calc(m.telepass2), + energiaTim1: calc(m.energiaTim1), + energiaTim2: calc(m.energiaTim2), + energiaAltri1: calc(m.energiaAltri1), + energiaAltri2: calc(m.energiaAltri2), + ); + + return it.copyWith(metrics: distributedMetrics); + }).toList(); emit(state.copyWith(individualTargets: updated)); } + /// Distribuisce equamente le metriche del target di negozio tra tutti gli addetti + void distributeMetricsEqually() { + final weights = { + for (final it in state.individualTargets) it.staffId: 1.0, + }; + distributeMetrics(staffWeights: weights); + } + void setActiveTab(int tab) { emit(state.copyWith(activeTab: tab)); } diff --git a/lib/features/targets/blocs/target_list_cubit.dart b/lib/features/targets/blocs/target_list_cubit.dart index eb1acf0..0b7f60a 100644 --- a/lib/features/targets/blocs/target_list_cubit.dart +++ b/lib/features/targets/blocs/target_list_cubit.dart @@ -2,21 +2,37 @@ import 'dart:async'; import 'package:equatable/equatable.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/targets/data/target_progress_service.dart'; import 'package:flux/features/targets/data/targets_repository.dart'; import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; import 'package:flux/service_locator.dart'; part 'target_list_state.dart'; class TargetListCubit extends Cubit { final TargetsRepository _repository = sl(); + final OperationsRepository _operationsRepository = sl(); + final TargetProgressService _progressService = sl(); final SessionCubit _sessionCubit = sl(); - StreamSubscription? _changeSub; + StreamSubscription? _targetsSub; + StreamSubscription? _operationsSub; TargetListCubit() : super(const TargetListState()) { - _changeSub = _repository.onTargetsChanged.listen((_) { + _targetsSub = _repository.onTargetsChanged.listen((_) { loadTargets(); }); + _operationsSub = _operationsRepository.onOperationsChanged.listen((_) { + loadTargets(); + }); + } + + @override + Future close() { + _targetsSub?.cancel(); + _operationsSub?.cancel(); + return super.close(); } Future loadTargets({String? storeId, DateTime? month}) async { @@ -58,10 +74,22 @@ class TargetListCubit extends Cubit { toDate: toDate, ); + // Calcolo progressi e ritmi per ciascun target trovato + final progressMap = {}; + for (final target in targets) { + if (target.id != null) { + final progress = await _progressService.calculateTargetProgress( + target: target, + ); + progressMap[target.id!] = progress; + } + } + emit( state.copyWith( status: TargetListStatus.success, targets: targets, + progressMap: progressMap, selectedStoreId: () => effectiveStoreId, selectedMonth: () => effectiveMonth, ), @@ -98,10 +126,4 @@ class TargetListCubit extends Cubit { return false; } } - - @override - Future close() { - _changeSub?.cancel(); - return super.close(); - } } diff --git a/lib/features/targets/blocs/target_list_state.dart b/lib/features/targets/blocs/target_list_state.dart index 73be94d..3112be4 100644 --- a/lib/features/targets/blocs/target_list_state.dart +++ b/lib/features/targets/blocs/target_list_state.dart @@ -5,6 +5,7 @@ enum TargetListStatus { initial, loading, success, failure } class TargetListState extends Equatable { final TargetListStatus status; final List targets; + final Map progressMap; final String? selectedStoreId; final DateTime? selectedMonth; final String? errorMessage; @@ -12,6 +13,7 @@ class TargetListState extends Equatable { const TargetListState({ this.status = TargetListStatus.initial, this.targets = const [], + this.progressMap = const {}, this.selectedStoreId, this.selectedMonth, this.errorMessage, @@ -20,6 +22,7 @@ class TargetListState extends Equatable { TargetListState copyWith({ TargetListStatus? status, List? targets, + Map? progressMap, String? Function()? selectedStoreId, DateTime? Function()? selectedMonth, String? errorMessage, @@ -27,6 +30,7 @@ class TargetListState extends Equatable { return TargetListState( status: status ?? this.status, targets: targets ?? this.targets, + progressMap: progressMap ?? this.progressMap, selectedStoreId: selectedStoreId != null ? selectedStoreId() : this.selectedStoreId, selectedMonth: @@ -39,6 +43,7 @@ class TargetListState extends Equatable { List get props => [ status, targets, + progressMap, selectedStoreId, selectedMonth, errorMessage, diff --git a/lib/features/targets/data/target_progress_service.dart b/lib/features/targets/data/target_progress_service.dart new file mode 100644 index 0000000..5e5cfe9 --- /dev/null +++ b/lib/features/targets/data/target_progress_service.dart @@ -0,0 +1,264 @@ +import 'package:flutter/foundation.dart'; +import 'package:flux/core/enums_and_consts/consts.dart'; +import 'package:flux/core/utils/working_days_helper.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; +import 'package:flux/features/targets/models/target_metrics.dart'; +import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; +import 'package:flux/service_locator.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class TargetProgressService { + final SupabaseClient _supabase; + + TargetProgressService({SupabaseClient? supabase}) + : _supabase = supabase ?? sl(); + + static const List<({String key, String label})> metricDefinitions = [ + (key: 'mnp', label: 'MNP'), + (key: 'unica', label: 'TIM Unica'), + (key: 'nip', label: 'NIP'), + (key: 'business', label: 'Business'), + (key: 'contenuti', label: 'Contenuti'), + (key: 'calcio', label: 'Calcio'), + (key: 'fin', label: 'Finanziamenti'), + (key: 'upselling', label: 'Upselling'), + (key: 'cb', label: 'Customer Base'), + (key: 'al', label: 'Attivazioni Linea'), + (key: 'telepass', label: 'Telepass'), + (key: 'energiaTim', label: 'Energia TIM'), + (key: 'energiaAltri', label: 'Energia Non TIM'), + ]; + + /// Calcola l'avanzamento completo per un target (di negozio e per ciascun addetto) + Future calculateTargetProgress({ + required TargetModel target, + DateTime? now, + }) async { + final effectiveNow = now ?? DateTime.now(); + + // 1. Calcolo giorni lavorativi con esclusione di domeniche e festivi + final days = WorkingDaysHelper.calculateWorkingDaysPeriod( + start: target.startDay, + end: target.endDay, + now: effectiveNow, + ); + + // 2. Query su operations nel periodo target per lo store + final storeCounts = {}; + final staffCounts = >{}; + + // Inizializza contatori + for (final def in metricDefinitions) { + storeCounts[def.key] = 0; + } + + try { + final storeId = target.storeId; + if (storeId != null && storeId.isNotEmpty) { + final response = await _supabase + .from(Tables.operations) + .select(''' + id, + store_id, + staff_id, + created_at, + status, + is_business, + ${Tables.operationDetails}( + type, + sub_type, + provider_id, + ${Tables.providers}(name) + ) + ''') + .eq('company_id', target.companyId) + .eq('store_id', storeId) + .neq('status', 'failure') + .gte('created_at', target.startDay.toIso8601String()) + .lte('created_at', target.endDay.toIso8601String()); + + final operations = response as List; + + for (final op in operations) { + final staffId = op['staff_id'] as String?; + final isBusinessOp = op['is_business'] as bool? ?? false; + final details = op[Tables.operationDetails] as List? ?? []; + + if (staffId != null && !staffCounts.containsKey(staffId)) { + staffCounts[staffId] = { + for (final def in metricDefinitions) def.key: 0, + }; + } + + for (final d in details) { + final typeStr = d['type'] as String?; + final opType = OperationType.fromValue(typeStr); + final subType = (d['sub_type'] as String?)?.trim().toLowerCase(); + final providerMap = d[Tables.providers] as Map?; + final providerName = (providerMap?['name'] as String?)?.toLowerCase() ?? ''; + + final categoryKey = _mapDetailToCategory( + opType: opType, + subType: subType, + providerName: providerName, + isBusinessOp: isBusinessOp, + ); + + if (categoryKey != null && storeCounts.containsKey(categoryKey)) { + storeCounts[categoryKey] = (storeCounts[categoryKey] ?? 0) + 1; + if (staffId != null && staffCounts.containsKey(staffId)) { + staffCounts[staffId]![categoryKey] = + (staffCounts[staffId]![categoryKey] ?? 0) + 1; + } + } + } + } + } + } catch (e) { + debugPrint('Errore nel caricamento delle operazioni per il target: $e'); + } + + // 3. Costruzione CategoryProgress per il negozio + final storeCategories = {}; + for (final def in metricDefinitions) { + final actual = storeCounts[def.key] ?? 0; + final targets = _extractTargetS1S2(target.metrics, def.key); + + storeCategories[def.key] = CategoryProgress.calculate( + key: def.key, + label: def.label, + actual: actual, + s1: targets.s1, + s2: targets.s2, + elapsedDays: days.elapsed, + remainingDays: days.remaining, + totalDays: days.total, + ); + } + + // 4. Costruzione avanzamento per singoli addetti + final staffProgressMap = {}; + for (final it in target.individualTargets) { + final sId = it.staffId; + final sCounts = staffCounts[sId] ?? {}; + final sCategories = {}; + + for (final def in metricDefinitions) { + final actual = sCounts[def.key] ?? 0; + final targets = _extractTargetS1S2(it.metrics, def.key); + + sCategories[def.key] = CategoryProgress.calculate( + key: def.key, + label: def.label, + actual: actual, + s1: targets.s1, + s2: targets.s2, + elapsedDays: days.elapsed, + remainingDays: days.remaining, + totalDays: days.total, + ); + } + + staffProgressMap[sId] = TargetProgressModel( + targetId: target.id ?? '', + storeId: target.storeId, + staffId: sId, + staffName: it.staff?.name, + totalWorkingDays: days.total, + elapsedWorkingDays: days.elapsed, + remainingWorkingDays: days.remaining, + categories: sCategories, + ); + } + + return TargetProgressModel( + targetId: target.id ?? '', + storeId: target.storeId, + totalWorkingDays: days.total, + elapsedWorkingDays: days.elapsed, + remainingWorkingDays: days.remaining, + categories: storeCategories, + staffProgress: staffProgressMap, + ); + } + + /// Mappa un dettaglio operazione alla chiave di metrica target corrispondente + String? _mapDetailToCategory({ + required OperationType? opType, + required String? subType, + required String providerName, + required bool isBusinessOp, + }) { + if (opType == null) return null; + + if (opType == OperationType.business || isBusinessOp) { + return 'business'; + } + + switch (opType) { + case OperationType.mnp: + return 'mnp'; + case OperationType.unica: + return 'unica'; + case OperationType.nip: + return 'nip'; + case OperationType.entertainment: + if (subType == 'calcio') { + return 'calcio'; + } + return 'contenuti'; + case OperationType.fin: + return 'fin'; + case OperationType.upselling: + return 'upselling'; + case OperationType.cb: + return 'cb'; + case OperationType.al: + return 'al'; + case OperationType.telepass: + return 'telepass'; + case OperationType.energy: + if (providerName.contains('tim')) { + return 'energiaTim'; + } + return 'energiaAltri'; + default: + return null; + } + } + + /// Estrae i valori di Soglia 1 e Soglia 2 per la specifica categoria da TargetMetrics + ({int s1, int s2}) _extractTargetS1S2(TargetMetrics m, String key) { + switch (key) { + case 'mnp': + return (s1: m.mnp1, s2: m.mnp2); + case 'unica': + return (s1: m.unica1, s2: m.unica2); + case 'nip': + return (s1: m.nip1, s2: m.nip2); + case 'business': + return (s1: m.business1, s2: m.business2); + case 'contenuti': + return (s1: m.contenuti1, s2: m.contenuti2); + case 'calcio': + return (s1: m.calcio1, s2: m.calcio2); + case 'fin': + return (s1: m.fin1, s2: m.fin2); + case 'upselling': + return (s1: m.upselling1, s2: m.upselling2); + case 'cb': + return (s1: m.cb1, s2: m.cb2); + case 'al': + return (s1: m.al1, s2: m.al2); + case 'telepass': + return (s1: m.telepass1, s2: m.telepass2); + case 'energiaTim': + return (s1: m.energiaTim1, s2: m.energiaTim2); + case 'energiaAltri': + return (s1: m.energiaAltri1, s2: m.energiaAltri2); + default: + return (s1: 0, s2: 0); + } + } +} diff --git a/lib/features/targets/models/target_metrics.dart b/lib/features/targets/models/target_metrics.dart index f866fb2..73c86d8 100644 --- a/lib/features/targets/models/target_metrics.dart +++ b/lib/features/targets/models/target_metrics.dart @@ -23,8 +23,14 @@ class TargetMetrics extends Equatable { final int al2; final int telepass1; final int telepass2; - final int energiaTim; - final int energiaAltri; + final int energiaTim1; + final int energiaTim2; + final int energiaAltri1; + final int energiaAltri2; + + // Getter di compatibilità con codice pregresso + int get energiaTim => energiaTim1; + int get energiaAltri => energiaAltri1; const TargetMetrics({ this.mnp1 = 0, @@ -49,37 +55,44 @@ class TargetMetrics extends Equatable { this.al2 = 0, this.telepass1 = 0, this.telepass2 = 0, - this.energiaTim = 0, - this.energiaAltri = 0, - }); + int? energiaTim1, + int? energiaTim, + this.energiaTim2 = 0, + int? energiaAltri1, + int? energiaAltri, + this.energiaAltri2 = 0, + }) : energiaTim1 = energiaTim1 ?? energiaTim ?? 0, + energiaAltri1 = energiaAltri1 ?? energiaAltri ?? 0; @override List get props => [ - mnp1, - mnp2, - unica1, - unica2, - nip1, - nip2, - business1, - business2, - contenuti1, - contenuti2, - calcio1, - calcio2, - fin1, - fin2, - upselling1, - upselling2, - cb1, - cb2, - al1, - al2, - telepass1, - telepass2, - energiaTim, - energiaAltri, - ]; + mnp1, + mnp2, + unica1, + unica2, + nip1, + nip2, + business1, + business2, + contenuti1, + contenuti2, + calcio1, + calcio2, + fin1, + fin2, + upselling1, + upselling2, + cb1, + cb2, + al1, + al2, + telepass1, + telepass2, + energiaTim1, + energiaTim2, + energiaAltri1, + energiaAltri2, + ]; TargetMetrics copyWith({ int? mnp1, @@ -104,8 +117,12 @@ class TargetMetrics extends Equatable { int? al2, int? telepass1, int? telepass2, + int? energiaTim1, int? energiaTim, + int? energiaTim2, + int? energiaAltri1, int? energiaAltri, + int? energiaAltri2, }) { return TargetMetrics( mnp1: mnp1 ?? this.mnp1, @@ -130,8 +147,10 @@ class TargetMetrics extends Equatable { al2: al2 ?? this.al2, telepass1: telepass1 ?? this.telepass1, telepass2: telepass2 ?? this.telepass2, - energiaTim: energiaTim ?? this.energiaTim, - energiaAltri: energiaAltri ?? this.energiaAltri, + energiaTim1: energiaTim1 ?? energiaTim ?? this.energiaTim1, + energiaTim2: energiaTim2 ?? this.energiaTim2, + energiaAltri1: energiaAltri1 ?? energiaAltri ?? this.energiaAltri1, + energiaAltri2: energiaAltri2 ?? this.energiaAltri2, ); } @@ -163,14 +182,20 @@ class TargetMetrics extends Equatable { al2: (map['al_2'] as num?)?.toInt() ?? 0, telepass1: (map['telepass_1'] as num?)?.toInt() ?? 0, telepass2: (map['telepass_2'] as num?)?.toInt() ?? 0, - energiaTim: + energiaTim1: (map['energia_tim_1'] as num?)?.toInt() ?? (map['energia_tim'] as num?)?.toInt() ?? (map['Energia_tim'] as num?)?.toInt() ?? 0, - energiaAltri: + energiaTim2: (map['energia_tim_2'] as num?)?.toInt() ?? + (map['Energia_tim_2'] as num?)?.toInt() ?? + 0, + energiaAltri1: (map['energia_altri_1'] as num?)?.toInt() ?? (map['energia_altri'] as num?)?.toInt() ?? (map['Energia_altri'] as num?)?.toInt() ?? 0, + energiaAltri2: (map['energia_altri_2'] as num?)?.toInt() ?? + (map['Energia_altri_2'] as num?)?.toInt() ?? + 0, ); } @@ -198,8 +223,12 @@ class TargetMetrics extends Equatable { 'al_2': al2, 'telepass_1': telepass1, 'telepass_2': telepass2, - 'energia_tim': energiaTim, - 'energia_altri': energiaAltri, + 'energia_tim_1': energiaTim1, + 'energia_tim_2': energiaTim2, + 'energia_tim': energiaTim1, + 'energia_altri_1': energiaAltri1, + 'energia_altri_2': energiaAltri2, + 'energia_altri': energiaAltri1, }; } @@ -216,10 +245,10 @@ class TargetMetrics extends Equatable { cb1 + al1 + telepass1 + - energiaTim + - energiaAltri; + energiaTim1 + + energiaAltri1; - /// Somma totale di tutti i target del Livello 2 + /// Somma totale di tutti i target del Livello 2 (inclusa energia) int get totalLevel2 => mnp2 + unica2 + @@ -231,5 +260,7 @@ class TargetMetrics extends Equatable { upselling2 + cb2 + al2 + - telepass2; + telepass2 + + energiaTim2 + + energiaAltri2; } diff --git a/lib/features/targets/models/target_progress_model.dart b/lib/features/targets/models/target_progress_model.dart new file mode 100644 index 0000000..0150816 --- /dev/null +++ b/lib/features/targets/models/target_progress_model.dart @@ -0,0 +1,294 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; + +/// Stato di avanzamento sul ritmo di ciascuna metrica +enum TargetPacingStatus { + /// In linea con lo sfidante o già superato (VERDE PIENO) + inLineS2(label: 'In linea Sfidante', emoji: '🚀'), + + /// In linea con il minimo o già raggiunto (VERDINO) + inLineS1(label: 'In linea Minimo', emoji: '✅'), + + /// Sotto ritmo ma vicino/recuperabile (ROSA) + recoverable(label: 'Da spingere', emoji: '⚡'), + + /// Sotto ritmo grave o fermo (ROSSO) + critical(label: 'Critico', emoji: '🔴'), + + /// Nessun obiettivo impostato per questa categoria + notSet(label: 'Non impostato', emoji: '—'); + + final String label; + final String emoji; + + const TargetPacingStatus({required this.label, required this.emoji}); +} + +/// Avanzamento e ritmo su una singola metrica/categoria di obiettivo +class CategoryProgress extends Equatable { + final String key; + final String label; + final int actualPieces; + final int targetS1; + final int targetS2; + final TargetPacingStatus status; + final double actualDailyRate; + final double requiredDailyRateS1; + final double requiredDailyRateS2; + final double projectedPieces; + + const CategoryProgress({ + required this.key, + required this.label, + required this.actualPieces, + required this.targetS1, + required this.targetS2, + required this.status, + required this.actualDailyRate, + required this.requiredDailyRateS1, + required this.requiredDailyRateS2, + required this.projectedPieces, + }); + + /// Calcola il progresso di una singola metrica dati i giorni lavorativi + factory CategoryProgress.calculate({ + required String key, + required String label, + required int actual, + required int s1, + required int s2, + required int elapsedDays, + required int remainingDays, + required int totalDays, + }) { + if (s1 == 0 && s2 == 0) { + return CategoryProgress( + key: key, + label: label, + actualPieces: actual, + targetS1: 0, + targetS2: 0, + status: TargetPacingStatus.notSet, + actualDailyRate: elapsedDays > 0 ? (actual / elapsedDays) : 0.0, + requiredDailyRateS1: 0.0, + requiredDailyRateS2: 0.0, + projectedPieces: elapsedDays > 0 ? (actual / elapsedDays) * totalDays : 0.0, + ); + } + + final actualDaily = elapsedDays > 0 ? (actual / elapsedDays) : 0.0; + final projected = actualDaily * totalDays; + + final remainingPiecesS1 = s1 > actual ? (s1 - actual) : 0; + final remainingPiecesS2 = s2 > actual ? (s2 - actual) : 0; + + final reqDailyS1 = remainingDays > 0 ? (remainingPiecesS1 / remainingDays) : 0.0; + final reqDailyS2 = remainingDays > 0 ? (remainingPiecesS2 / remainingDays) : 0.0; + + // Determinazione dello stato di pacing cromatico a 4 livelli + TargetPacingStatus status; + if (elapsedDays == 0) { + status = TargetPacingStatus.inLineS1; + } else if (s2 > 0 && (actual >= s2 || projected >= s2)) { + status = TargetPacingStatus.inLineS2; // Verde pieno + } else if (actual >= s1 || projected >= s1) { + status = TargetPacingStatus.inLineS1; // Verdino + } else if (s1 > 0 && projected >= (s1 * 0.55)) { + status = TargetPacingStatus.recoverable; // Rosa (da spingere) + } else { + status = TargetPacingStatus.critical; // Rosso (critico) + } + + return CategoryProgress( + key: key, + label: label, + actualPieces: actual, + targetS1: s1, + targetS2: s2, + status: status, + actualDailyRate: actualDaily, + requiredDailyRateS1: reqDailyS1, + requiredDailyRateS2: reqDailyS2, + projectedPieces: projected, + ); + } + + @override + List get props => [ + key, + label, + actualPieces, + targetS1, + targetS2, + status, + actualDailyRate, + requiredDailyRateS1, + requiredDailyRateS2, + projectedPieces, + ]; +} + +/// Modello aggregato di avanzamento target per il negozio o per singolo addetto +class TargetProgressModel extends Equatable { + final String targetId; + final String? storeId; + final String? staffId; + final String? staffName; + final int totalWorkingDays; + final int elapsedWorkingDays; + final int remainingWorkingDays; + final Map categories; + final Map staffProgress; + + const TargetProgressModel({ + required this.targetId, + this.storeId, + this.staffId, + this.staffName, + required this.totalWorkingDays, + required this.elapsedWorkingDays, + required this.remainingWorkingDays, + required this.categories, + this.staffProgress = const {}, + }); + + /// Somma di tutti i pezzi realizzati finora + int get totalActualPieces => + categories.values.fold(0, (sum, c) => sum + c.actualPieces); + + /// Totale pezzi obiettivo Soglia 1 + int get totalTargetS1 => + categories.values.fold(0, (sum, c) => sum + c.targetS1); + + /// Totale pezzi obiettivo Soglia 2 + int get totalTargetS2 => + categories.values.fold(0, (sum, c) => sum + c.targetS2); + + /// Numero di obiettivi in linea o raggiunti in Soglia 2 + int get countInLineS2 => categories.values + .where((c) => c.status == TargetPacingStatus.inLineS2) + .length; + + /// Numero di obiettivi in linea o raggiunti in Soglia 1 + int get countInLineS1 => categories.values + .where((c) => c.status == TargetPacingStatus.inLineS1) + .length; + + /// Numero di obiettivi sotto ritmo ma vicini/recuperabili (ROSA) + int get countRecoverable => categories.values + .where((c) => c.status == TargetPacingStatus.recoverable) + .length; + + /// Numero di obiettivi in forte ritardo o fermi (ROSSO) + int get countCritical => categories.values + .where((c) => c.status == TargetPacingStatus.critical) + .length; + + /// Numero totale di obiettivi sotto ritmo (Rosa + Rosso) + int get countBehind => countRecoverable + countCritical; + + /// Numero di categorie con obiettivo attivo (> 0) + int get countTotalActive => categories.values + .where((c) => c.status != TargetPacingStatus.notSet) + .length; + + /// Media giornaliera complessiva tenuta finora + double get overallActualDailyRate => + elapsedWorkingDays > 0 ? (totalActualPieces / elapsedWorkingDays) : 0.0; + + /// Media giornaliera complessiva necessaria per raggiungere Soglia 1 + double get overallRequiredDailyRateS1 { + final remainingPieces = + totalTargetS1 > totalActualPieces ? (totalTargetS1 - totalActualPieces) : 0; + return remainingWorkingDays > 0 ? (remainingPieces / remainingWorkingDays) : 0.0; + } + + /// Media giornaliera complessiva necessaria per raggiungere Soglia 2 + double get overallRequiredDailyRateS2 { + final remainingPieces = + totalTargetS2 > totalActualPieces ? (totalTargetS2 - totalActualPieces) : 0; + return remainingWorkingDays > 0 ? (remainingPieces / remainingWorkingDays) : 0.0; + } + + @override + List get props => [ + targetId, + storeId, + staffId, + staffName, + totalWorkingDays, + elapsedWorkingDays, + remainingWorkingDays, + categories, + staffProgress, + ]; +} + +/// Palette cromatica a 4 livelli (Verde, Verdino, Rosa, Rosso) per massima chiarezza visiva +class PacingTheme { + final Color primary; + final Color background; + final Color border; + final Color text; + final String label; + final IconData icon; + + const PacingTheme({ + required this.primary, + required this.background, + required this.border, + required this.text, + required this.label, + required this.icon, + }); + + static PacingTheme of(TargetPacingStatus status) { + switch (status) { + case TargetPacingStatus.inLineS2: + return const PacingTheme( + primary: Color(0xFF15803D), // Verde pieno (Sfidante centrato o in linea) + background: Color(0xFFDCFCE7), + border: Color(0xFF86EFAC), + text: Color(0xFF14532D), + label: 'In linea Sfidante', + icon: Icons.rocket_launch_rounded, + ); + case TargetPacingStatus.inLineS1: + return const PacingTheme( + primary: Color(0xFF0D9488), // Verdino / Mint (Minimo centrato o in linea) + background: Color(0xFFCCFBF1), + border: Color(0xFF5EEAD4), + text: Color(0xFF115E59), + label: 'In linea Minimo', + icon: Icons.check_circle_outline_rounded, + ); + case TargetPacingStatus.recoverable: + return const PacingTheme( + primary: Color(0xFFDB2777), // Rosa (Sotto ritmo ma recuperabile) + background: Color(0xFFFCE7F3), + border: Color(0xFFF9A8D4), + text: Color(0xFF831843), + label: 'Da spingere', + icon: Icons.bolt_rounded, + ); + case TargetPacingStatus.critical: + return const PacingTheme( + primary: Color(0xFFDC2626), // Rosso (Forte ritardo) + background: Color(0xFFFEE2E2), + border: Color(0xFFFCA5A5), + text: Color(0xFF7F1D1D), + label: 'In ritardo', + icon: Icons.warning_amber_rounded, + ); + case TargetPacingStatus.notSet: + return const PacingTheme( + primary: Colors.grey, + background: Color(0xFFF3F4F6), + border: Color(0xFFE5E7EB), + text: Color(0xFF374151), + label: 'Non impostato', + icon: Icons.remove, + ); + } + } +} diff --git a/lib/features/targets/ui/target_detail_screen.dart b/lib/features/targets/ui/target_detail_screen.dart new file mode 100644 index 0000000..cad589a --- /dev/null +++ b/lib/features/targets/ui/target_detail_screen.dart @@ -0,0 +1,1154 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/routes/routes.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'; +import 'package:flux/features/targets/models/target_progress_model.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +class TargetDetailScreen extends StatefulWidget { + final TargetModel target; + + const TargetDetailScreen({ + super.key, + required this.target, + }); + + @override + State createState() => _TargetDetailScreenState(); +} + +class _TargetDetailScreenState extends State + with SingleTickerProviderStateMixin { + late TabController _tabController; + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _tabController.dispose(); + super.dispose(); + } + + String _formatMonthYear(DateTime date) { + try { + final formatted = DateFormat('MMMM yyyy', 'it_IT').format(date); + return formatted[0].toUpperCase() + formatted.substring(1); + } catch (_) { + return DateFormat('MMMM yyyy').format(date); + } + } + + String _formatDateRange(DateTime start, DateTime end) { + try { + final s = DateFormat('dd/MM/yyyy', 'it_IT').format(start); + final e = DateFormat('dd/MM/yyyy', 'it_IT').format(end); + return '$s - $e'; + } catch (_) { + return '${start.day}/${start.month}/${start.year} - ${end.day}/${end.month}/${end.year}'; + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDesktop = MediaQuery.of(context).size.width >= 900; + final cubit = context.read(); + + return BlocBuilder( + builder: (context, state) { + final target = state.target; + final progress = state.progress; + final title = _formatMonthYear(target.startDay); + final storeName = target.store?.name ?? 'Negozio'; + final range = _formatDateRange(target.startDay, target.endDay); + + return Scaffold( + appBar: AppBar( + title: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 18), + ), + const SizedBox(width: 8), + Chip( + label: Text( + storeName, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.1), + side: BorderSide.none, + padding: EdgeInsets.zero, + visualDensity: VisualDensity.compact, + ), + ], + ), + Text( + range, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + actions: [ + IconButton( + icon: const Icon(Icons.refresh_rounded), + tooltip: 'Ricalcola avanzamento', + onPressed: () => cubit.refresh(), + ), + IconButton( + icon: const Icon(Icons.edit_outlined), + tooltip: 'Modifica quote target', + onPressed: () { + context.pushNamed(Routes.targetForm, extra: target); + }, + ), + const SizedBox(width: 8), + ], + bottom: TabBar( + controller: _tabController, + tabs: const [ + Tab( + icon: Icon(Icons.store_mall_directory_outlined, size: 20), + text: 'Obiettivi Negozio', + ), + Tab( + icon: Icon(Icons.people_alt_outlined, size: 20), + text: 'Avanzamento Addetti', + ), + ], + ), + ), + body: state.status == TargetDetailStatus.loading && progress == null + ? const Center(child: CircularProgressIndicator()) + : progress == null + ? Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.error_outline, size: 48, color: Colors.grey.shade400), + const SizedBox(height: 12), + const Text('Impossibile calcolare l\'avanzamento del target.'), + const SizedBox(height: 8), + ElevatedButton.icon( + onPressed: () => cubit.refresh(), + icon: const Icon(Icons.refresh), + label: const Text('Riprova'), + ), + ], + ), + ) + : TabBarView( + controller: _tabController, + children: [ + _buildStoreTab(context, theme, target, progress, isDesktop), + _buildStaffTab(context, theme, target, progress, isDesktop), + ], + ), + ); + }, + ); + } + + // ========================================== + // TAB 1: OBIETTIVI NEGOZIO + // ========================================== + + Widget _buildStoreTab( + BuildContext context, + ThemeData theme, + TargetModel target, + TargetProgressModel progress, + bool isDesktop, + ) { + return SingleChildScrollView( + padding: EdgeInsets.all(isDesktop ? 24.0 : 16.0), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 1100), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Hero KPI Dashboard (Overview) + _buildHeroKpiCard(theme, progress, isDesktop), + const SizedBox(height: 24), + + // Titolo Sezione + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Dettaglio per Categoria di Prodotto', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + Text( + '${progress.countTotalActive} categorie attive', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 12), + + // Lista Categorie Negozio + ...progress.categories.values.map((cat) { + return _buildCategoryCard(theme, cat, progress); + }), + ], + ), + ), + ), + ); + } + + Widget _buildHeroKpiCard( + ThemeData theme, + TargetProgressModel progress, + bool isDesktop, + ) { + final s1Target = progress.totalTargetS1; + final s2Target = progress.totalTargetS2; + final actual = progress.totalActualPieces; + final s1Ratio = s1Target > 0 ? (actual / s1Target).clamp(0.0, 1.0) : 0.0; + + final greenTheme = PacingTheme.of(TargetPacingStatus.inLineS2); + final verdinoTheme = PacingTheme.of(TargetPacingStatus.inLineS1); + final pinkTheme = PacingTheme.of(TargetPacingStatus.recoverable); + final redTheme = PacingTheme.of(TargetPacingStatus.critical); + + return Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(20), + side: BorderSide(color: theme.colorScheme.primary.withValues(alpha: 0.2)), + ), + color: theme.colorScheme.primaryContainer.withValues(alpha: 0.12), + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + children: [ + // Riga KPI Superiori + Row( + children: [ + // KPI 1: Stato Pacing Gare (I 4 Colori: Verde, Verdino, Rosa, Rosso) + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'STATO GARE (COLPO D\'OCCHIO)', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + letterSpacing: 0.5, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 6, + runSpacing: 6, + children: [ + if (progress.countInLineS2 > 0) + _buildPill( + '🚀 ${progress.countInLineS2} Sfidante (Verde)', + greenTheme.text, + greenTheme.background, + greenTheme.border, + ), + if (progress.countInLineS1 > 0) + _buildPill( + '✅ ${progress.countInLineS1} Minimo (Verdino)', + verdinoTheme.text, + verdinoTheme.background, + verdinoTheme.border, + ), + if (progress.countRecoverable > 0) + _buildPill( + '⚡ ${progress.countRecoverable} Da spingere (Rosa)', + pinkTheme.text, + pinkTheme.background, + pinkTheme.border, + ), + if (progress.countCritical > 0) + _buildPill( + '🔴 ${progress.countCritical} In ritardo (Rosso)', + redTheme.text, + redTheme.background, + redTheme.border, + ), + if (progress.countBehind == 0 && progress.countTotalActive > 0) + _buildPill( + '🌟 Tutti a ritmo!', + greenTheme.text, + greenTheme.background, + greenTheme.border, + ), + ], + ), + ], + ), + ), + + // Separatore + Container( + height: 70, + width: 1, + color: theme.dividerColor.withValues(alpha: 0.3), + margin: const EdgeInsets.symmetric(horizontal: 16), + ), + + // KPI 2: Totale Realizzato vs Minimo + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'VOLUME TOTALE', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + letterSpacing: 0.5, + ), + ), + const SizedBox(height: 4), + Row( + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + '$actual', + style: const TextStyle( + fontSize: 30, + fontWeight: FontWeight.w900, + ), + ), + Text( + ' / $s1Target (Minimo)', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + if (s2Target > 0) ...[ + const SizedBox(width: 8), + Text( + '• Sfida: $s2Target', + style: TextStyle( + fontSize: 13, + color: Colors.purple.shade700, + fontWeight: FontWeight.bold, + ), + ), + ], + ], + ), + const SizedBox(height: 8), + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: s1Ratio, + minHeight: 8, + backgroundColor: theme.dividerColor.withValues(alpha: 0.3), + color: s1Ratio >= 1.0 ? const Color(0xFF15803D) : theme.colorScheme.primary, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + const Divider(height: 1), + const SizedBox(height: 14), + + // Riga Inferiore: Ritmo e Medie Lavorative (Grandi e Immediate) + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon(Icons.calendar_month_outlined, color: theme.colorScheme.primary, size: 16), + const SizedBox(width: 8), + Text( + '${progress.elapsedWorkingDays} gg lav. trascorsi • ${progress.remainingWorkingDays} gg rimanenti (escluse domeniche e festivi)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 12), + Wrap( + spacing: 12, + runSpacing: 10, + children: [ + // Media Attuale + _buildRateBadge( + label: 'MEDIA ATTUALE NEGOZIO', + value: '${progress.overallActualDailyRate.toStringAsFixed(1)} / gg', + color: theme.colorScheme.primary, + bgColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.25), + borderColor: theme.colorScheme.primary.withValues(alpha: 0.35), + ), + + // Richiesta S1 + () { + final isS1Done = actual >= s1Target; + Color c; + Color bg; + Color border; + String val; + if (isS1Done) { + c = greenTheme.text; + bg = greenTheme.background; + border = greenTheme.border; + val = 'RAGGIUNTA! 🎉'; + } else if (progress.overallRequiredDailyRateS1 <= progress.overallActualDailyRate) { + c = verdinoTheme.text; + bg = verdinoTheme.background; + border = verdinoTheme.border; + val = '${progress.overallRequiredDailyRateS1.toStringAsFixed(1)} / gg'; + } else if (progress.overallRequiredDailyRateS1 <= progress.overallActualDailyRate * 1.35) { + c = pinkTheme.text; + bg = pinkTheme.background; + border = pinkTheme.border; + val = '${progress.overallRequiredDailyRateS1.toStringAsFixed(1)} / gg'; + } else { + c = redTheme.text; + bg = redTheme.background; + border = redTheme.border; + val = '${progress.overallRequiredDailyRateS1.toStringAsFixed(1)} / gg'; + } + return _buildRateBadge( + label: 'SERVE PER S1 (MINIMO)', + value: val, + color: c, + bgColor: bg, + borderColor: border, + ); + }(), + + // Richiesta S2 (se presente) + if (s2Target > 0) + () { + final isS2Done = actual >= s2Target; + return _buildRateBadge( + label: 'SERVE PER S2 (SFIDANTE)', + value: isS2Done + ? 'RAGGIUNTA! 🚀' + : '${progress.overallRequiredDailyRateS2.toStringAsFixed(1)} / gg', + color: isS2Done ? greenTheme.text : Colors.purple.shade900, + bgColor: isS2Done ? greenTheme.background : Colors.purple.shade50, + borderColor: isS2Done ? greenTheme.border : Colors.purple.shade200, + ); + }(), + ], + ), + ], + ), + ], + ), + ), + ); + } + + Widget _buildCategoryCard( + ThemeData theme, + CategoryProgress cat, + TargetProgressModel progress, + ) { + final hasTargets = cat.targetS1 > 0 || cat.targetS2 > 0; + final isDoneS1 = hasTargets && cat.actualPieces >= cat.targetS1; + final isDoneS2 = cat.targetS2 > 0 && cat.actualPieces >= cat.targetS2; + final ratio = cat.targetS1 > 0 ? (cat.actualPieces / cat.targetS1).clamp(0.0, 1.0) : 0.0; + + final pacingTheme = PacingTheme.of(cat.status); + String statusLabel = pacingTheme.label; + if (isDoneS2) { + statusLabel = 'S2 Raggiunto! 🚀'; + } else if (isDoneS1) { + statusLabel = 'S1 Raggiunto! ✅'; + } + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: hasTargets + ? pacingTheme.border.withValues(alpha: 0.8) + : theme.dividerColor.withValues(alpha: 0.3), + width: 1.2, + ), + boxShadow: [ + BoxShadow( + color: (hasTargets ? pacingTheme.primary : Colors.black).withValues(alpha: 0.04), + blurRadius: 8, + offset: const Offset(0, 2), + ), + ], + ), + 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, + ), + ), + ), + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // 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, + ), + ), + ], + ), + ), + ], + ), + ), + + // 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(height: 12), + + // Barra di avanzamento + if (hasTargets) ...[ + ClipRRect( + borderRadius: BorderRadius.circular(4), + child: LinearProgressIndicator( + value: ratio, + minHeight: 6, + backgroundColor: theme.dividerColor.withValues(alpha: 0.15), + color: isDoneS1 ? const Color(0xFF15803D) : pacingTheme.primary, + ), + ), + const SizedBox(height: 14), + ], + + // Riga Medie Giornaliere: Blocchi Immediati e Grandi + Wrap( + spacing: 12, + runSpacing: 8, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + // Blocco 1: Media Attuale + _buildRateBadge( + label: 'MEDIA ATTUALE', + value: '${cat.actualDailyRate.toStringAsFixed(1)} / gg', + color: theme.colorScheme.primary, + bgColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.2), + borderColor: theme.colorScheme.primary.withValues(alpha: 0.35), + ), + + // Blocco 2: Media Richiesta S1 + if (hasTargets) + () { + final verdino = PacingTheme.of(TargetPacingStatus.inLineS1); + final pink = PacingTheme.of(TargetPacingStatus.recoverable); + final red = PacingTheme.of(TargetPacingStatus.critical); + + Color bColor; + Color bBg; + Color bBorder; + String bValue; + + if (isDoneS1) { + bColor = const Color(0xFF15803D); + bBg = const Color(0xFFDCFCE7); + bBorder = const Color(0xFF86EFAC); + bValue = 'RAGGIUNTO! 🎉'; + } else if (cat.requiredDailyRateS1 <= cat.actualDailyRate) { + bColor = verdino.text; + bBg = verdino.background; + bBorder = verdino.border; + bValue = '${cat.requiredDailyRateS1.toStringAsFixed(1)} / gg'; + } else if (cat.requiredDailyRateS1 <= cat.actualDailyRate * 1.35) { + bColor = pink.text; + bBg = pink.background; + bBorder = pink.border; + bValue = '${cat.requiredDailyRateS1.toStringAsFixed(1)} / gg'; + } else { + bColor = red.text; + bBg = red.background; + bBorder = red.border; + bValue = '${cat.requiredDailyRateS1.toStringAsFixed(1)} / gg'; + } + + return _buildRateBadge( + label: 'SERVE PER S1 (MIN)', + value: bValue, + color: bColor, + bgColor: bBg, + borderColor: bBorder, + ); + }(), + + // Blocco 3: Media Richiesta S2 (se presente) + if (cat.targetS2 > 0) + _buildRateBadge( + label: 'SERVE PER S2 (SFIDA)', + value: isDoneS2 + ? 'RAGGIUNTO! 🚀' + : '${cat.requiredDailyRateS2.toStringAsFixed(1)} / gg', + color: isDoneS2 ? const Color(0xFF15803D) : Colors.purple.shade900, + bgColor: isDoneS2 ? const Color(0xFFDCFCE7) : Colors.purple.shade50, + borderColor: isDoneS2 ? const Color(0xFF86EFAC) : Colors.purple.shade200, + ), + + // Proiezione a fine mese + if (hasTargets) + Padding( + padding: const EdgeInsets.only(left: 4.0), + child: Text( + 'Proiezione fine mese: ~${cat.projectedPieces.round()}', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + ], + ), + ), + ), + ); + } + + // ========================================== + // TAB 2: AVANZAMENTO ADDETTI + // ========================================== + + Widget _buildStaffTab( + BuildContext context, + ThemeData theme, + TargetModel target, + TargetProgressModel progress, + bool isDesktop, + ) { + final staffMembers = target.individualTargets; + + if (staffMembers.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.group_off_outlined, size: 48, color: Colors.grey.shade400), + const SizedBox(height: 12), + const Text( + 'Nessun addetto associato a questo target.', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + ], + ), + ), + ); + } + + return SingleChildScrollView( + padding: EdgeInsets.all(isDesktop ? 24.0 : 16.0), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 1100), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Avanzamento e Quote Collaboratori', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + Text( + '${staffMembers.length} collaboratori', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 16), + + // Card o ExpansionTile per ciascun addetto + ...staffMembers.map((it) { + final staffId = it.staffId; + final staffName = it.staff?.name ?? 'Addetto'; + final sp = progress.staffProgress[staffId]; + + final totalS1 = it.metrics.totalLevel1; + final totalS2 = it.metrics.totalLevel2; + final hasTargets = totalS1 > 0 || totalS2 > 0; + final actualTotal = sp?.totalActualPieces ?? 0; + final s1Ratio = totalS1 > 0 ? (actualTotal / totalS1).clamp(0.0, 1.0) : 0.0; + + final staffPacingStatus = sp == null || !hasTargets + ? TargetPacingStatus.notSet + : (actualTotal >= totalS1 + ? (totalS2 > 0 && actualTotal >= totalS2 + ? TargetPacingStatus.inLineS2 + : TargetPacingStatus.inLineS1) + : (sp.overallRequiredDailyRateS1 <= sp.overallActualDailyRate + ? TargetPacingStatus.inLineS1 + : (sp.overallRequiredDailyRateS1 <= sp.overallActualDailyRate * 1.35 + ? TargetPacingStatus.recoverable + : TargetPacingStatus.critical))); + final staffTheme = PacingTheme.of(staffPacingStatus); + + return Container( + margin: const EdgeInsets.only(bottom: 14), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(16), + border: Border.all( + color: hasTargets + ? staffTheme.border.withValues(alpha: 0.8) + : theme.dividerColor.withValues(alpha: 0.3), + width: 1.2, + ), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(16), + child: Container( + decoration: BoxDecoration( + border: Border( + left: BorderSide( + color: hasTargets ? staffTheme.primary : Colors.grey.shade400, + width: 6, + ), + ), + ), + child: ExpansionTile( + leading: CircleAvatar( + backgroundColor: hasTargets + ? staffTheme.background + : theme.colorScheme.surfaceContainerHighest, + child: Text( + staffName.isNotEmpty ? staffName[0].toUpperCase() : 'A', + style: TextStyle( + color: hasTargets + ? staffTheme.text + : theme.colorScheme.onSurfaceVariant, + fontWeight: FontWeight.bold, + ), + ), + ), + title: Row( + children: [ + Expanded( + child: Text( + staffName, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), + ), + ), + if (!hasTargets) + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + 'Nessun obiettivo', + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ) + else + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + '$actualTotal', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w900, + color: actualTotal >= totalS1 + ? const Color(0xFF15803D) + : theme.colorScheme.onSurface, + ), + ), + Text( + ' / $totalS1', + style: TextStyle( + fontSize: 14, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + if (totalS2 > 0) ...[ + const SizedBox(width: 6), + Text( + '(S2: $totalS2)', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: actualTotal >= totalS2 + ? const Color(0xFF15803D) + : Colors.purple.shade700, + ), + ), + ], + ], + ), + ], + ), + subtitle: hasTargets && sp != null + ? Padding( + padding: const EdgeInsets.only(top: 6.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 10, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Text( + 'Media: ${sp.overallActualDailyRate.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: theme.colorScheme.primary, + ), + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3), + decoration: BoxDecoration( + color: staffTheme.background, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: staffTheme.border), + ), + child: Text( + actualTotal >= totalS1 + ? 'S1 RAGGIUNTO! 🎉' + : 'Req S1: ${sp.overallRequiredDailyRateS1.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: staffTheme.text, + ), + ), + ), + if (totalS2 > 0) + Text( + 'Req S2: ${sp.overallRequiredDailyRateS2.toStringAsFixed(1)} / gg', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.purple.shade700, + ), + ), + ], + ), + const SizedBox(height: 6), + ClipRRect( + borderRadius: BorderRadius.circular(3), + child: LinearProgressIndicator( + value: s1Ratio, + minHeight: 5, + backgroundColor: theme.dividerColor.withValues(alpha: 0.15), + color: actualTotal >= totalS1 + ? const Color(0xFF15803D) + : staffTheme.primary, + ), + ), + ], + ), + ) + : Text( + 'Tutte le quote impostate a 0', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + children: [ + if (hasTargets && sp != null) ...[ + const Divider(height: 1), + Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Dettaglio Obiettivi di $staffName', + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 10), + ...sp.categories.values.where((c) => c.targetS1 > 0 || c.targetS2 > 0).map((c) { + return _buildStaffCategoryRow(theme, c); + }), + ], + ), + ), + ], + ], + ), + ), + ), + ); + }), + ], + ), + ), + ), + ); + } + + Widget _buildStaffCategoryRow(ThemeData theme, CategoryProgress c) { + 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), + border: Border( + left: BorderSide(color: pacingTheme.primary, width: 4), + ), + ), + child: Row( + children: [ + 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, + ), + ), + ), + ), + ], + ), + ); + } + + Widget _buildPill(String text, Color color, Color bg, [Color? border]) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 9, vertical: 4), + decoration: BoxDecoration( + color: bg, + borderRadius: BorderRadius.circular(8), + border: Border.all(color: border ?? color.withValues(alpha: 0.3), width: 1.2), + ), + child: Text( + text, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ); + } + + Widget _buildRateBadge({ + required String label, + required String value, + required Color color, + required Color bgColor, + required Color borderColor, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 7), + decoration: BoxDecoration( + color: bgColor, + borderRadius: BorderRadius.circular(10), + border: Border.all(color: borderColor, width: 1.2), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + label, + style: TextStyle( + fontSize: 9, + fontWeight: FontWeight.bold, + color: color.withValues(alpha: 0.85), + letterSpacing: 0.4, + ), + ), + const SizedBox(height: 2), + Text( + value, + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w900, + color: color, + ), + ), + ], + ), + ); + } +} diff --git a/lib/features/targets/ui/target_form_screen.dart b/lib/features/targets/ui/target_form_screen.dart index d30fb1c..3e43fe1 100644 --- a/lib/features/targets/ui/target_form_screen.dart +++ b/lib/features/targets/ui/target_form_screen.dart @@ -324,13 +324,13 @@ class _TargetFormScreenState extends State Row( children: [ Chip( - label: Text('Tot. S1: ${metrics.totalLevel1} pz'), + label: Text('Tot. S1: ${metrics.totalLevel1}'), backgroundColor: Colors.blue.withValues(alpha: 0.1), side: BorderSide.none, ), const SizedBox(width: 8), Chip( - label: Text('Tot. S2: ${metrics.totalLevel2} pz'), + label: Text('Tot. S2: ${metrics.totalLevel2}'), backgroundColor: Colors.deepPurple.withValues( alpha: 0.1, ), @@ -548,29 +548,35 @@ class _TargetFormScreenState extends State icon: Icons.bolt_outlined, color: Colors.blue, label: 'Energia TIM', - val1: metrics.energiaTim, - val2: 0, - showLevel2: false, + val1: metrics.energiaTim1, + val2: metrics.energiaTim2, + showLevel2: true, onChanged1: (v) => cubit.updateStoreMetrics( - metrics.copyWith(energiaTim: v), + metrics.copyWith(energiaTim1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(energiaTim2: v), ), - onChanged2: (_) {}, ), const Divider(), _buildMetricInputRow( theme: theme, icon: Icons.flash_on_outlined, color: Colors.teal, - label: 'Energia Altri Gestori', - val1: metrics.energiaAltri, - val2: 0, - showLevel2: false, + label: 'Energia Non TIM', + val1: metrics.energiaAltri1, + val2: metrics.energiaAltri2, + showLevel2: true, onChanged1: (v) => cubit.updateStoreMetrics( - metrics.copyWith(energiaAltri: v), + metrics.copyWith(energiaAltri1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(energiaAltri2: v), ), - onChanged2: (_) {}, ), ], ), @@ -632,7 +638,7 @@ class _TargetFormScreenState extends State // Barra Azioni Rapide Card( elevation: 0, - color: theme.colorScheme.primary.withValues(alpha: 0.05), + color: theme.colorScheme.primary.withValues(alpha: 0.06), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide( @@ -643,18 +649,25 @@ class _TargetFormScreenState extends State padding: const EdgeInsets.all(16.0), child: Row( children: [ - Icon(Icons.auto_awesome, color: theme.colorScheme.primary), - const SizedBox(width: 12), + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(10), + ), + child: Icon(Icons.tune_rounded, color: theme.colorScheme.primary, size: 22), + ), + const SizedBox(width: 14), Expanded( child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ const Text( - 'Ripartizione Automatica', + 'Ripartizione Automatica Quote', style: TextStyle(fontWeight: FontWeight.bold), ), Text( - 'Suddividi le quote del negozio in parti uguali tra i ${state.storeStaff.length} addetti.', + 'Seleziona quali addetti hanno obiettivi e calcola la ripartizione con pesi e part-time.', style: TextStyle( fontSize: 12, color: theme.colorScheme.onSurfaceVariant, @@ -663,17 +676,12 @@ class _TargetFormScreenState extends State ], ), ), - OutlinedButton.icon( - icon: const Icon(Icons.call_split, size: 18), - label: const Text('Distribuisci'), + const SizedBox(width: 10), + FilledButton.tonalIcon( + icon: const Icon(Icons.tune_rounded, size: 18), + label: const Text('Ripartisci Quote'), onPressed: () { - cubit.distributeMetricsEqually(); - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Quote distribuite in parti uguali!'), - duration: Duration(seconds: 2), - ), - ); + _showDistributionDialog(context, cubit, state); }, ), ], @@ -688,6 +696,7 @@ class _TargetFormScreenState extends State final staffName = staff?.name ?? 'Addetto'; final totalL1 = it.metrics.totalLevel1; final totalL2 = it.metrics.totalLevel2; + final hasObjectives = totalL1 > 0 || totalL2 > 0; return Card( elevation: 0, @@ -695,27 +704,60 @@ class _TargetFormScreenState extends State shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(16), side: BorderSide( - color: theme.dividerColor.withValues(alpha: 0.5), + color: hasObjectives + ? theme.dividerColor.withValues(alpha: 0.6) + : theme.dividerColor.withValues(alpha: 0.25), ), ), clipBehavior: Clip.antiAlias, child: ExpansionTile( leading: CircleAvatar( - backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.1), + backgroundColor: hasObjectives + ? theme.colorScheme.primary.withValues(alpha: 0.1) + : theme.colorScheme.surfaceContainerHighest, child: Text( staffName.isNotEmpty ? staffName[0].toUpperCase() : 'A', style: TextStyle( - color: theme.colorScheme.primary, + color: hasObjectives + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, fontWeight: FontWeight.bold, ), ), ), - title: Text( - staffName, - style: const TextStyle(fontWeight: FontWeight.bold), + title: Row( + children: [ + Expanded( + child: Text( + staffName, + style: TextStyle( + fontWeight: FontWeight.bold, + color: hasObjectives ? null : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + if (!hasObjectives) + Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + 'Nessun obiettivo', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w500, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], ), subtitle: Text( - 'Soglia 1: $totalL1 pz • Soglia 2: $totalL2 pz', + hasObjectives + ? 'Soglia 1: $totalL1 • Soglia 2: $totalL2' + : 'Tutte le quote a 0', style: TextStyle( fontSize: 12, color: theme.colorScheme.onSurfaceVariant, @@ -883,26 +925,32 @@ class _TargetFormScreenState extends State _buildStaffMetricRow( theme: theme, label: 'Energia TIM', - val1: it.metrics.energiaTim, - val2: 0, - showLevel2: false, + val1: it.metrics.energiaTim1, + val2: it.metrics.energiaTim2, + showLevel2: true, onChanged1: (v) => cubit.updateIndividualMetrics( it.staffId, - it.metrics.copyWith(energiaTim: v), + it.metrics.copyWith(energiaTim1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(energiaTim2: v), ), - onChanged2: (_) {}, ), _buildStaffMetricRow( theme: theme, - label: 'Energia Altri', - val1: it.metrics.energiaAltri, - val2: 0, - showLevel2: false, + label: 'Energia Non TIM', + val1: it.metrics.energiaAltri1, + val2: it.metrics.energiaAltri2, + showLevel2: true, onChanged1: (v) => cubit.updateIndividualMetrics( it.staffId, - it.metrics.copyWith(energiaAltri: v), + it.metrics.copyWith(energiaAltri1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(energiaAltri2: v), ), - onChanged2: (_) {}, ), const SizedBox(height: 8), ], @@ -1055,6 +1103,34 @@ class _TargetFormScreenState extends State cubit.setDateRange(start, end); } } + + void _showDistributionDialog( + BuildContext context, + TargetFormCubit cubit, + TargetFormState state, + ) { + showDialog( + context: context, + builder: (dialogContext) { + return _DistributionDialog( + state: state, + onApply: (weights) { + cubit.distributeMetrics(staffWeights: weights); + final activeCount = weights.values.where((w) => w > 0).length; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + 'Quote ripartite con successo tra $activeCount addetti!', + ), + backgroundColor: Colors.green.shade700, + behavior: SnackBarBehavior.floating, + ), + ); + }, + ); + }, + ); + } } class _NumberInputField extends StatefulWidget { @@ -1124,3 +1200,449 @@ class _NumberInputFieldState extends State<_NumberInputField> { ); } } + +class _DistributionDialog extends StatefulWidget { + final TargetFormState state; + final Function(Map weights) onApply; + + const _DistributionDialog({ + required this.state, + required this.onApply, + }); + + @override + State<_DistributionDialog> createState() => _DistributionDialogState(); +} + +class _DistributionDialogState extends State<_DistributionDialog> { + late Map _selected; + late Map _weights; + + @override + void initState() { + super.initState(); + final anyHasTarget = widget.state.individualTargets.any( + (it) => it.metrics.totalLevel1 > 0 || it.metrics.totalLevel2 > 0, + ); + + _selected = { + for (final it in widget.state.individualTargets) + it.staffId: anyHasTarget + ? (it.metrics.totalLevel1 > 0 || it.metrics.totalLevel2 > 0) + : true, + }; + + _weights = { + for (final it in widget.state.individualTargets) it.staffId: 1.0, + }; + } + + double get _totalActiveWeight { + double sum = 0.0; + for (final it in widget.state.individualTargets) { + if (_selected[it.staffId] == true) { + sum += _weights[it.staffId] ?? 1.0; + } + } + return sum; + } + + double _getShare(String staffId) { + if (_selected[staffId] != true) return 0.0; + final total = _totalActiveWeight; + if (total <= 0) return 0.0; + return (_weights[staffId] ?? 1.0) / total; + } + + void _selectAll(bool select) { + setState(() { + for (final it in widget.state.individualTargets) { + _selected[it.staffId] = select; + } + }); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final activeCount = _selected.values.where((v) => v).length; + final totalCount = widget.state.individualTargets.length; + final storeMetrics = widget.state.target.metrics; + + return Dialog( + shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)), + clipBehavior: Clip.antiAlias, + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 580, maxHeight: 750), + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Header + Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: theme.colorScheme.primaryContainer, + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.tune_rounded, + color: theme.colorScheme.primary, + size: 24, + ), + ), + const SizedBox(width: 14), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Ripartizione Quote Addetti', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Seleziona chi partecipa e regola il carico (es. part-time o ferie)', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.of(context).pop(), + ), + ], + ), + const SizedBox(height: 16), + + // Barra Azioni Rapide (Seleziona tutti / Deseleziona) + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Row( + children: [ + TextButton.icon( + icon: const Icon(Icons.select_all, size: 18), + label: const Text('Tutti'), + onPressed: () => _selectAll(true), + ), + TextButton.icon( + icon: const Icon(Icons.deselect_outlined, size: 18), + label: const Text('Nessuno'), + onPressed: () => _selectAll(false), + ), + ], + ), + Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 4), + decoration: BoxDecoration( + color: activeCount > 0 + ? theme.colorScheme.primaryContainer + : theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(12), + ), + child: Text( + '$activeCount su $totalCount attivi', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: activeCount > 0 + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + const Divider(), + + // Lista Addetti con slider e pesi + Flexible( + child: ListView.separated( + shrinkWrap: true, + itemCount: widget.state.individualTargets.length, + separatorBuilder: (context, index) => const SizedBox(height: 10), + itemBuilder: (context, index) { + final it = widget.state.individualTargets[index]; + final staff = it.staff; + final staffName = staff?.name ?? 'Addetto'; + final isSelected = _selected[it.staffId] ?? false; + final weight = _weights[it.staffId] ?? 1.0; + final share = _getShare(it.staffId); + + return Container( + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: isSelected + ? theme.colorScheme.primary.withValues(alpha: 0.5) + : theme.dividerColor.withValues(alpha: 0.3), + width: isSelected ? 1.5 : 1.0, + ), + color: isSelected + ? theme.colorScheme.primary.withValues(alpha: 0.03) + : theme.colorScheme.surface, + ), + padding: const EdgeInsets.all(12), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Intestazione con checkbox, avatar e share % + Row( + children: [ + Checkbox( + value: isSelected, + onChanged: (v) { + setState(() { + _selected[it.staffId] = v ?? false; + }); + }, + ), + CircleAvatar( + radius: 16, + backgroundColor: isSelected + ? theme.colorScheme.primary.withValues(alpha: 0.12) + : theme.colorScheme.surfaceContainerHighest, + child: Text( + staffName.isNotEmpty + ? staffName[0].toUpperCase() + : 'A', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: isSelected + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + staffName, + style: TextStyle( + fontWeight: FontWeight.bold, + fontSize: 14, + color: isSelected + ? null + : theme.colorScheme.onSurfaceVariant, + ), + ), + if (staff?.jobTitle != null && + staff!.jobTitle!.isNotEmpty) + Text( + staff.jobTitle!, + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 4, + ), + decoration: BoxDecoration( + color: isSelected + ? theme.colorScheme.primary.withValues(alpha: 0.1) + : theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(8), + ), + child: Text( + isSelected + ? 'Quota: ${(share * 100).toStringAsFixed(0)}%' + : 'Escluso (0)', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: isSelected + ? theme.colorScheme.primary + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + + // Se selezionato: regolazione carico / slider + if (isSelected) ...[ + const SizedBox(height: 8), + Padding( + padding: const EdgeInsets.only(left: 48.0, right: 8.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + 'Carico: ${(weight * 100).round()}%', + style: const TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + ), + ), + const Spacer(), + _buildPresetChip('100%', 1.0, it.staffId), + const SizedBox(width: 4), + _buildPresetChip('75%', 0.75, it.staffId), + const SizedBox(width: 4), + _buildPresetChip('50%', 0.50, it.staffId), + const SizedBox(width: 4), + _buildPresetChip('25%', 0.25, it.staffId), + ], + ), + SliderTheme( + data: SliderTheme.of(context).copyWith( + trackHeight: 3, + thumbShape: const RoundSliderThumbShape( + enabledThumbRadius: 7, + ), + overlayShape: const RoundSliderOverlayShape( + overlayRadius: 14, + ), + ), + child: Slider( + value: weight, + min: 0.1, + max: 1.0, + divisions: 18, + label: '${(weight * 100).round()}%', + onChanged: (v) { + setState(() { + _weights[it.staffId] = v; + }); + }, + ), + ), + if (storeMetrics.totalLevel1 > 0 || + storeMetrics.totalLevel2 > 0) + Text( + 'Previsto: ~${(storeMetrics.totalLevel1 * share).floor()} (Soglia 1) • ~${(storeMetrics.totalLevel2 * share).floor()} (Soglia 2)', + style: TextStyle( + fontSize: 11, + color: theme.colorScheme.primary, + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ), + ], + ], + ), + ); + }, + ), + ), + + const SizedBox(height: 12), + const Divider(), + const SizedBox(height: 8), + + // Riepilogo Totale Negozio + Row( + children: [ + Icon( + Icons.store_mall_directory_outlined, + size: 18, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 8), + Expanded( + child: Text( + 'Target Negozio: ${storeMetrics.totalLevel1} (Min) • ${storeMetrics.totalLevel2} (Sfidante)', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ], + ), + const SizedBox(height: 16), + + // Bottoni di Conferma + Row( + mainAxisAlignment: MainAxisAlignment.end, + children: [ + TextButton( + onPressed: () => Navigator.of(context).pop(), + child: const Text('Annulla'), + ), + const SizedBox(width: 8), + FilledButton.icon( + icon: const Icon(Icons.check, size: 18), + label: const Text('Applica Ripartizione'), + onPressed: activeCount == 0 + ? null + : () { + final finalWeights = {}; + for (final it in widget.state.individualTargets) { + final isSel = _selected[it.staffId] ?? false; + finalWeights[it.staffId] = + isSel ? (_weights[it.staffId] ?? 1.0) : 0.0; + } + widget.onApply(finalWeights); + Navigator.of(context).pop(); + }, + ), + ], + ), + ], + ), + ), + ), + ); + } + + Widget _buildPresetChip(String label, double val, String staffId) { + final currentVal = _weights[staffId] ?? 1.0; + final isCurrent = (currentVal - val).abs() < 0.01; + final theme = Theme.of(context); + + return InkWell( + borderRadius: BorderRadius.circular(6), + onTap: () { + setState(() { + _weights[staffId] = val; + }); + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2), + decoration: BoxDecoration( + color: isCurrent + ? theme.colorScheme.primary + : theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(6), + ), + child: Text( + label, + style: TextStyle( + fontSize: 10, + fontWeight: isCurrent ? FontWeight.bold : FontWeight.normal, + color: isCurrent + ? theme.colorScheme.onPrimary + : theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ); + } +} + diff --git a/lib/features/targets/ui/target_list_screen.dart b/lib/features/targets/ui/target_list_screen.dart index 2f701a1..67257b1 100644 --- a/lib/features/targets/ui/target_list_screen.dart +++ b/lib/features/targets/ui/target_list_screen.dart @@ -5,6 +5,7 @@ import 'package:flux/core/routes/routes.dart'; import 'package:flux/features/master_data/store/bloc/store_cubit.dart'; import 'package:flux/features/targets/blocs/target_list_cubit.dart'; import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/features/targets/models/target_progress_model.dart'; import 'package:go_router/go_router.dart'; import 'package:intl/intl.dart'; @@ -172,7 +173,13 @@ class _TargetListScreenState extends State { separatorBuilder: (_, _) => const SizedBox(height: 16), itemBuilder: (context, index) { final target = state.targets[index]; - return _buildTargetCard(context, target, theme); + final progress = state.progressMap[target.id]; + return _buildTargetCard( + context, + target, + theme, + progress: progress, + ); }, ), ); @@ -321,8 +328,9 @@ class _TargetListScreenState extends State { Widget _buildTargetCard( BuildContext context, TargetModel target, - ThemeData theme, - ) { + ThemeData theme, { + TargetProgressModel? progress, + }) { final title = _formatMonthYear(target.startDay); final range = _formatDateRange(target.startDay, target.endDay); final storeName = target.store?.name ?? 'Negozio'; @@ -425,32 +433,239 @@ class _TargetListScreenState extends State { const Divider(height: 1), const SizedBox(height: 16), - // Riga 2: Indicatori Totali e Statistiche Rapide - Wrap( - spacing: 12, - runSpacing: 8, - children: [ - _buildMetricBadge( - label: 'Soglia 1 (Totale)', - value: '$totalL1 pz', - color: Colors.blue, - icon: Icons.flag_outlined, - ), - if (totalL2 > 0) + // Riga 2: Chip Strategici di Pacing & Avanzamento (4 Colori: Verde, Verdino, Rosa, Rosso) + if (progress != null) ...[ + () { + final greenTheme = PacingTheme.of(TargetPacingStatus.inLineS2); + final verdinoTheme = PacingTheme.of(TargetPacingStatus.inLineS1); + final pinkTheme = PacingTheme.of(TargetPacingStatus.recoverable); + final redTheme = PacingTheme.of(TargetPacingStatus.critical); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + spacing: 8, + runSpacing: 8, + children: [ + // 1. Verde pieno: In linea con Soglia 2 (Sfidante) + if (progress.countInLineS2 > 0) + _buildSmartChip( + icon: greenTheme.icon, + label: '${progress.countInLineS2} Sfidante (Verde)', + color: greenTheme.text, + backgroundColor: greenTheme.background, + borderColor: greenTheme.border, + ), + + // 2. Verdino: In linea con Soglia 1 (Minimo) + if (progress.countInLineS1 > 0) + _buildSmartChip( + icon: verdinoTheme.icon, + label: '${progress.countInLineS1} Minimo (Verdino)', + color: verdinoTheme.text, + backgroundColor: verdinoTheme.background, + borderColor: verdinoTheme.border, + ), + + // 3. Rosa: Sotto ritmo ma recuperabile (Da spingere) + if (progress.countRecoverable > 0) + _buildSmartChip( + icon: pinkTheme.icon, + label: '${progress.countRecoverable} Da spingere (Rosa)', + color: pinkTheme.text, + backgroundColor: pinkTheme.background, + borderColor: pinkTheme.border, + ), + + // 4. Rosso: In ritardo critico + if (progress.countCritical > 0) + _buildSmartChip( + icon: redTheme.icon, + label: '${progress.countCritical} In ritardo (Rosso)', + color: redTheme.text, + backgroundColor: redTheme.background, + borderColor: redTheme.border, + ), + + // Se tutti sono a target + if (progress.countBehind == 0 && progress.countTotalActive > 0) + _buildSmartChip( + icon: Icons.star_rounded, + label: 'Tutti gli obiettivi a ritmo! 🚀', + color: greenTheme.text, + backgroundColor: greenTheme.background, + borderColor: greenTheme.border, + ), + + // Addetti + _buildSmartChip( + icon: Icons.people_outline, + label: '$staffCount addetti', + color: Colors.blue.shade900, + backgroundColor: Colors.blue.shade50, + borderColor: Colors.blue.shade200, + ), + ], + ), + const SizedBox(height: 14), + + // Box Grande & Immediato: Quantità, Media Attuale, Media Richiesta + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.35), + borderRadius: BorderRadius.circular(14), + border: Border.all( + color: theme.colorScheme.outlineVariant.withValues(alpha: 0.5), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + Icons.calendar_month_outlined, + size: 15, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 6), + Text( + '${progress.elapsedWorkingDays} gg trascorsi • ${progress.remainingWorkingDays} gg rimasti (escluse dom. e festivi)', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + const SizedBox(height: 12), + Wrap( + spacing: 12, + runSpacing: 10, + children: [ + // 1. QUANTITÀ / VOLUME + _buildPacingMetricCard( + title: 'QUANTITÀ FATTA', + value: '${progress.totalActualPieces}', + suffix: '/ ${progress.totalTargetS1}', + note: progress.totalTargetS2 > 0 + ? 'Sfida: ${progress.totalTargetS2}' + : 'Target Minimo', + color: theme.colorScheme.onSurface, + backgroundColor: theme.colorScheme.surface, + borderColor: theme.colorScheme.outlineVariant.withValues(alpha: 0.6), + ), + + // 2. MEDIA ATTUALE + _buildPacingMetricCard( + title: 'MEDIA ATTUALE', + value: progress.overallActualDailyRate.toStringAsFixed(1), + suffix: '/ gg', + note: 'Ritmo tenuto finora', + color: theme.colorScheme.primary, + backgroundColor: theme.colorScheme.primaryContainer.withValues(alpha: 0.2), + borderColor: theme.colorScheme.primary.withValues(alpha: 0.35), + ), + + // 3. MEDIA RICHIESTA S1 (Colorata in base al semaforo) + () { + final isS1Done = progress.totalActualPieces >= progress.totalTargetS1; + Color cardColor; + Color cardBg; + Color cardBorder; + String note; + + if (isS1Done) { + cardColor = greenTheme.primary; + cardBg = greenTheme.background; + cardBorder = greenTheme.border; + note = 'Obiettivo centrato!'; + } else if (progress.overallRequiredDailyRateS1 <= progress.overallActualDailyRate) { + cardColor = verdinoTheme.primary; + cardBg = verdinoTheme.background; + cardBorder = verdinoTheme.border; + note = 'In linea col ritmo'; + } else if (progress.overallRequiredDailyRateS1 <= progress.overallActualDailyRate * 1.35) { + cardColor = pinkTheme.primary; + cardBg = pinkTheme.background; + cardBorder = pinkTheme.border; + note = 'Serve spingere'; + } else { + cardColor = redTheme.primary; + cardBg = redTheme.background; + cardBorder = redTheme.border; + note = 'Serve forte spinta'; + } + + return _buildPacingMetricCard( + title: 'MEDIA RICHIESTA S1', + value: isS1Done + ? 'CENTRATO!' + : progress.overallRequiredDailyRateS1.toStringAsFixed(1), + suffix: isS1Done ? '🎉' : '/ gg', + note: note, + color: cardColor, + backgroundColor: cardBg, + borderColor: cardBorder, + ); + }(), + + // 4. MEDIA RICHIESTA S2 (se presente) + if (progress.totalTargetS2 > 0) ...[ + () { + final isS2Done = progress.totalActualPieces >= progress.totalTargetS2; + return _buildPacingMetricCard( + title: 'MEDIA RICHIESTA S2', + value: isS2Done + ? 'CENTRATO!' + : progress.overallRequiredDailyRateS2.toStringAsFixed(1), + suffix: isS2Done ? '🚀' : '/ gg', + note: isS2Done ? 'Sfidante raggiunto!' : 'Per lo sfidante', + color: isS2Done ? greenTheme.primary : Colors.purple.shade700, + backgroundColor: isS2Done ? greenTheme.background : Colors.purple.shade50, + borderColor: isS2Done ? greenTheme.border : Colors.purple.shade200, + ); + }(), + ], + ], + ), + ], + ), + ), + ], + ); + }(), + ] else ...[ + // Fallback indicatori totali di base se il progresso è ancora in calcolo + Wrap( + spacing: 12, + runSpacing: 8, + children: [ _buildMetricBadge( - label: 'Soglia 2 (Sfidante)', - value: '$totalL2 pz', - color: Colors.deepPurple, - icon: Icons.stars_outlined, + label: 'Soglia 1 (Totale)', + value: '$totalL1', + color: Colors.blue, + icon: Icons.flag_outlined, ), - _buildMetricBadge( - label: 'Addetti Coinvolti', - value: '$staffCount assegnati', - color: Colors.teal, - icon: Icons.people_outline, - ), - ], - ), + if (totalL2 > 0) + _buildMetricBadge( + label: 'Soglia 2 (Sfidante)', + value: '$totalL2', + color: Colors.deepPurple, + icon: Icons.stars_outlined, + ), + _buildMetricBadge( + label: 'Addetti Coinvolti', + value: '$staffCount assegnati', + color: Colors.teal, + icon: Icons.people_outline, + ), + ], + ), + ], const SizedBox(height: 14), // Pulsante Visualizza Avanzamento @@ -469,6 +684,109 @@ class _TargetListScreenState extends State { ); } + Widget _buildSmartChip({ + required IconData icon, + required String label, + required Color color, + required Color backgroundColor, + Color? borderColor, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: borderColor ?? color.withValues(alpha: 0.3), + width: 1.2, + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 14, color: color), + const SizedBox(width: 6), + Text( + label, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ], + ), + ); + } + + Widget _buildPacingMetricCard({ + required String title, + required String value, + required String suffix, + required String note, + required Color color, + required Color backgroundColor, + required Color borderColor, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10), + decoration: BoxDecoration( + color: backgroundColor, + borderRadius: BorderRadius.circular(12), + border: Border.all(color: borderColor, width: 1.2), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Text( + title, + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.bold, + color: color.withValues(alpha: 0.85), + letterSpacing: 0.5, + ), + ), + const SizedBox(height: 4), + Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.baseline, + textBaseline: TextBaseline.alphabetic, + children: [ + Text( + value, + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w900, + color: color, + ), + ), + const SizedBox(width: 4), + Text( + suffix, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: color.withValues(alpha: 0.8), + ), + ), + ], + ), + const SizedBox(height: 2), + Text( + note, + style: TextStyle( + fontSize: 10, + color: color.withValues(alpha: 0.75), + fontWeight: FontWeight.w500, + ), + ), + ], + ), + ); + } + Widget _buildMetricBadge({ required String label, required String value, diff --git a/lib/service_locator.dart b/lib/service_locator.dart index a93331d..4390a03 100644 --- a/lib/service_locator.dart +++ b/lib/service_locator.dart @@ -28,6 +28,7 @@ import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart'; import 'package:flux/features/tickets/data/ticket_repository.dart'; import 'package:flux/features/tickets/data/tickets_shipping_repository.dart'; import 'package:flux/features/targets/data/targets_repository.dart'; +import 'package:flux/features/targets/data/target_progress_service.dart'; import 'package:flux/features/targets/blocs/target_list_cubit.dart'; import 'package:flux/features/tracking/blocs/tracking_cubit.dart'; import 'package:flux/features/tracking/data/tracking_repository.dart'; @@ -72,6 +73,9 @@ Future init() async { () => DocumentSequenceRepository(), ); sl.registerLazySingleton(() => TargetsRepository()); + sl.registerLazySingleton( + () => TargetProgressService(), + ); //Cubit globali sl.registerLazySingleton( diff --git a/test/core/utils/working_days_helper_test.dart b/test/core/utils/working_days_helper_test.dart new file mode 100644 index 0000000..b41852a --- /dev/null +++ b/test/core/utils/working_days_helper_test.dart @@ -0,0 +1,68 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/core/utils/working_days_helper.dart'; + +void main() { + group('WorkingDaysHelper Tests', () { + test('Identifica correttamente domeniche e festività italiane', () { + // 1 Gennaio (Capodanno) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 1, 1)), isFalse); + + // 6 Gennaio (Epifania) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 1, 6)), isFalse); + + // 25 Aprile (Liberazione) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 4, 25)), isFalse); + + // 1 Maggio (Festa Lavoratori) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 5, 1)), isFalse); + + // 2 Giugno (Festa Repubblica) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 6, 2)), isFalse); + + // 15 Agosto (Ferragosto) + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 8, 15)), isFalse); + + // Domenica qualunque (es. 13 Settembre 2026) + final sunday = DateTime(2026, 9, 13); + expect(sunday.weekday, equals(DateTime.sunday)); + expect(WorkingDaysHelper.isWorkingDay(sunday), isFalse); + + // Lunedì normale lavorativo (es. 14 Settembre 2026) + final monday = DateTime(2026, 9, 14); + expect(monday.weekday, equals(DateTime.monday)); + expect(WorkingDaysHelper.isWorkingDay(monday), isTrue); + + // Sabato (giorno lavorativo nei negozi di telefonia/energia) + final saturday = DateTime(2026, 9, 12); + expect(saturday.weekday, equals(DateTime.saturday)); + expect(WorkingDaysHelper.isWorkingDay(saturday), isTrue); + }); + + test('Calcolo Pasquetta (Lunedì dell\'Angelo)', () { + // Nel 2026 Pasqua è il 5 Aprile, Pasquetta è il 6 Aprile + final easterMonday2026 = WorkingDaysHelper.calculateEasterMonday(2026); + expect(easterMonday2026.month, equals(4)); + expect(easterMonday2026.day, equals(6)); + expect(WorkingDaysHelper.isWorkingDay(DateTime(2026, 4, 6)), isFalse); + }); + + test('Calcolo giorni lavorativi periodo escludendo domeniche', () { + // Settembre 2026: dal 1 al 30 + // Totale 30 giorni, 4 domeniche (6, 13, 20, 27) = 26 giorni lavorativi + final septStart = DateTime(2026, 9, 1); + final septEnd = DateTime(2026, 9, 30); + + final period = WorkingDaysHelper.calculateWorkingDaysPeriod( + start: septStart, + end: septEnd, + now: DateTime(2026, 9, 10), + ); + + expect(period.total, equals(26)); + // Dal 1 al 10 settembre: 10 giorni meno 1 domenica (6 sett) = 9 giorni lavorativi trascorsi + expect(period.elapsed, equals(9)); + // Dal 10 al 30 settembre (10 compreso): 21 giorni meno 3 domeniche (13, 20, 27) = 18 giorni rimanenti + expect(period.remaining, equals(18)); + }); + }); +}