diff --git a/lib/core/layout/app_shell.dart b/lib/core/layout/app_shell.dart index 9cc0c61..1175940 100644 --- a/lib/core/layout/app_shell.dart +++ b/lib/core/layout/app_shell.dart @@ -147,6 +147,14 @@ class _AppMenuState extends State { ], ), + const SizedBox(height: 8), + _buildRouteItem( + title: 'Obiettivi', + icon: Icons.track_changes_outlined, + routeName: Routes.targets, + pathToCheck: '/targets', + isCollapsed: effectivelyCollapsed, + ), const SizedBox(height: 8), // --- IL MENU GERARCHICO (ANAGRAFICHE) --- diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 8e55868..56abf3d 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -61,8 +61,16 @@ import 'package:flux/features/tickets/models/ticket_model.dart'; import 'package:flux/features/tickets/ui/ticket_form_screen.dart'; import 'package:flux/features/tickets/ui/ticket_list_screen.dart'; import 'package:flux/features/tickets/ui/ticket_workspace/ticket_workspace_screen.dart'; +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/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'; import 'package:flux/features/tracking/blocs/tracking_cubit.dart'; import 'package:flux/features/tracking/models/tracking_model.dart'; +import 'package:flux/service_locator.dart'; import 'package:get_it/get_it.dart'; import 'package:go_router/go_router.dart'; @@ -311,10 +319,40 @@ class AppRouter { ); }, ), + GoRoute( + path: '/targets', + name: Routes.targets, + builder: (context, state) => BlocProvider( + create: (_) => sl(), + child: const TargetListScreen(), + ), + ), ], ), // --- DETTAGLI E OPERATIVITÀ (FUORI DALLA SHELL - TUTTO SCHERMO) --- + GoRoute( + path: '/targets/form', + name: Routes.targetForm, + builder: (context, state) { + final existingTarget = state.extra as TargetModel?; + final session = context.read().state; + final companyId = session.company?.id ?? ''; + final defaultStoreId = session.currentStore?.id ?? ''; + + return BlocProvider( + create: (context) => TargetFormCubit( + targetsRepository: sl(), + staffRepository: sl(), + )..init( + initialTarget: existingTarget, + companyId: companyId, + defaultStoreId: defaultStoreId, + ), + child: const TargetFormScreen(), + ); + }, + ), GoRoute( path: '/providers/form', name: Routes.providerForm, diff --git a/lib/core/routes/routes.dart b/lib/core/routes/routes.dart index 5622704..dac5db6 100644 --- a/lib/core/routes/routes.dart +++ b/lib/core/routes/routes.dart @@ -27,4 +27,7 @@ class Routes { static const String tasks = 'tasks'; static const String taskForm = 'task-form'; static const String reminderSettings = 'reminder-settings'; + static const String targets = 'targets'; + static const String targetForm = 'target-form'; + static const String targetDetail = 'target-detail'; } diff --git a/lib/features/master_data/providers/models/provider_model_extensions.dart b/lib/features/master_data/providers/models/provider_model_extensions.dart index 9813a5d..abd0ac2 100644 --- a/lib/features/master_data/providers/models/provider_model_extensions.dart +++ b/lib/features/master_data/providers/models/provider_model_extensions.dart @@ -1,28 +1,42 @@ import 'package:flux/features/master_data/providers/models/provider_model.dart'; import 'package:flux/features/master_data/providers/models/provider_role.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; extension ProviderCompatibility on ProviderModel { - bool supportsOperation(String operationType) { - if (operationType == 'Altro') return true; + bool supportsOperationType(OperationType? operationType) { + if (operationType == null || operationType == OperationType.altro) { + return true; + } switch (operationType) { - case 'AL' || 'MNP': + case OperationType.al || + OperationType.mnp || + OperationType.cb || + OperationType.upselling: return roles.contains(ProviderRole.mobile); - case 'NIP' || 'FWA': + case OperationType.nip || OperationType.fwa: return roles.contains(ProviderRole.landline); - case 'UNICA': + case OperationType.unica: return roles.contains(ProviderRole.landline) || roles.contains(ProviderRole.mobile); - case 'Energy': + case OperationType.energy: return roles.contains(ProviderRole.energy); - case 'Fin': + case OperationType.fin: return roles.contains(ProviderRole.financing); - case 'Entertainment': + case OperationType.entertainment: return roles.contains(ProviderRole.entertainment); - case 'TELEPASS': + case OperationType.telepass: return roles.contains(ProviderRole.telepass); + case OperationType.business: + return roles.contains(ProviderRole.mobile) || + roles.contains(ProviderRole.landline); default: return true; } } + + bool supportsOperation(String operationType) { + final type = OperationType.fromValue(operationType); + return supportsOperationType(type); + } } diff --git a/lib/features/operations/blocs/operation_details_form_cubit.dart b/lib/features/operations/blocs/operation_details_form_cubit.dart index 7960cd9..0998efe 100644 --- a/lib/features/operations/blocs/operation_details_form_cubit.dart +++ b/lib/features/operations/blocs/operation_details_form_cubit.dart @@ -4,6 +4,7 @@ import 'package:flux/features/master_data/products/models/model_model.dart'; import 'package:flux/features/master_data/providers/models/provider_model.dart'; import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; part 'operation_details_form_state.dart'; @@ -22,7 +23,7 @@ class OperationDetailsFormCubit extends Cubit { if (initialDetail == null && allProviders != null && allProviders.isNotEmpty) { - const defaultType = 'AL'; + const defaultType = OperationType.al; setTypeWithSmartDefaults( newType: defaultType, allProviders: allProviders, @@ -32,7 +33,7 @@ class OperationDetailsFormCubit extends Cubit { } void updateFields({ - String? type, + OperationType? type, String? subType, ProviderModel? provider, ModelModel? model, @@ -79,7 +80,7 @@ class OperationDetailsFormCubit extends Cubit { } void setTypeWithSmartDefaults({ - required String newType, + required OperationType newType, required List allProviders, String? defaultProviderId, }) { @@ -88,7 +89,7 @@ class OperationDetailsFormCubit extends Cubit { final foundDefault = allProviders.firstWhere( (p) => p.id == defaultProviderId && - p.supportsOperation(newType) && + p.supportsOperationType(newType) && p.isActive, orElse: () => const ProviderModel(companyId: '', name: ''), ); @@ -98,7 +99,7 @@ class OperationDetailsFormCubit extends Cubit { } if (selectedProvider == null) { final foundCompatible = allProviders.firstWhere( - (p) => p.supportsOperation(newType) && p.isActive, + (p) => p.supportsOperationType(newType) && p.isActive, orElse: () => const ProviderModel(companyId: '', name: ''), ); if (foundCompatible.id != null) { @@ -109,7 +110,7 @@ class OperationDetailsFormCubit extends Cubit { final current = state.operationDetail; final updated = current.copyWith( type: newType, - subType: newType == 'Energy' ? 'Luce' : null, + subType: newType == OperationType.energy ? EnergySubtypes.luce : null, provider: selectedProvider != null ? () => selectedProvider : null, providerId: selectedProvider?.id, ); diff --git a/lib/features/operations/models/operation_detail_model.dart b/lib/features/operations/models/operation_detail_model.dart index a2bf7c4..5e67e2a 100644 --- a/lib/features/operations/models/operation_detail_model.dart +++ b/lib/features/operations/models/operation_detail_model.dart @@ -2,12 +2,13 @@ import 'package:equatable/equatable.dart'; import 'package:flux/core/enums_and_consts/consts.dart'; import 'package:flux/features/master_data/products/models/model_model.dart'; import 'package:flux/features/master_data/providers/models/provider_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; class OperationDetailModel extends Equatable { final String? id; final DateTime? createdAt; final String operationId; - final String? type; + final OperationType? type; final String? providerId; final String? modelId; final String? description; @@ -57,7 +58,7 @@ class OperationDetailModel extends Equatable { String? id, DateTime? createdAt, String? operationId, - String? type, + OperationType? type, String? providerId, String? modelId, String? description, @@ -84,7 +85,7 @@ class OperationDetailModel extends Equatable { ); factory OperationDetailModel.empty() { - return OperationDetailModel(); + return const OperationDetailModel(); } factory OperationDetailModel.fromMap(Map map) { @@ -94,7 +95,7 @@ class OperationDetailModel extends Equatable { ? DateTime.parse(map['created_at']) : null, operationId: map['operation_id'] as String? ?? '', - type: map['type'] as String?, + type: OperationType.fromValue(map['type'] as String?), providerId: map['provider_id'] as String?, modelId: map['model_id'] as String?, description: map['description'] as String?, @@ -129,7 +130,7 @@ class OperationDetailModel extends Equatable { return { if (id?.isNotEmpty == true) 'id': id, if (operationId.isNotEmpty) 'operation_id': operationId, - if (type?.isNotEmpty == true) 'type': type, + if (type != null) 'type': type!.value, if (pId?.isNotEmpty == true) 'provider_id': pId, if (mId?.isNotEmpty == true) 'model_id': mId, if (description?.isNotEmpty == true) 'description': description, diff --git a/lib/features/operations/models/operation_type.dart b/lib/features/operations/models/operation_type.dart new file mode 100644 index 0000000..d2de19f --- /dev/null +++ b/lib/features/operations/models/operation_type.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; + +/// Enum fortemente tipizzato per i tipi di operazione/servizio nel sistema Flux +enum OperationType { + al( + value: 'AL', + label: 'Attivazione Linea', + shortLabel: 'AL', + icon: Icons.sim_card_outlined, + color: Colors.blue, + ), + mnp( + value: 'MNP', + label: 'Portabilità', + shortLabel: 'MNP', + icon: Icons.phone_forwarded_outlined, + color: Colors.indigo, + ), + nip( + value: 'NIP', + label: 'Nuovo Impianto', + shortLabel: 'NIP', + icon: Icons.home_repair_service_outlined, + color: Colors.cyan, + ), + unica( + value: 'UNICA', + label: 'TIM Unica / Convergenza', + shortLabel: 'UNICA', + icon: Icons.merge_type_outlined, + color: Colors.orange, + ), + fwa( + value: 'FWA', + label: 'Fixed Wireless Access', + shortLabel: 'FWA', + icon: Icons.router_outlined, + color: Colors.teal, + ), + telepass( + value: 'TELEPASS', + label: 'Telepass', + shortLabel: 'Telepass', + icon: Icons.directions_car_outlined, + color: Colors.amber, + ), + energy( + value: 'Energy', + label: 'Energia Luce & Gas', + shortLabel: 'Energy', + icon: Icons.bolt_outlined, + color: Colors.green, + ), + fin( + value: 'Fin', + label: 'Finanziamento', + shortLabel: 'Fin', + icon: Icons.credit_card_outlined, + color: Colors.purple, + ), + entertainment( + value: 'Entertainment', + label: 'Contenuti & Intrattenimento', + shortLabel: 'Entertainment', + icon: Icons.live_tv_outlined, + color: Colors.redAccent, + ), + cb( + value: 'CB', + label: 'Customer Base', + shortLabel: 'CB', + icon: Icons.people_alt_outlined, + color: Colors.deepOrange, + ), + upselling( + value: 'Upselling', + label: 'Upselling / Cambio Offerta', + shortLabel: 'Upselling', + icon: Icons.trending_up_outlined, + color: Colors.deepPurple, + ), + business( + value: 'Business', + label: 'Servizio Business', + shortLabel: 'Business', + icon: Icons.business_center_outlined, + color: Colors.blueGrey, + ), + altro( + value: 'Altro', + label: 'Altro Servizio', + shortLabel: 'Altro', + icon: Icons.more_horiz_outlined, + color: Colors.grey, + ); + + final String value; + final String label; + final String shortLabel; + final IconData icon; + final Color color; + + const OperationType({ + required this.value, + required this.label, + required this.shortLabel, + required this.icon, + required this.color, + }); + + /// Ricostruisce l'enum dal valore stringa salvato su DB in modo case-insensitive + static OperationType? fromValue(String? val) { + if (val == null || val.trim().isEmpty) return null; + final clean = val.trim().toLowerCase(); + for (final t in OperationType.values) { + if (t.value.toLowerCase() == clean || t.name.toLowerCase() == clean) { + return t; + } + } + return OperationType.altro; + } +} + +/// Sottotipi standard suggeriti per Entertainment +class EntertainmentSubtypes { + static const String calcio = 'Calcio'; + static const String cinemaTv = 'Cinema & TV'; + static const String musica = 'Musica'; + static const String altro = 'Altro'; + + static const List all = [calcio, cinemaTv, musica, altro]; +} + +/// Sottotipi standard per Energy +class EnergySubtypes { + static const String luce = 'Luce'; + static const String gas = 'Gas'; + static const String dual = 'Luce e Gas'; + + static const List all = [luce, gas, dual]; +} diff --git a/lib/features/operations/ui/operation_list_screen.dart b/lib/features/operations/ui/operation_list_screen.dart index 78f72a3..76391ec 100644 --- a/lib/features/operations/ui/operation_list_screen.dart +++ b/lib/features/operations/ui/operation_list_screen.dart @@ -7,6 +7,7 @@ import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/operations/blocs/operation_list_cubit.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; import 'package:flux/features/operations/models/operation_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; import 'package:go_router/go_router.dart'; class OperationListScreen extends StatefulWidget { @@ -406,33 +407,19 @@ class _RichOperationCard extends StatelessWidget { } } - Color _getTypeColor(String? type) { - switch (type?.toUpperCase()) { - case 'FIN': - return Colors.deepPurple; - case 'TELEPASS': - return Colors.yellow.shade700; - case 'ENERGY': - return Colors.amber.shade700; - case 'ENTERTAINMENT': - return Colors.pinkAccent; - case 'AL': - case 'MNP': - return Colors.indigo; - case 'NIP': - case 'FWA': - return Colors.cyan; - default: - return Colors.blueGrey; - } + Color _getTypeColor(OperationType? type) { + return type?.color ?? Colors.blueGrey; } - IconData? _getIconForType(String? type, String? subtype) { - if (type?.toLowerCase() == 'energy') { + IconData? _getIconForType(OperationType? type, String? subtype) { + if (type == OperationType.energy) { if (subtype?.toLowerCase() == 'luce') return Icons.bolt; if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department; } - return null; + if (type == OperationType.entertainment) { + if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer; + } + return type?.icon; } Widget _buildDetailItem(BuildContext context, OperationDetailModel detail) { @@ -441,8 +428,8 @@ class _RichOperationCard extends StatelessWidget { final icon = _getIconForType(detail.type, detail.subType); final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty) - ? '${detail.type ?? ''} (${detail.subType})' - : (detail.type ?? 'Dettaglio'); + ? '${detail.type?.shortLabel ?? ''} (${detail.subType})' + : (detail.type?.shortLabel ?? 'Dettaglio'); return Container( padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), diff --git a/lib/features/operations/ui/widgets/operation_details_section.dart b/lib/features/operations/ui/widgets/operation_details_section.dart index e46f493..7cef28e 100644 --- a/lib/features/operations/ui/widgets/operation_details_section.dart +++ b/lib/features/operations/ui/widgets/operation_details_section.dart @@ -7,23 +7,11 @@ import 'package:flux/features/master_data/providers/models/provider_model_extens import 'package:flux/features/operations/blocs/operation_details_form_cubit.dart'; import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; +import 'package:flux/features/operations/models/operation_type.dart'; class OperationDetailsSection extends StatelessWidget { const OperationDetailsSection({super.key}); - static const List _availableTypes = [ - 'AL', - 'MNP', - 'NIP', - 'UNICA', - 'FWA', - 'TELEPASS', - 'Energy', - 'Fin', - 'Entertainment', - 'Altro', - ]; - @override Widget build(BuildContext context) { final theme = Theme.of(context); @@ -117,10 +105,11 @@ class OperationDetailsSection extends StatelessWidget { final typeColor = _getTypeColor(detail.type); final providerColor = detail.provider?.displayColor ?? Colors.blueGrey; + final typeLabel = detail.type?.shortLabel ?? 'Dettaglio'; final typeText = (detail.subType != null && detail.subType!.isNotEmpty) - ? '${detail.type ?? ''} (${detail.subType})' - : (detail.type ?? 'Dettaglio'); + ? '$typeLabel (${detail.subType})' + : typeLabel; return Card( elevation: 0, @@ -292,48 +281,19 @@ class OperationDetailsSection extends StatelessWidget { ); } - Color _getTypeColor(String? type) { - switch (type?.toUpperCase()) { - case 'FIN': - return Colors.deepPurple; - case 'TELEPASS': - return Colors.yellow.shade800; - case 'ENERGY': - return Colors.amber.shade800; - case 'ENTERTAINMENT': - return Colors.pinkAccent; - case 'AL': - case 'MNP': - return Colors.indigo; - case 'NIP': - case 'FWA': - return Colors.cyan; - default: - return Colors.blueGrey; - } + Color _getTypeColor(OperationType? type) { + return type?.color ?? Colors.blueGrey; } - IconData _getIconForType(String? type, String? subtype) { - if (type?.toLowerCase() == 'energy') { + IconData _getIconForType(OperationType? type, String? subtype) { + if (type == OperationType.energy) { if (subtype?.toLowerCase() == 'luce') return Icons.bolt; if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department; } - switch (type?.toUpperCase()) { - case 'FIN': - return Icons.devices; - case 'TELEPASS': - return Icons.directions_car; - case 'ENTERTAINMENT': - return Icons.tv; - case 'AL': - case 'MNP': - return Icons.phone_android; - case 'NIP': - case 'FWA': - return Icons.wifi; - default: - return Icons.build; + if (type == OperationType.entertainment) { + if (subtype?.toLowerCase() == 'calcio') return Icons.sports_soccer; } + return type?.icon ?? Icons.build; } } @@ -372,7 +332,7 @@ class _OperationDetailFormSheetState super.dispose(); } - void _showProviderModal(BuildContext context, String operationType) { + void _showProviderModal(BuildContext context, OperationType? operationType) { final formCubit = context.read(); showModalBottomSheet( context: context, @@ -415,7 +375,7 @@ class _OperationDetailFormSheetState final filteredProviders = state.providers.where((p) { - return p.supportsOperation(operationType) && + return p.supportsOperationType(operationType) && p.isActive; }).toList(); @@ -528,7 +488,7 @@ class _OperationDetailFormSheetState >( builder: (context, formState) { final detail = formState.operationDetail; - final currentType = detail.type ?? 'AL'; + final currentType = detail.type ?? OperationType.al; return Padding( padding: EdgeInsets.only( @@ -573,11 +533,10 @@ class _OperationDetailFormSheetState spacing: 8.0, runSpacing: 8.0, children: - OperationDetailsSection._availableTypes.map(( - type, - ) { + OperationType.values.map((type) { return ChoiceChip( - label: Text(type), + avatar: Icon(type.icon, size: 16), + label: Text(type.shortLabel), selected: currentType == type, onSelected: (selected) { if (selected) { @@ -638,18 +597,18 @@ class _OperationDetailFormSheetState const SizedBox(height: 16), // 3. Scenario Energy (Dropdown Fisso) - if (currentType == 'Energy') ...[ + if (currentType == OperationType.energy) ...[ DropdownButtonFormField( initialValue: (detail.subType != null && detail.subType!.isNotEmpty) ? detail.subType - : 'Luce', + : EnergySubtypes.luce, decoration: const InputDecoration( labelText: 'Dettaglio Fornitura', ), items: - ['Luce', 'Gas'] + EnergySubtypes.all .map( (s) => DropdownMenuItem( value: s, @@ -681,7 +640,7 @@ class _OperationDetailFormSheetState ], // 4. Scenario Fin (Ricerca Modello/Prodotto) - if (currentType == 'Fin') ...[ + if (currentType == OperationType.fin) ...[ SharedModelSection( label: 'Seleziona Dispositivo/Prodotto', modelId: detail.modelId, @@ -695,16 +654,56 @@ class _OperationDetailFormSheetState const SizedBox(height: 16), ], - // 5. Scenario Entertainment o Custom (Testo libero) - if (currentType == 'Entertainment' || - currentType == 'Altro') ...[ + // 5. Scenario Entertainment (Chip veloci per Calcio/DAZN, Cinema, Musica + Campo testo) + if (currentType == OperationType.entertainment) ...[ + const Text( + 'Categoria Contenuto / Piattaforma', + style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8.0, + runSpacing: 8.0, + children: EntertainmentSubtypes.all.map((sub) { + final isSelected = detail.subType?.toLowerCase() == sub.toLowerCase(); + return ChoiceChip( + avatar: sub == EntertainmentSubtypes.calcio + ? const Icon(Icons.sports_soccer, size: 16) + : (sub == EntertainmentSubtypes.cinemaTv + ? const Icon(Icons.movie_outlined, size: 16) + : (sub == EntertainmentSubtypes.musica + ? const Icon(Icons.music_note_outlined, size: 16) + : null)), + label: Text(sub), + selected: isSelected, + onSelected: (selected) { + final newVal = selected ? sub : null; + _subtypeController.text = newVal ?? ''; + context.read().updateFields(subType: newVal); + }, + ); + }).toList(), + ), + const SizedBox(height: 12), TextFormField( controller: _subtypeController, - decoration: InputDecoration( - labelText: - currentType == 'Entertainment' - ? 'Piattaforma (es. Netflix, DAZN, Spotify...)' - : 'Specifica il servizio (es. Monopattino)', + decoration: const InputDecoration( + labelText: 'Specifica Piattaforma / Offerta (opzionale)', + hintText: 'Es. DAZN, TIMVISION Calcio, Netflix, Spotify...', + ), + onChanged: (val) { + context.read().updateFields(subType: val); + }, + ), + const SizedBox(height: 16), + ], + + // Scenario Altro (Testo libero) + if (currentType == OperationType.altro) ...[ + TextFormField( + controller: _subtypeController, + decoration: const InputDecoration( + labelText: 'Specifica il servizio (es. Monopattino)', ), onChanged: (val) { context @@ -717,10 +716,10 @@ class _OperationDetailFormSheetState // 6. Scadenza (Reattiva per tipi complessi) if ([ - 'Energy', - 'Fin', - 'Entertainment', - 'Altro', + OperationType.energy, + OperationType.fin, + OperationType.entertainment, + OperationType.altro, ].contains(currentType)) ...[ _buildDurationQuickPicks(context), const SizedBox(height: 16), diff --git a/lib/features/targets/blocs/target_form_cubit.dart b/lib/features/targets/blocs/target_form_cubit.dart new file mode 100644 index 0000000..5c3806d --- /dev/null +++ b/lib/features/targets/blocs/target_form_cubit.dart @@ -0,0 +1,280 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter_bloc/flutter_bloc.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'; +import 'package:flux/features/targets/data/targets_repository.dart'; +import 'package:flux/features/targets/models/individual_target_model.dart'; +import 'package:flux/features/targets/models/target_metrics.dart'; +import 'package:flux/features/targets/models/target_model.dart'; + +class TargetFormCubit extends Cubit { + final TargetsRepository _targetsRepository; + final StaffRepository _staffRepository; + + TargetFormCubit({ + required TargetsRepository targetsRepository, + required StaffRepository staffRepository, + }) : _targetsRepository = targetsRepository, + _staffRepository = staffRepository, + super( + TargetFormState( + target: TargetModel.empty(), + status: TargetFormStatus.initial, + ), + ); + + Future init({ + TargetModel? initialTarget, + required String companyId, + required String defaultStoreId, + }) async { + emit(state.copyWith(status: TargetFormStatus.loading)); + try { + final now = DateTime.now(); + final defaultStart = DateTime(now.year, now.month, 1); + final defaultEnd = DateTime(now.year, now.month + 1, 0, 23, 59, 59); + + final isEditing = initialTarget != null; + final target = + initialTarget ?? + TargetModel( + companyId: companyId, + storeId: defaultStoreId, + startDay: defaultStart, + endDay: defaultEnd, + metrics: const TargetMetrics(), + ); + + final storeId = target.storeId ?? defaultStoreId; + final storeStaff = await _loadStoreStaff(companyId, storeId); + + // Costruisci o allinea individualTargets per ogni membro dello staff + final List individuals = []; + for (final staff in storeStaff) { + if (staff.id == null) continue; + final existing = target.individualTargets.firstWhere( + (it) => it.staffId == staff.id, + orElse: + () => IndividualTargetModel( + companyId: companyId, + targetId: target.id ?? '', + staffId: staff.id!, + staff: staff, + metrics: const TargetMetrics(), + ), + ); + individuals.add( + existing.copyWith(staff: staff, companyId: companyId), + ); + } + + emit( + state.copyWith( + target: target, + individualTargets: individuals, + storeStaff: storeStaff, + isEditing: isEditing, + status: TargetFormStatus.ready, + ), + ); + } catch (e) { + debugPrint('Errore init TargetFormCubit: $e'); + emit( + state.copyWith( + status: TargetFormStatus.failure, + errorMessage: 'Errore nel caricamento della form: $e', + ), + ); + } + } + + Future> _loadStoreStaff( + String companyId, + String storeId, + ) async { + try { + final allStaff = await _staffRepository.getStaffMembers( + companyId, + storeId: storeId, + ); + return allStaff.where((s) => s.isActive).toList(); + } catch (_) { + return []; + } + } + + Future setStore(String storeId) async { + if (state.target.storeId == storeId) return; + emit(state.copyWith(status: TargetFormStatus.loading)); + try { + final updatedTarget = state.target.copyWith(storeId: storeId); + final storeStaff = await _loadStoreStaff( + state.target.companyId, + storeId, + ); + + final List individuals = []; + for (final staff in storeStaff) { + if (staff.id == null) continue; + individuals.add( + IndividualTargetModel( + companyId: state.target.companyId, + targetId: state.target.id ?? '', + staffId: staff.id!, + staff: staff, + metrics: const TargetMetrics(), + ), + ); + } + + emit( + state.copyWith( + target: updatedTarget, + storeStaff: storeStaff, + individualTargets: individuals, + status: TargetFormStatus.ready, + ), + ); + } catch (e) { + emit( + state.copyWith( + status: TargetFormStatus.ready, + errorMessage: 'Errore nel caricamento dello staff del negozio', + ), + ); + } + } + + void setDateRange(DateTime start, DateTime end) { + emit( + state.copyWith( + target: state.target.copyWith(startDay: start, endDay: end), + ), + ); + } + + void setDescription(String description) { + emit( + state.copyWith( + target: state.target.copyWith(description: description), + ), + ); + } + + void updateStoreMetrics(TargetMetrics metrics) { + emit( + state.copyWith( + target: state.target.copyWith(metrics: metrics), + ), + ); + } + + void updateIndividualMetrics(String staffId, TargetMetrics metrics) { + final updated = + state.individualTargets.map((it) { + if (it.staffId == staffId) { + return it.copyWith(metrics: metrics); + } + return it; + }).toList(); + + 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; + + 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) { + return it.copyWith(metrics: distributedMetrics); + }).toList(); + + emit(state.copyWith(individualTargets: updated)); + } + + void setActiveTab(int tab) { + emit(state.copyWith(activeTab: tab)); + } + + Future save() async { + if (state.target.storeId == null || state.target.storeId!.isEmpty) { + emit( + state.copyWith( + errorMessage: 'Seleziona un negozio per questo target', + ), + ); + return false; + } + + emit(state.copyWith(status: TargetFormStatus.saving)); + try { + // 1. Salva il target di negozio + final savedStoreTarget = await _targetsRepository.saveStoreTarget( + state.target, + ); + + // 2. Prepara e salva gli individualTargets collegati a savedStoreTarget.id + if (savedStoreTarget.id != null && state.individualTargets.isNotEmpty) { + final toSave = + state.individualTargets.map((it) { + return it.copyWith( + targetId: savedStoreTarget.id!, + companyId: savedStoreTarget.companyId, + ); + }).toList(); + + await _targetsRepository.saveIndividualTargets(toSave); + } + + emit( + state.copyWith( + target: savedStoreTarget, + status: TargetFormStatus.success, + ), + ); + return true; + } catch (e) { + debugPrint('Errore salvataggio target: $e'); + emit( + state.copyWith( + status: TargetFormStatus.failure, + errorMessage: 'Errore durante il salvataggio: $e', + ), + ); + return false; + } + } +} diff --git a/lib/features/targets/blocs/target_form_state.dart b/lib/features/targets/blocs/target_form_state.dart new file mode 100644 index 0000000..1d126aa --- /dev/null +++ b/lib/features/targets/blocs/target_form_state.dart @@ -0,0 +1,64 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/features/targets/models/individual_target_model.dart'; +import 'package:flux/features/targets/models/target_model.dart'; + +enum TargetFormStatus { + initial, + loading, + ready, + saving, + success, + failure, +} + +class TargetFormState extends Equatable { + final TargetModel target; + final List individualTargets; + final List storeStaff; + final TargetFormStatus status; + final String? errorMessage; + final bool isEditing; + final int activeTab; // 0: Obiettivi Negozio, 1: Quote Addetti + + const TargetFormState({ + required this.target, + this.individualTargets = const [], + this.storeStaff = const [], + this.status = TargetFormStatus.initial, + this.errorMessage, + this.isEditing = false, + this.activeTab = 0, + }); + + TargetFormState copyWith({ + TargetModel? target, + List? individualTargets, + List? storeStaff, + TargetFormStatus? status, + String? errorMessage, + bool? isEditing, + int? activeTab, + }) { + return TargetFormState( + target: target ?? this.target, + individualTargets: individualTargets ?? this.individualTargets, + storeStaff: storeStaff ?? this.storeStaff, + status: status ?? this.status, + errorMessage: errorMessage, + isEditing: isEditing ?? this.isEditing, + activeTab: activeTab ?? this.activeTab, + ); + } + + @override + List get props => [ + target, + individualTargets, + storeStaff, + status, + errorMessage, + isEditing, + activeTab, + ]; +} diff --git a/lib/features/targets/blocs/target_list_cubit.dart b/lib/features/targets/blocs/target_list_cubit.dart new file mode 100644 index 0000000..eb1acf0 --- /dev/null +++ b/lib/features/targets/blocs/target_list_cubit.dart @@ -0,0 +1,107 @@ +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/targets/data/targets_repository.dart'; +import 'package:flux/features/targets/models/target_model.dart'; +import 'package:flux/service_locator.dart'; + +part 'target_list_state.dart'; + +class TargetListCubit extends Cubit { + final TargetsRepository _repository = sl(); + final SessionCubit _sessionCubit = sl(); + StreamSubscription? _changeSub; + + TargetListCubit() : super(const TargetListState()) { + _changeSub = _repository.onTargetsChanged.listen((_) { + loadTargets(); + }); + } + + Future loadTargets({String? storeId, DateTime? month}) async { + final companyId = _sessionCubit.state.company?.id; + if (companyId == null) { + emit( + state.copyWith( + status: TargetListStatus.failure, + errorMessage: 'Nessuna azienda associata alla sessione', + ), + ); + return; + } + + emit(state.copyWith(status: TargetListStatus.loading)); + + final effectiveStoreId = storeId ?? state.selectedStoreId; + final effectiveMonth = month ?? state.selectedMonth; + + DateTime? fromDate; + DateTime? toDate; + if (effectiveMonth != null) { + fromDate = DateTime(effectiveMonth.year, effectiveMonth.month, 1); + toDate = DateTime( + effectiveMonth.year, + effectiveMonth.month + 1, + 0, + 23, + 59, + 59, + ); + } + + try { + final targets = await _repository.getStoreTargets( + companyId: companyId, + storeId: effectiveStoreId, + fromDate: fromDate, + toDate: toDate, + ); + + emit( + state.copyWith( + status: TargetListStatus.success, + targets: targets, + selectedStoreId: () => effectiveStoreId, + selectedMonth: () => effectiveMonth, + ), + ); + } catch (e) { + emit( + state.copyWith( + status: TargetListStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + + void filterByStore(String? storeId) { + loadTargets(storeId: storeId); + } + + void filterByMonth(DateTime? month) { + loadTargets(month: month); + } + + Future deleteTarget(String id) async { + try { + await _repository.deleteStoreTarget(id); + return true; + } catch (e) { + emit( + state.copyWith( + status: TargetListStatus.failure, + errorMessage: "Errore durante l'eliminazione del target: $e", + ), + ); + 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 new file mode 100644 index 0000000..73be94d --- /dev/null +++ b/lib/features/targets/blocs/target_list_state.dart @@ -0,0 +1,46 @@ +part of 'target_list_cubit.dart'; + +enum TargetListStatus { initial, loading, success, failure } + +class TargetListState extends Equatable { + final TargetListStatus status; + final List targets; + final String? selectedStoreId; + final DateTime? selectedMonth; + final String? errorMessage; + + const TargetListState({ + this.status = TargetListStatus.initial, + this.targets = const [], + this.selectedStoreId, + this.selectedMonth, + this.errorMessage, + }); + + TargetListState copyWith({ + TargetListStatus? status, + List? targets, + String? Function()? selectedStoreId, + DateTime? Function()? selectedMonth, + String? errorMessage, + }) { + return TargetListState( + status: status ?? this.status, + targets: targets ?? this.targets, + selectedStoreId: + selectedStoreId != null ? selectedStoreId() : this.selectedStoreId, + selectedMonth: + selectedMonth != null ? selectedMonth() : this.selectedMonth, + errorMessage: errorMessage, + ); + } + + @override + List get props => [ + status, + targets, + selectedStoreId, + selectedMonth, + errorMessage, + ]; +} diff --git a/lib/features/targets/data/targets_repository.dart b/lib/features/targets/data/targets_repository.dart index b4572f0..6357f23 100644 --- a/lib/features/targets/data/targets_repository.dart +++ b/lib/features/targets/data/targets_repository.dart @@ -255,6 +255,31 @@ class TargetsRepository { } } + Future> saveIndividualTargets( + List targets, + ) async { + if (targets.isEmpty) return []; + try { + final List> data = + targets.map((t) => t.toMap()).toList(); + final response = await _supabase + .from(Tables.individualTargets) + .upsert(data) + .select(''' + *, + ${Tables.staffMembers}(*) + '''); + + notifyTargetsChanged(); + return (response as List) + .map((e) => IndividualTargetModel.fromMap(e as Map)) + .toList(); + } on Exception catch (e) { + debugPrint('Errore saveIndividualTargets: $e'); + throw Exception('Errore nel salvataggio degli obiettivi individuali: $e'); + } + } + Future deleteIndividualTarget(String id) async { try { await _supabase.from(Tables.individualTargets).delete().eq('id', id); diff --git a/lib/features/targets/models/target_metrics.dart b/lib/features/targets/models/target_metrics.dart index 883dd36..f866fb2 100644 --- a/lib/features/targets/models/target_metrics.dart +++ b/lib/features/targets/models/target_metrics.dart @@ -11,6 +11,8 @@ class TargetMetrics extends Equatable { final int business2; final int contenuti1; final int contenuti2; + final int calcio1; + final int calcio2; final int fin1; final int fin2; final int upselling1; @@ -35,6 +37,8 @@ class TargetMetrics extends Equatable { this.business2 = 0, this.contenuti1 = 0, this.contenuti2 = 0, + this.calcio1 = 0, + this.calcio2 = 0, this.fin1 = 0, this.fin2 = 0, this.upselling1 = 0, @@ -61,6 +65,8 @@ class TargetMetrics extends Equatable { business2, contenuti1, contenuti2, + calcio1, + calcio2, fin1, fin2, upselling1, @@ -86,6 +92,8 @@ class TargetMetrics extends Equatable { int? business2, int? contenuti1, int? contenuti2, + int? calcio1, + int? calcio2, int? fin1, int? fin2, int? upselling1, @@ -110,6 +118,8 @@ class TargetMetrics extends Equatable { business2: business2 ?? this.business2, contenuti1: contenuti1 ?? this.contenuti1, contenuti2: contenuti2 ?? this.contenuti2, + calcio1: calcio1 ?? this.calcio1, + calcio2: calcio2 ?? this.calcio2, fin1: fin1 ?? this.fin1, fin2: fin2 ?? this.fin2, upselling1: upselling1 ?? this.upselling1, @@ -141,6 +151,8 @@ class TargetMetrics extends Equatable { business2: (map['business_2'] as num?)?.toInt() ?? 0, contenuti1: (map['contenuti_1'] as num?)?.toInt() ?? 0, contenuti2: (map['contenuti_2'] as num?)?.toInt() ?? 0, + calcio1: (map['calcio_1'] as num?)?.toInt() ?? 0, + calcio2: (map['calcio_2'] as num?)?.toInt() ?? 0, fin1: (map['fin_1'] as num?)?.toInt() ?? 0, fin2: (map['fin_2'] as num?)?.toInt() ?? 0, upselling1: (map['upselling_1'] as num?)?.toInt() ?? 0, @@ -174,6 +186,8 @@ class TargetMetrics extends Equatable { 'business_2': business2, 'contenuti_1': contenuti1, 'contenuti_2': contenuti2, + if (calcio1 > 0) 'calcio_1': calcio1, + if (calcio2 > 0) 'calcio_2': calcio2, 'fin_1': fin1, 'fin_2': fin2, 'upselling_1': upselling1, @@ -196,6 +210,7 @@ class TargetMetrics extends Equatable { nip1 + business1 + contenuti1 + + calcio1 + fin1 + upselling1 + cb1 + @@ -211,6 +226,7 @@ class TargetMetrics extends Equatable { nip2 + business2 + contenuti2 + + calcio2 + fin2 + upselling2 + cb2 + diff --git a/lib/features/targets/ui/target_form_screen.dart b/lib/features/targets/ui/target_form_screen.dart new file mode 100644 index 0000000..d30fb1c --- /dev/null +++ b/lib/features/targets/ui/target_form_screen.dart @@ -0,0 +1,1126 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/master_data/store/bloc/store_cubit.dart'; +import 'package:flux/features/targets/blocs/target_form_cubit.dart'; +import 'package:flux/features/targets/blocs/target_form_state.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +class TargetFormScreen extends StatefulWidget { + const TargetFormScreen({super.key}); + + @override + State createState() => _TargetFormScreenState(); +} + +class _TargetFormScreenState extends State + with SingleTickerProviderStateMixin { + late TabController _tabController; + final TextEditingController _descController = TextEditingController(); + + @override + void initState() { + super.initState(); + _tabController = TabController(length: 2, vsync: this); + } + + @override + void dispose() { + _tabController.dispose(); + _descController.dispose(); + super.dispose(); + } + + String _formatMonthYear(DateTime date) { + try { + final formatter = DateFormat('MMMM yyyy', 'it_IT'); + final formatted = formatter.format(date); + return formatted[0].toUpperCase() + formatted.substring(1); + } catch (_) { + final formatter = DateFormat('MM/yyyy'); + return formatter.format(date); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDesktop = MediaQuery.sizeOf(context).width >= 900; + + return BlocConsumer( + listener: (context, state) { + if (state.status == TargetFormStatus.success) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Obiettivo salvato con successo!'), + backgroundColor: Colors.green, + ), + ); + context.pop(); + } else if (state.status == TargetFormStatus.failure || + state.errorMessage != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text( + state.errorMessage ?? 'Errore durante il salvataggio', + ), + backgroundColor: Colors.red, + ), + ); + } + }, + builder: (context, state) { + if (state.status == TargetFormStatus.loading) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + final title = + state.isEditing ? 'Modifica Target Mensile' : 'Nuovo Target Mensile'; + + return Scaffold( + appBar: AppBar( + title: Text(title), + bottom: TabBar( + controller: _tabController, + tabs: [ + const Tab( + icon: Icon(Icons.storefront_outlined), + text: 'Obiettivi Negozio', + ), + Tab( + icon: const Icon(Icons.people_outline), + text: 'Quote Addetti (${state.storeStaff.length})', + ), + ], + ), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 16.0), + child: + state.status == TargetFormStatus.saving + ? const Center( + child: SizedBox( + width: 24, + height: 24, + child: CircularProgressIndicator(strokeWidth: 2), + ), + ) + : FilledButton.icon( + onPressed: () { + context.read().save(); + }, + icon: const Icon(Icons.save_outlined, size: 20), + label: const Text('Salva'), + ), + ), + ], + ), + body: TabBarView( + controller: _tabController, + children: [ + _buildStoreTargetTab(context, theme, state, isDesktop), + _buildStaffQuotaTab(context, theme, state, isDesktop), + ], + ), + ); + }, + ); + } + + // ========================================== + // TAB 1: OBIETTIVI NEGOZIO + // ========================================== + + Widget _buildStoreTargetTab( + BuildContext context, + ThemeData theme, + TargetFormState state, + bool isDesktop, + ) { + final stores = context.watch().state.stores; + final cubit = context.read(); + final metrics = state.target.metrics; + + if (_descController.text != (state.target.description ?? '')) { + _descController.text = state.target.description ?? ''; + } + + return SingleChildScrollView( + padding: EdgeInsets.all(isDesktop ? 24.0 : 16.0), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 1000), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Card Dati Generali (Negozio, Mese, Note) + Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide( + color: theme.dividerColor.withValues(alpha: 0.5), + ), + ), + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Periodo & Punto Vendita', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 16), + Wrap( + spacing: 16, + runSpacing: 16, + children: [ + // Selettore Mese + InkWell( + onTap: () => _pickMonth(context, state.target), + borderRadius: BorderRadius.circular(12), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 16, + vertical: 12, + ), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues( + alpha: 0.06, + ), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: theme.colorScheme.primary.withValues( + alpha: 0.3, + ), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.calendar_month, + color: theme.colorScheme.primary, + ), + const SizedBox(width: 10), + Column( + crossAxisAlignment: + CrossAxisAlignment.start, + children: [ + Text( + 'Mese di competenza', + style: TextStyle( + fontSize: 11, + color: + theme + .colorScheme + .onSurfaceVariant, + ), + ), + Text( + _formatMonthYear(state.target.startDay), + style: const TextStyle( + fontSize: 15, + fontWeight: FontWeight.bold, + ), + ), + ], + ), + const SizedBox(width: 8), + const Icon(Icons.arrow_drop_down, size: 20), + ], + ), + ), + ), + + // Selettore Negozio + if (stores.isNotEmpty) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 4, + ), + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: theme.dividerColor.withValues( + alpha: 0.5, + ), + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: + (state.target.storeId?.isNotEmpty == true) + ? state.target.storeId + : (stores.isNotEmpty + ? stores.first.id + : null), + hint: const Text('Seleziona Negozio'), + items: + stores.map((s) { + return DropdownMenuItem( + value: s.id, + child: Text( + s.name, + style: const TextStyle( + fontWeight: FontWeight.w600, + ), + ), + ); + }).toList(), + onChanged: (val) { + if (val != null) cubit.setStore(val); + }, + ), + ), + ), + ], + ), + const SizedBox(height: 16), + TextFormField( + controller: _descController, + decoration: const InputDecoration( + labelText: 'Note o Descrizione target (opzionale)', + hintText: 'Es. Focus su Calcio e Fibra per promozioni', + border: OutlineInputBorder(), + ), + onChanged: (val) => cubit.setDescription(val), + ), + ], + ), + ), + ), + const SizedBox(height: 24), + + // Header Quote con Riepilogo Totali + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Metriche & Soglie Negozio', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Definisci la Soglia 1 (base) e la Soglia 2 (sfidante)', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + Row( + children: [ + Chip( + label: Text('Tot. S1: ${metrics.totalLevel1} pz'), + backgroundColor: Colors.blue.withValues(alpha: 0.1), + side: BorderSide.none, + ), + const SizedBox(width: 8), + Chip( + label: Text('Tot. S2: ${metrics.totalLevel2} pz'), + backgroundColor: Colors.deepPurple.withValues( + alpha: 0.1, + ), + side: BorderSide.none, + ), + ], + ), + ], + ), + const SizedBox(height: 16), + + // Lista o Griglia delle Categorie + Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide( + color: theme.dividerColor.withValues(alpha: 0.5), + ), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Column( + children: [ + _buildMetricInputRow( + theme: theme, + icon: Icons.phone_forwarded_outlined, + color: Colors.indigo, + label: 'Portabilità (MNP)', + val1: metrics.mnp1, + val2: metrics.mnp2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(mnp1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(mnp2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.sim_card_outlined, + color: Colors.blue, + label: 'Attivazione Linea (AL)', + val1: metrics.al1, + val2: metrics.al2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(al1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(al2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.merge_type_outlined, + color: Colors.orange, + label: 'TIM Unica / Convergenza', + val1: metrics.unica1, + val2: metrics.unica2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(unica1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(unica2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.home_repair_service_outlined, + color: Colors.cyan, + label: 'Nuovo Impianto (NIP / Fibra)', + val1: metrics.nip1, + val2: metrics.nip2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(nip1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(nip2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.live_tv_outlined, + color: Colors.redAccent, + label: 'Contenuti & Intrattenimento (Totale)', + val1: metrics.contenuti1, + val2: metrics.contenuti2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(contenuti1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(contenuti2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.sports_soccer, + color: Colors.green, + label: 'Di cui Calcio & DAZN', + val1: metrics.calcio1, + val2: metrics.calcio2, + isSubtype: true, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(calcio1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(calcio2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.directions_car_outlined, + color: Colors.amber.shade800, + label: 'Telepass', + val1: metrics.telepass1, + val2: metrics.telepass2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(telepass1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(telepass2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.credit_card_outlined, + color: Colors.purple, + label: 'Finanziamenti (Fin)', + val1: metrics.fin1, + val2: metrics.fin2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(fin1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(fin2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.people_alt_outlined, + color: Colors.deepOrange, + label: 'Customer Base (CB)', + val1: metrics.cb1, + val2: metrics.cb2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(cb1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(cb2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.trending_up_outlined, + color: Colors.deepPurple, + label: 'Upselling / Cambio Offerta', + val1: metrics.upselling1, + val2: metrics.upselling2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(upselling1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(upselling2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.business_outlined, + color: Colors.blueGrey, + label: 'Servizi Business', + val1: metrics.business1, + val2: metrics.business2, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(business1: v), + ), + onChanged2: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(business2: v), + ), + ), + const Divider(), + _buildMetricInputRow( + theme: theme, + icon: Icons.bolt_outlined, + color: Colors.blue, + label: 'Energia TIM', + val1: metrics.energiaTim, + val2: 0, + showLevel2: false, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(energiaTim: 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, + onChanged1: + (v) => cubit.updateStoreMetrics( + metrics.copyWith(energiaAltri: v), + ), + onChanged2: (_) {}, + ), + ], + ), + ), + ), + const SizedBox(height: 32), + ], + ), + ), + ), + ); + } + + // ========================================== + // TAB 2: QUOTE ADDETTI + // ========================================== + + Widget _buildStaffQuotaTab( + BuildContext context, + ThemeData theme, + TargetFormState state, + bool isDesktop, + ) { + final cubit = context.read(); + + if (state.storeStaff.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: 16), + const Text( + 'Nessun addetto assegnato a questo negozio.', + style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Text( + 'Assegna lo staff a questo negozio nell\'anagrafica per configurare le quote individuali.', + style: TextStyle(color: theme.colorScheme.onSurfaceVariant), + textAlign: TextAlign.center, + ), + ], + ), + ), + ); + } + + return SingleChildScrollView( + padding: EdgeInsets.all(isDesktop ? 24.0 : 16.0), + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 1000), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Barra Azioni Rapide + Card( + elevation: 0, + color: theme.colorScheme.primary.withValues(alpha: 0.05), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide( + color: theme.colorScheme.primary.withValues(alpha: 0.2), + ), + ), + child: Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + children: [ + Icon(Icons.auto_awesome, color: theme.colorScheme.primary), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + 'Ripartizione Automatica', + style: TextStyle(fontWeight: FontWeight.bold), + ), + Text( + 'Suddividi le quote del negozio in parti uguali tra i ${state.storeStaff.length} addetti.', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + OutlinedButton.icon( + icon: const Icon(Icons.call_split, size: 18), + label: const Text('Distribuisci'), + onPressed: () { + cubit.distributeMetricsEqually(); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Quote distribuite in parti uguali!'), + duration: Duration(seconds: 2), + ), + ); + }, + ), + ], + ), + ), + ), + const SizedBox(height: 20), + + // Lista Addetti (ExpansionTiles o Card) + ...state.individualTargets.map((it) { + final staff = it.staff; + final staffName = staff?.name ?? 'Addetto'; + final totalL1 = it.metrics.totalLevel1; + final totalL2 = it.metrics.totalLevel2; + + return Card( + elevation: 0, + margin: const EdgeInsets.only(bottom: 12), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide( + color: theme.dividerColor.withValues(alpha: 0.5), + ), + ), + clipBehavior: Clip.antiAlias, + child: ExpansionTile( + leading: CircleAvatar( + backgroundColor: theme.colorScheme.primary.withValues(alpha: 0.1), + child: Text( + staffName.isNotEmpty ? staffName[0].toUpperCase() : 'A', + style: TextStyle( + color: theme.colorScheme.primary, + fontWeight: FontWeight.bold, + ), + ), + ), + title: Text( + staffName, + style: const TextStyle(fontWeight: FontWeight.bold), + ), + subtitle: Text( + 'Soglia 1: $totalL1 pz • Soglia 2: $totalL2 pz', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + children: [ + Padding( + padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 8.0), + child: Column( + children: [ + _buildStaffMetricRow( + theme: theme, + label: 'MNP', + val1: it.metrics.mnp1, + val2: it.metrics.mnp2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(mnp1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(mnp2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'AL', + val1: it.metrics.al1, + val2: it.metrics.al2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(al1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(al2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'UNICA', + val1: it.metrics.unica1, + val2: it.metrics.unica2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(unica1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(unica2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'NIP', + val1: it.metrics.nip1, + val2: it.metrics.nip2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(nip1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(nip2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Contenuti (Totale)', + val1: it.metrics.contenuti1, + val2: it.metrics.contenuti2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(contenuti1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(contenuti2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: ' ↳ di cui Calcio / DAZN', + val1: it.metrics.calcio1, + val2: it.metrics.calcio2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(calcio1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(calcio2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Telepass', + val1: it.metrics.telepass1, + val2: it.metrics.telepass2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(telepass1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(telepass2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Fin', + val1: it.metrics.fin1, + val2: it.metrics.fin2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(fin1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(fin2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'CB', + val1: it.metrics.cb1, + val2: it.metrics.cb2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(cb1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(cb2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Upselling', + val1: it.metrics.upselling1, + val2: it.metrics.upselling2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(upselling1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(upselling2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Business', + val1: it.metrics.business1, + val2: it.metrics.business2, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(business1: v), + ), + onChanged2: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(business2: v), + ), + ), + _buildStaffMetricRow( + theme: theme, + label: 'Energia TIM', + val1: it.metrics.energiaTim, + val2: 0, + showLevel2: false, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(energiaTim: v), + ), + onChanged2: (_) {}, + ), + _buildStaffMetricRow( + theme: theme, + label: 'Energia Altri', + val1: it.metrics.energiaAltri, + val2: 0, + showLevel2: false, + onChanged1: (v) => cubit.updateIndividualMetrics( + it.staffId, + it.metrics.copyWith(energiaAltri: v), + ), + onChanged2: (_) {}, + ), + const SizedBox(height: 8), + ], + ), + ), + ], + ), + ); + }), + const SizedBox(height: 32), + ], + ), + ), + ), + ); + } + + // ========================================== + // HELPERS PER GLI INPUT DELLE METRICHE + // ========================================== + + Widget _buildMetricInputRow({ + required ThemeData theme, + required IconData icon, + required Color color, + required String label, + required int val1, + required int val2, + required ValueChanged onChanged1, + required ValueChanged onChanged2, + bool isSubtype = false, + bool showLevel2 = true, + }) { + return Padding( + padding: EdgeInsets.symmetric( + vertical: 8.0, + horizontal: isSubtype ? 16.0 : 0.0, + ), + child: Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon(icon, color: color, size: 20), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + label, + style: TextStyle( + fontWeight: isSubtype ? FontWeight.normal : FontWeight.w600, + fontSize: 14, + ), + ), + ), + const SizedBox(width: 12), + + // Input Soglia 1 + SizedBox( + width: 80, + child: _NumberInputField( + label: 'S1 (Base)', + value: val1, + onChanged: onChanged1, + ), + ), + const SizedBox(width: 8), + + // Input Soglia 2 + if (showLevel2) + SizedBox( + width: 80, + child: _NumberInputField( + label: 'S2 (Sfida)', + value: val2, + onChanged: onChanged2, + ), + ) + else + const SizedBox(width: 80), + ], + ), + ); + } + + Widget _buildStaffMetricRow({ + required ThemeData theme, + required String label, + required int val1, + required int val2, + required ValueChanged onChanged1, + required ValueChanged onChanged2, + bool showLevel2 = true, + }) { + return Padding( + padding: const EdgeInsets.symmetric(vertical: 4.0), + child: Row( + children: [ + Expanded( + child: Text( + label, + style: const TextStyle(fontSize: 13), + ), + ), + SizedBox( + width: 70, + child: _NumberInputField( + label: 'S1', + value: val1, + onChanged: onChanged1, + isDense: true, + ), + ), + const SizedBox(width: 8), + if (showLevel2) + SizedBox( + width: 70, + child: _NumberInputField( + label: 'S2', + value: val2, + onChanged: onChanged2, + isDense: true, + ), + ) + else + const SizedBox(width: 70), + ], + ), + ); + } + + Future _pickMonth(BuildContext context, target) async { + final cubit = context.read(); + final current = target.startDay as DateTime; + + final picked = await showDatePicker( + context: context, + initialDate: current, + firstDate: DateTime(2020), + lastDate: DateTime(2035), + helpText: 'SELEZIONA IL MESE DEL TARGET', + ); + + if (picked != null) { + final start = DateTime(picked.year, picked.month, 1); + final end = DateTime(picked.year, picked.month + 1, 0, 23, 59, 59); + cubit.setDateRange(start, end); + } + } +} + +class _NumberInputField extends StatefulWidget { + final String label; + final int value; + final ValueChanged onChanged; + final bool isDense; + + const _NumberInputField({ + required this.label, + required this.value, + required this.onChanged, + this.isDense = false, + }); + + @override + State<_NumberInputField> createState() => _NumberInputFieldState(); +} + +class _NumberInputFieldState extends State<_NumberInputField> { + late TextEditingController _controller; + + @override + void initState() { + super.initState(); + _controller = TextEditingController( + text: widget.value > 0 ? widget.value.toString() : '', + ); + } + + @override + void didUpdateWidget(covariant _NumberInputField oldWidget) { + super.didUpdateWidget(oldWidget); + if (oldWidget.value != widget.value) { + final textVal = widget.value > 0 ? widget.value.toString() : ''; + if (_controller.text != textVal) { + _controller.text = textVal; + } + } + } + + @override + void dispose() { + _controller.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) { + return TextFormField( + controller: _controller, + keyboardType: TextInputType.number, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + textAlign: TextAlign.center, + style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 13), + decoration: InputDecoration( + labelText: widget.label, + labelStyle: const TextStyle(fontSize: 10), + isDense: widget.isDense, + contentPadding: const EdgeInsets.symmetric(horizontal: 4, vertical: 8), + border: OutlineInputBorder(borderRadius: BorderRadius.circular(8)), + ), + onChanged: (val) { + final parsed = int.tryParse(val) ?? 0; + widget.onChanged(parsed); + }, + ); + } +} diff --git a/lib/features/targets/ui/target_list_screen.dart b/lib/features/targets/ui/target_list_screen.dart new file mode 100644 index 0000000..2f701a1 --- /dev/null +++ b/lib/features/targets/ui/target_list_screen.dart @@ -0,0 +1,573 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/routes/routes.dart'; +import 'package:flux/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:go_router/go_router.dart'; +import 'package:intl/intl.dart'; + +class TargetListScreen extends StatefulWidget { + const TargetListScreen({super.key}); + + @override + State createState() => _TargetListScreenState(); +} + +class _TargetListScreenState extends State { + @override + void initState() { + super.initState(); + WidgetsBinding.instance.addPostFrameCallback((_) { + final currentStoreId = + context.read().state.currentStore?.id; + context.read().loadTargets(storeId: currentStoreId); + }); + } + + String _formatMonthYear(DateTime date) { + try { + final formatter = DateFormat('MMMM yyyy', 'it_IT'); + final formatted = formatter.format(date); + return formatted[0].toUpperCase() + formatted.substring(1); + } catch (_) { + final formatter = DateFormat('MM/yyyy'); + return formatter.format(date); + } + } + + String _formatDateRange(DateTime start, DateTime end) { + final formatter = DateFormat('dd/MM/yyyy'); + return '${formatter.format(start)} - ${formatter.format(end)}'; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final isDesktop = MediaQuery.sizeOf(context).width >= 900; + + return Scaffold( + backgroundColor: theme.colorScheme.surface, + body: SafeArea( + child: Column( + children: [ + // ========================================== + // HEADER + // ========================================== + Container( + padding: EdgeInsets.symmetric( + horizontal: isDesktop ? 24.0 : 16.0, + vertical: isDesktop ? 20.0 : 12.0, + ), + color: theme.colorScheme.surface, + child: _buildHeader(context, theme, isDesktop), + ), + const Divider(height: 1), + + // ========================================== + // LISTA DEI TARGET + // ========================================== + Expanded( + child: BlocBuilder( + builder: (context, state) { + if (state.status == TargetListStatus.loading && + state.targets.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + + if (state.status == TargetListStatus.failure && + state.targets.isEmpty) { + return Center( + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + const Icon( + Icons.error_outline, + size: 48, + color: Colors.red, + ), + const SizedBox(height: 12), + Text( + state.errorMessage ?? + 'Errore nel caricamento dei target', + style: const TextStyle(fontSize: 16), + textAlign: TextAlign.center, + ), + const SizedBox(height: 16), + ElevatedButton.icon( + onPressed: () { + context.read().loadTargets(); + }, + icon: const Icon(Icons.refresh), + label: const Text('Riprova'), + ), + ], + ), + ); + } + + if (state.targets.isEmpty) { + return Center( + child: Padding( + padding: const EdgeInsets.all(32.0), + child: Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Container( + padding: const EdgeInsets.all(24), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues( + alpha: 0.1, + ), + shape: BoxShape.circle, + ), + child: Icon( + Icons.track_changes_outlined, + size: 64, + color: theme.colorScheme.primary, + ), + ), + const SizedBox(height: 20), + Text( + 'Nessun target configurato', + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Text( + 'Definisci gli obiettivi mensili del negozio e assegnali agli addetti.', + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant, + fontSize: 14, + ), + textAlign: TextAlign.center, + ), + const SizedBox(height: 24), + ElevatedButton.icon( + icon: const Icon(Icons.add), + label: const Text('Crea Primo Target'), + style: ElevatedButton.styleFrom( + padding: const EdgeInsets.symmetric( + horizontal: 24, + vertical: 12, + ), + ), + onPressed: () => _goToNewTarget(context), + ), + ], + ), + ), + ); + } + + return RefreshIndicator( + onRefresh: () async { + await context.read().loadTargets(); + }, + child: ListView.separated( + padding: const EdgeInsets.all(24.0), + itemCount: state.targets.length, + separatorBuilder: (_, _) => const SizedBox(height: 16), + itemBuilder: (context, index) { + final target = state.targets[index]; + return _buildTargetCard(context, target, theme); + }, + ), + ); + }, + ), + ), + ], + ), + ), + ); + } + + Widget _buildHeader(BuildContext context, ThemeData theme, bool isDesktop) { + return BlocBuilder( + builder: (context, state) { + final stores = context.watch().state.stores; + + final titleWidget = Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Row( + children: [ + Icon( + Icons.track_changes_outlined, + color: theme.colorScheme.primary, + size: isDesktop ? 28 : 24, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Obiettivi & Target', + style: (isDesktop + ? theme.textTheme.headlineMedium + : theme.textTheme.titleLarge) + ?.copyWith( + fontWeight: FontWeight.bold, + ), + overflow: TextOverflow.ellipsis, + ), + ), + ], + ), + const SizedBox(height: 4), + Text( + 'Gestione e avanzamento delle quote mensili di vendita', + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant, + fontSize: isDesktop ? 13 : 12, + ), + ), + ], + ); + + final storeFilterWidget = stores.length > 1 + ? Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 2), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues(alpha: 0.4), + borderRadius: BorderRadius.circular(10), + border: Border.all( + color: theme.dividerColor.withValues(alpha: 0.4), + ), + ), + child: DropdownButtonHideUnderline( + child: DropdownButton( + value: state.selectedStoreId, + isDense: true, + isExpanded: !isDesktop, + hint: const Text('Tutti i negozi'), + items: [ + const DropdownMenuItem( + value: null, + child: Text('Tutti i negozi'), + ), + ...stores.map((s) { + return DropdownMenuItem( + value: s.id, + child: Text( + s.name, + overflow: TextOverflow.ellipsis, + ), + ); + }), + ], + onChanged: (val) { + context.read().filterByStore(val); + }, + ), + ), + ) + : null; + + final newTargetButton = ElevatedButton.icon( + icon: const Icon(Icons.add, size: 18), + label: const Text('Nuovo Target'), + style: ElevatedButton.styleFrom( + backgroundColor: theme.colorScheme.primary, + foregroundColor: theme.colorScheme.onPrimary, + padding: EdgeInsets.symmetric( + horizontal: isDesktop ? 18 : 14, + vertical: isDesktop ? 12 : 10, + ), + ), + onPressed: () => _goToNewTarget(context), + ); + + if (isDesktop) { + return Row( + crossAxisAlignment: CrossAxisAlignment.center, + children: [ + Expanded(child: titleWidget), + const SizedBox(width: 16), + if (storeFilterWidget != null) ...[ + storeFilterWidget, + const SizedBox(width: 12), + ], + newTargetButton, + ], + ); + } + + // Su schermi mobili / stretti disponiamo su due livelli + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + titleWidget, + const SizedBox(height: 12), + Row( + children: [ + if (storeFilterWidget != null) ...[ + Expanded(child: storeFilterWidget), + const SizedBox(width: 10), + ] else ...[ + const Spacer(), + ], + newTargetButton, + ], + ), + ], + ); + }, + ); + } + + Widget _buildTargetCard( + BuildContext context, + TargetModel target, + ThemeData theme, + ) { + final title = _formatMonthYear(target.startDay); + final range = _formatDateRange(target.startDay, target.endDay); + final storeName = target.store?.name ?? 'Negozio'; + + final totalL1 = target.metrics.totalLevel1; + final totalL2 = target.metrics.totalLevel2; + final staffCount = target.individualTargets.length; + + return Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: theme.dividerColor.withValues(alpha: 0.6)), + ), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: () => _goToTargetDetail(context, target), + borderRadius: BorderRadius.circular(16), + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Riga 1: Titolo Mese + Badge Negozio + Azioni (Modifica / Elimina) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + ), + child: Icon( + Icons.calendar_month_outlined, + color: theme.colorScheme.primary, + size: 26, + ), + ), + const SizedBox(width: 16), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Wrap( + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 4, + children: [ + Text( + title, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + fontSize: 18, + ), + ), + 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, + ), + ], + ), + const SizedBox(height: 4), + Text( + range, + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + + // Menu Azioni (Modifica / Elimina) + IconButton( + icon: const Icon(Icons.edit_outlined), + tooltip: 'Modifica quote target', + onPressed: () => _goToEditTarget(context, target), + ), + IconButton( + icon: const Icon(Icons.delete_outline, color: Colors.red), + tooltip: 'Elimina target', + onPressed: () => _confirmDelete(context, target), + ), + ], + ), + const SizedBox(height: 16), + 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) + _buildMetricBadge( + label: 'Soglia 2 (Sfidante)', + value: '$totalL2 pz', + 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 + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + onPressed: () => _goToTargetDetail(context, target), + icon: const Icon(Icons.analytics_outlined, size: 18), + label: const Text('Vedi Avanzamento & Statistiche'), + ), + ), + ], + ), + ), + ), + ); + } + + Widget _buildMetricBadge({ + required String label, + required String value, + required Color color, + required IconData icon, + }) { + return Container( + padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8), + decoration: BoxDecoration( + color: color.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + border: Border.all(color: color.withValues(alpha: 0.25)), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(icon, size: 16, color: color), + const SizedBox(width: 8), + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + label, + style: TextStyle( + fontSize: 10, + color: Colors.grey.shade700, + fontWeight: FontWeight.w500, + ), + ), + Text( + value, + style: TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: color, + ), + ), + ], + ), + ], + ), + ); + } + + void _goToNewTarget(BuildContext context) { + context.pushNamed(Routes.targetForm); + } + + void _goToEditTarget(BuildContext context, TargetModel target) { + context.pushNamed(Routes.targetForm, extra: target); + } + + void _goToTargetDetail(BuildContext context, TargetModel target) { + context.pushNamed(Routes.targetDetail, extra: target); + } + + Future _confirmDelete(BuildContext context, TargetModel target) async { + final title = _formatMonthYear(target.startDay); + final confirmed = await showDialog( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.warning_amber_rounded, color: Colors.red), + SizedBox(width: 8), + Text('Elimina Target'), + ], + ), + content: Text( + 'Sei sicuro di voler eliminare il target di "$title"?\nVerranno eliminati anche tutti i target individuali assegnati agli addetti per questo mese.', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogContext, false), + child: const Text('Annulla'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red, + foregroundColor: Colors.white, + ), + onPressed: () => Navigator.pop(dialogContext, true), + child: const Text('Elimina'), + ), + ], + ); + }, + ); + + if (confirmed == true && context.mounted) { + final success = await context.read().deleteTarget( + target.id!, + ); + if (success && context.mounted) { + ScaffoldMessenger.of( + context, + ).showSnackBar(const SnackBar(content: Text('Target eliminato.'))); + } + } + } +} diff --git a/lib/service_locator.dart b/lib/service_locator.dart index 07c90a4..a93331d 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/blocs/target_list_cubit.dart'; import 'package:flux/features/tracking/blocs/tracking_cubit.dart'; import 'package:flux/features/tracking/data/tracking_repository.dart'; import 'package:get_it/get_it.dart'; @@ -90,4 +91,5 @@ Future init() async { sl.registerFactory(() => TicketListCubit()); sl.registerFactory(() => TrackingCubit()); sl.registerFactory(() => NotesCubit()); + sl.registerFactory(() => TargetListCubit()); }