diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index d381cd6..8e55868 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -42,6 +42,7 @@ import 'package:flux/features/notes/ui/notes_list_screen.dart'; import 'package:flux/features/onboarding/blocs/onboarding_cubit.dart'; import 'package:flux/features/onboarding/ui/onboarding_screen.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; +import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart'; import 'package:flux/features/operations/blocs/operation_form_cubit.dart'; import 'package:flux/features/operations/models/operation_model.dart'; import 'package:flux/features/operations/ui/operation_form_screen.dart'; @@ -505,10 +506,15 @@ class AppRouter { existingOperation: record?.operation, ), ), + BlocProvider( + create: (context) => OperationDetailsListCubit( + details: record?.operation?.details ?? [], + ), + ), ], child: OperationFormScreen( operationId: realOperationId, - existingOperation: record?.operation, + operation: record?.operation, ), ); }, diff --git a/lib/features/operations/blocs/operation_details_form_cubit.dart b/lib/features/operations/blocs/operation_details_form_cubit.dart index 7799550..7960cd9 100644 --- a/lib/features/operations/blocs/operation_details_form_cubit.dart +++ b/lib/features/operations/blocs/operation_details_form_cubit.dart @@ -1,4 +1,124 @@ import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.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/master_data/providers/models/provider_model_extensions.dart'; import 'package:flux/features/operations/models/operation_detail_model.dart'; part 'operation_details_form_state.dart'; + +class OperationDetailsFormCubit extends Cubit { + OperationDetailsFormCubit({ + OperationDetailModel? initialDetail, + int? editingIndex, + List? allProviders, + String? defaultProviderId, + }) : super( + OperationDetailsFormState( + operationDetail: initialDetail ?? const OperationDetailModel(), + editingIndex: editingIndex, + ), + ) { + if (initialDetail == null && + allProviders != null && + allProviders.isNotEmpty) { + const defaultType = 'AL'; + setTypeWithSmartDefaults( + newType: defaultType, + allProviders: allProviders, + defaultProviderId: defaultProviderId, + ); + } + } + + void updateFields({ + String? type, + String? subType, + ProviderModel? provider, + ModelModel? model, + String? modelId, + String? description, + DateTime? expirationDate, + }) { + final current = state.operationDetail; + final updated = current.copyWith( + type: type ?? current.type, + subType: subType ?? current.subType, + provider: + provider != null + ? () => provider + : (current.provider != null ? () => current.provider : null), + model: + model != null + ? () => model + : (current.model != null ? () => current.model : null), + modelId: modelId ?? current.modelId, + description: description ?? current.description, + expirationDate: expirationDate ?? current.expirationDate, + ); + + emit( + state.copyWith( + operationDetail: updated, + status: OperationDetailsFormStatus.ready, + ), + ); + } + + void setProvider(ProviderModel provider) { + final updated = state.operationDetail.copyWith( + provider: () => provider, + providerId: provider.id, + ); + emit( + state.copyWith( + operationDetail: updated, + status: OperationDetailsFormStatus.ready, + ), + ); + } + + void setTypeWithSmartDefaults({ + required String newType, + required List allProviders, + String? defaultProviderId, + }) { + ProviderModel? selectedProvider; + if (defaultProviderId != null) { + final foundDefault = allProviders.firstWhere( + (p) => + p.id == defaultProviderId && + p.supportsOperation(newType) && + p.isActive, + orElse: () => const ProviderModel(companyId: '', name: ''), + ); + if (foundDefault.id != null) { + selectedProvider = foundDefault; + } + } + if (selectedProvider == null) { + final foundCompatible = allProviders.firstWhere( + (p) => p.supportsOperation(newType) && p.isActive, + orElse: () => const ProviderModel(companyId: '', name: ''), + ); + if (foundCompatible.id != null) { + selectedProvider = foundCompatible; + } + } + + final current = state.operationDetail; + final updated = current.copyWith( + type: newType, + subType: newType == 'Energy' ? 'Luce' : null, + provider: selectedProvider != null ? () => selectedProvider : null, + providerId: selectedProvider?.id, + ); + + emit( + state.copyWith( + operationDetail: updated, + status: OperationDetailsFormStatus.ready, + ), + ); + } +} diff --git a/lib/features/operations/blocs/operation_details_form_state.dart b/lib/features/operations/blocs/operation_details_form_state.dart index 6eb7109..aa76792 100644 --- a/lib/features/operations/blocs/operation_details_form_state.dart +++ b/lib/features/operations/blocs/operation_details_form_state.dart @@ -6,25 +6,36 @@ class OperationDetailsFormState extends Equatable { final OperationDetailModel operationDetail; final String? errorMessage; final OperationDetailsFormStatus status; + final int? editingIndex; const OperationDetailsFormState({ required this.operationDetail, this.errorMessage, this.status = OperationDetailsFormStatus.ready, + this.editingIndex, }); + bool get isEditing => editingIndex != null; + OperationDetailsFormState copyWith({ OperationDetailModel? operationDetail, String? errorMessage, OperationDetailsFormStatus? status, + int? Function()? editingIndex, }) { return OperationDetailsFormState( operationDetail: operationDetail ?? this.operationDetail, errorMessage: errorMessage ?? this.errorMessage, status: status ?? this.status, + editingIndex: editingIndex != null ? editingIndex() : this.editingIndex, ); } @override - List get props => [operationDetail, errorMessage, status]; + List get props => [ + operationDetail, + errorMessage, + status, + editingIndex, + ]; } diff --git a/lib/features/operations/blocs/operation_form_cubit.dart b/lib/features/operations/blocs/operation_form_cubit.dart index 55431cc..da48316 100644 --- a/lib/features/operations/blocs/operation_form_cubit.dart +++ b/lib/features/operations/blocs/operation_form_cubit.dart @@ -40,6 +40,8 @@ class OperationFormCubit extends Cubit { state.copyWith( operation: existingOperation, status: OperationFormStatus.ready, + isNew: false, + hasUnsavedChanges: false, ), ); } else if (operationId != null) { @@ -50,6 +52,8 @@ class OperationFormCubit extends Cubit { state.copyWith( operation: operation, status: OperationFormStatus.ready, + isNew: false, + hasUnsavedChanges: false, ), ); } on Exception catch (e) { @@ -63,14 +67,20 @@ class OperationFormCubit extends Cubit { } else { // NUOVA PRATICA final currentStore = _sessionCubit.state.currentStore; + final initialStaffDisplayName = state.operation.staffDisplayName; final newOperation = await _repository.createNewOperation( currentStore: currentStore!, createdById: state.operation.staffId!, ); emit( state.copyWith( - operation: newOperation, + operation: newOperation.copyWith( + staffDisplayName: + newOperation.staffDisplayName ?? initialStaffDisplayName, + ), status: OperationFormStatus.ready, + isNew: true, + hasUnsavedChanges: true, ), ); } @@ -111,7 +121,9 @@ class OperationFormCubit extends Cubit { emit( state.copyWith( status: OperationFormStatus.success, - operation: operationToSave, // Aggiorniamo con l'ID restituito dal DB + operation: operationToSave, + isNew: false, + hasUnsavedChanges: false, ), ); } catch (e) { @@ -124,6 +136,29 @@ class OperationFormCubit extends Cubit { } } + // --- ANNULLA E ELIMINA SE NUOVA --- + Future discardAndExit() async { + emit(state.copyWith(status: OperationFormStatus.saving)); + try { + if (state.isNew && state.operation.id != null) { + await _repository.deleteOperation(state.operation.id!); + } + emit( + state.copyWith( + status: OperationFormStatus.discarded, + hasUnsavedChanges: false, + ), + ); + } catch (e) { + emit( + state.copyWith( + status: OperationFormStatus.failure, + errorMessage: "Errore durante l'eliminazione dell'operazione: $e", + ), + ); + } + } + // --- GESTIONE DEI CAMPI IN TEMPO REALE --- void updateFields({ String? reference, @@ -143,7 +178,7 @@ class OperationFormCubit extends Cubit { isBusiness: isBusiness ?? current.isBusiness, ); - emit(state.copyWith(operation: updated)); + emit(state.copyWith(operation: updated, hasUnsavedChanges: true)); } void updateCustomer(CustomerModel customer) { @@ -153,12 +188,12 @@ class OperationFormCubit extends Cubit { customerId: customer.id, isBusiness: isBusiness, ); - emit(state.copyWith(operation: updatedOperation)); + emit(state.copyWith(operation: updatedOperation, hasUnsavedChanges: true)); } void updateOperationDetailsList(List details) { final current = state.operation; final updated = current.copyWith(details: details); - emit(state.copyWith(operation: updated)); + emit(state.copyWith(operation: updated, hasUnsavedChanges: true)); } } diff --git a/lib/features/operations/blocs/operation_form_state.dart b/lib/features/operations/blocs/operation_form_state.dart index 5023f91..df70c34 100644 --- a/lib/features/operations/blocs/operation_form_state.dart +++ b/lib/features/operations/blocs/operation_form_state.dart @@ -1,30 +1,52 @@ part of 'operation_form_cubit.dart'; -enum OperationFormStatus { initial, loading, ready, saving, success, failure } +enum OperationFormStatus { + initial, + loading, + ready, + saving, + success, + failure, + discarded, +} class OperationFormState extends Equatable { final OperationFormStatus status; final OperationModel operation; final String? errorMessage; + final bool isNew; + final bool hasUnsavedChanges; const OperationFormState({ this.status = OperationFormStatus.initial, required this.operation, this.errorMessage, + this.isNew = false, + this.hasUnsavedChanges = false, }); OperationFormState copyWith({ OperationFormStatus? status, OperationModel? operation, String? errorMessage, + bool? isNew, + bool? hasUnsavedChanges, }) { return OperationFormState( status: status ?? this.status, operation: operation ?? this.operation, errorMessage: errorMessage, + isNew: isNew ?? this.isNew, + hasUnsavedChanges: hasUnsavedChanges ?? this.hasUnsavedChanges, ); } @override - List get props => [status, operation, errorMessage]; + List get props => [ + status, + operation, + errorMessage, + isNew, + hasUnsavedChanges, + ]; } diff --git a/lib/features/operations/data/operations_repository.dart b/lib/features/operations/data/operations_repository.dart index 0bab41a..fc67cf2 100644 --- a/lib/features/operations/data/operations_repository.dart +++ b/lib/features/operations/data/operations_repository.dart @@ -160,10 +160,14 @@ class OperationsRepository { storeId: currentStore.id, staffId: createdById, companyId: currentStore.companyId, + status: OperationStatus.success, ) .toMap(), ) - .select() + .select(''' + *, + ${Tables.staffMembers}(*) + ''') .single(); return OperationModel.fromMap(res); } on Exception catch (e) { @@ -187,10 +191,39 @@ class OperationsRepository { .from(Tables.operations) .update(operation.toMap()) .eq('id', operation.id!); - for (OperationDetailModel operationDetail in operation.details) { + + final currentDetailIds = + operation.details + .map((d) => d.id) + .where((id) => id != null && id.isNotEmpty) + .cast() + .toList(); + + if (currentDetailIds.isNotEmpty) { await _supabase .from(Tables.operationDetails) - .upsert(operationDetail.toMap()); + .delete() + .eq('operation_id', operation.id!) + .not('id', 'in', currentDetailIds); + } else { + await _supabase + .from(Tables.operationDetails) + .delete() + .eq('operation_id', operation.id!); + } + + for (OperationDetailModel detail in operation.details) { + final detailToSave = detail.copyWith( + operationId: + detail.operationId.isNotEmpty ? detail.operationId : operation.id!, + companyId: + detail.companyId.isNotEmpty + ? detail.companyId + : operation.companyId, + ); + await _supabase + .from(Tables.operationDetails) + .upsert(detailToSave.toMap()); } } catch (e) { debugPrint('ERRORE SALVATAGGIO OPERAZIONE: $e'); diff --git a/lib/features/operations/models/operation_detail_model.dart b/lib/features/operations/models/operation_detail_model.dart index b89943e..a2bf7c4 100644 --- a/lib/features/operations/models/operation_detail_model.dart +++ b/lib/features/operations/models/operation_detail_model.dart @@ -114,18 +114,31 @@ class OperationDetailModel extends Equatable { } Map toMap() { + final String? pId = + (provider?.id != null && provider!.id!.isNotEmpty) + ? provider!.id + : (providerId != null && providerId!.isNotEmpty + ? providerId + : null); + + final String? mId = + (model?.id != null && model!.id!.isNotEmpty) + ? model!.id + : (modelId != null && modelId!.isNotEmpty ? modelId : null); + return { - if (id != null) 'id': id, - 'operation_id': operationId, - 'type': type, - 'provider_id': provider?.id ?? providerId, - 'model_id': model?.id ?? modelId, - 'description': description, + if (id?.isNotEmpty == true) 'id': id, + if (operationId.isNotEmpty) 'operation_id': operationId, + if (type?.isNotEmpty == true) 'type': type, + if (pId?.isNotEmpty == true) 'provider_id': pId, + if (mId?.isNotEmpty == true) 'model_id': mId, + if (description?.isNotEmpty == true) 'description': description, if (expirationDate != null) 'expiration_date': expirationDate!.toIso8601String(), - 'company_id': companyId, - if (lastCampaignId != null) 'last_campaign_id': lastCampaignId, - 'sub_type': subType, + if (companyId.isNotEmpty) 'company_id': companyId, + if (lastCampaignId?.isNotEmpty == true) + 'last_campaign_id': lastCampaignId, + if (subType?.isNotEmpty == true) 'sub_type': subType, }; } } diff --git a/lib/features/operations/models/operation_model.dart b/lib/features/operations/models/operation_model.dart index 05b5012..ff63812 100644 --- a/lib/features/operations/models/operation_model.dart +++ b/lib/features/operations/models/operation_model.dart @@ -57,7 +57,7 @@ class OperationModel extends Equatable { this.storeDisplayName, this.staffId, this.staffDisplayName, - this.status = OperationStatus.draft, + this.status = OperationStatus.success, this.customerId, this.customer, this.reference = '', diff --git a/lib/features/operations/ui/operation_form_new_screen.dart b/lib/features/operations/ui/operation_form_new_screen.dart deleted file mode 100644 index 915317e..0000000 --- a/lib/features/operations/ui/operation_form_new_screen.dart +++ /dev/null @@ -1,234 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter/widgets.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart'; -import 'package:flux/features/operations/blocs/operation_form_cubit.dart'; -import 'package:flux/features/operations/models/operation_detail_model.dart'; -import 'package:flux/features/operations/models/operation_model.dart'; - -class OperationFormNewScreen extends StatefulWidget { - final String? operationId; - final OperationModel? operation; - - const OperationFormNewScreen({super.key, this.operationId, this.operation}); - - @override - State createState() => _OperationFormNewScreenState(); -} - -class _OperationFormNewScreenState extends State { - final _formKey = GlobalKey(); - - bool _isInitialized = false; - bool _isClosingIntent = false; - - final _referenceController = TextEditingController(); - final _notesController = TextEditingController(); - - @override - void initState() { - super.initState(); - // 1. Lanciamo l'inizializzazione sincrona/asincrona - context.read().initForm( - existingOperation: widget.operation, - operationId: widget.operationId, - ); - - // 2. Lettura immediata dello stato (come fatto per il customer!) - final currentState = context.read().state; - if (currentState.status == OperationFormStatus.ready && !_isInitialized) { - _syncTextControllers(currentState.operation); - } - } - - @override - void dispose() { - _referenceController.dispose(); - _notesController.dispose(); - super.dispose(); - } - - void _syncTextControllers(OperationModel model) { - if (_referenceController.text.isEmpty) { - _referenceController.text = model.reference; - } - if (_notesController.text.isEmpty) { - _notesController.text = model.note; - } - - _isInitialized = true; - } - - void _flushControllersToCubit() { - context.read().updateFields( - reference: _referenceController.text, - note: _notesController.text, - ); - } - - void _saveOperation({ - required OperationStatus targetStatus, - required bool isClosingIntent, - }) { - if (!_formKey.currentState!.validate()) return; - - _isClosingIntent = isClosingIntent; - - _flushControllersToCubit(); - context.read().updateFields(status: targetStatus); - context.read().saveOperation( - targetStatus: targetStatus, - ); - } - - Color _getStatusColor(OperationStatus status) { - switch (status) { - case OperationStatus.success: - return Colors.green; - case OperationStatus.waitingForAction: - return Colors.orange; - case OperationStatus.waitingForSupport: - return Colors.blue; - case OperationStatus.failure: - return Colors.red; - case OperationStatus.draft: - return Colors.grey; - } - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - List details = context - .watch() - .state - .details; - return BlocConsumer( - listener: (context, state) { - if (state.status == OperationFormStatus.ready && !_isInitialized) { - _syncTextControllers(state.operation); - } - if (state.status == OperationFormStatus.success && _isClosingIntent) { - Navigator.of(context).pop(); - } else if (state.status == OperationFormStatus.failure) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text('Si è verificato un errore. ${state.errorMessage}'), - backgroundColor: Colors.red, - ), - ); - } - }, - builder: (context, state) { - if (!_isInitialized && - (widget.operationId != null || widget.operation != null) && - state.status == OperationFormStatus.loading) { - return const Scaffold( - body: Center(child: CircularProgressIndicator()), - ); - } - return Scaffold( - appBar: AppBar( - leading: IconButton( - icon: const Icon(Icons.arrow_back), - onPressed: () { - //TODO controlla se l'utente non ha ancora inserito dati rilevanti e nel caso cancella l'operazione e torna all'home page - Navigator.of(context).pop(); - }, - ), - title: Text( - 'Addetto selezionato: ${state.operation.staffDisplayName}', - ), - actions: [ - Padding( - padding: const EdgeInsets.only(right: 10), - child: Chip( - label: Text( - state.operation.status.displayName, - style: const TextStyle(color: Colors.white, fontSize: 12), - ), - backgroundColor: _getStatusColor(state.operation.status), - ), - ), - ], - ), - body: Form( - key: _formKey, - child: FocusTraversalGroup( - policy: WidgetOrderTraversalPolicy(), - child: LayoutBuilder( - builder: (context, constraints) { - final isUltraWide = constraints.maxWidth > 1400; - final isDesktop = constraints.maxWidth > 900; - return SingleChildScrollView( - padding: const EdgeInsets.all(16.0), - child: Center( - child: ConstrainedBox( - constraints: BoxConstraints( - maxWidth: isUltraWide - ? 1600 - : isDesktop - ? 1200 - : 800, - ), - child: _buildResponsiveLayout( - isUltraWide, - isDesktop, - state, - ), - ), - ), - ); - }, - ), - ), - ), - bottomNavigationBar: SafeArea( - child: Container( - padding: const EdgeInsets.all(16.0), - decoration: BoxDecoration( - color: theme.scaffoldBackgroundColor, - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.05), - blurRadius: 10, - offset: const Offset(0, -3), - ), - ], - ), - child: Row( - children: [ - Expanded( - flex: 1, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: _getStatusColor( - state.operation.status, - ), - foregroundColor: Colors.white, - ), - onPressed: () => _saveOperation( - targetStatus: state.operation.status, - isClosingIntent: true, - ), - child: state.status == OperationFormStatus.saving - ? const SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator( - color: Colors.white, - strokeWidth: 2, - ), - ) - : Text('Salva e chiudi'), - ), - ), - ], - ), - ), - ), - ); - }, - ); - } -} diff --git a/lib/features/operations/ui/operation_form_screen.dart b/lib/features/operations/ui/operation_form_screen.dart index 5dc66a0..ad7a00c 100644 --- a/lib/features/operations/ui/operation_form_screen.dart +++ b/lib/features/operations/ui/operation_form_screen.dart @@ -1,60 +1,43 @@ 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/widgets/shared_forms/attachments_section.dart'; +import 'package:flux/core/widgets/shared_forms/customer_section.dart'; import 'package:flux/features/attachments/blocs/attachments_bloc.dart'; -import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart'; +import 'package:flux/features/operations/blocs/operation_details_list_cubit.dart'; import 'package:flux/features/operations/blocs/operation_form_cubit.dart'; import 'package:flux/features/operations/models/operation_model.dart'; -import 'package:flux/core/widgets/shared_forms/customer_section.dart'; -import 'package:flux/features/operations/ui/widgets/details_section.dart'; +import 'package:flux/features/operations/ui/widgets/operation_details_section.dart'; class OperationFormScreen extends StatefulWidget { final String? operationId; - final OperationModel? existingOperation; + final OperationModel? operation; - const OperationFormScreen({ - super.key, - this.operationId, - this.existingOperation, - }); + const OperationFormScreen({super.key, this.operationId, this.operation}); @override State createState() => _OperationFormScreenState(); } +enum _UnsavedChangesAction { cancel, saveAndClose, discard } + class _OperationFormScreenState extends State { final _formKey = GlobalKey(); - // 🥷 IL NUOVO FLAG: Ci ricorderà se vogliamo davvero uscire! + bool _isInitialized = false; bool _isClosingIntent = false; final _referenceController = TextEditingController(); - final _noteController = TextEditingController(); - final _freeTextSubtypeController = TextEditingController(); - final _freeTextDescriptionController = TextEditingController(); - - final List _availableTypes = [ - 'AL', - 'MNP', - 'NIP', - 'UNICA', - 'FWA', - 'TELEPASS', - 'Energy', - 'Fin', - 'Entertainment', - 'Altro', - ]; - - bool _isInitialized = false; + final _notesController = TextEditingController(); @override void initState() { super.initState(); + _referenceController.addListener(_onFieldChanged); + _notesController.addListener(_onFieldChanged); + // 1. Lanciamo l'inizializzazione sincrona/asincrona context.read().initForm( - existingOperation: widget.existingOperation, + existingOperation: widget.operation, operationId: widget.operationId, ); @@ -67,71 +50,95 @@ class _OperationFormScreenState extends State { @override void dispose() { + _referenceController.removeListener(_onFieldChanged); + _notesController.removeListener(_onFieldChanged); _referenceController.dispose(); - _noteController.dispose(); - _freeTextSubtypeController.dispose(); - _freeTextDescriptionController.dispose(); + _notesController.dispose(); super.dispose(); } + void _onFieldChanged() { + if (!_isInitialized) return; + _flushControllersToCubit(); + } + void _syncTextControllers(OperationModel model) { if (_referenceController.text.isEmpty) { _referenceController.text = model.reference; } - if (_noteController.text.isEmpty) { - _noteController.text = model.note; - } - if (_freeTextSubtypeController.text.isEmpty) { - _freeTextSubtypeController.text = model.subType ?? ''; - } - if (_freeTextDescriptionController.text.isEmpty) { - _freeTextDescriptionController.text = model.description ?? ''; + if (_notesController.text.isEmpty) { + _notesController.text = model.note; } + _isInitialized = true; } void _flushControllersToCubit() { context.read().updateFields( reference: _referenceController.text, - note: _noteController.text, - subType: _freeTextSubtypeController.text, - description: _freeTextDescriptionController.text, + note: _notesController.text, ); } void _saveOperation({ required OperationStatus targetStatus, - required bool keepAdding, + required bool isClosingIntent, }) { - if (_formKey.currentState!.validate()) { - // Se non stiamo facendo "Salva e Aggiungi Altro", il nostro intento è chiudere - _isClosingIntent = !keepAdding; + if (!_formKey.currentState!.validate()) return; - _flushControllersToCubit(); - context.read().updateFields(status: targetStatus); - context.read().saveOperation( - targetStatus: targetStatus, - keepAdding: keepAdding, - ); - } - } - - // RINOMINATA E RESA SICURA - Future _ensureEntitySaved() async { - if (!_formKey.currentState!.validate()) return null; - - // 🥷 Diciamo esplicitamente al sistema che NON vogliamo uscire dalla pagina - _isClosingIntent = false; + _isClosingIntent = isClosingIntent; _flushControllersToCubit(); + context.read().updateFields(status: targetStatus); + context.read().saveOperation( + targetStatus: targetStatus, + ); + } - final attachmentsBloc = context.read(); - - final newId = await context.read().saveOperationDraft(); - if (newId != null && context.mounted) { - attachmentsBloc.add(ParentEntitySavedEvent(newId)); - } - return newId; + Future<_UnsavedChangesAction?> _showUnsavedChangesDialog( + BuildContext context, + ) { + return showDialog<_UnsavedChangesAction>( + context: context, + builder: (dialogContext) { + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.warning_amber_rounded, color: Colors.orange), + SizedBox(width: 8), + Text('Modifiche non salvate'), + ], + ), + content: const Text( + 'Ci sono modifiche non salvate. Cosa desideri fare?', + ), + actions: [ + TextButton( + onPressed: + () => Navigator.of( + dialogContext, + ).pop(_UnsavedChangesAction.cancel), + child: const Text('Annulla'), + ), + TextButton( + style: TextButton.styleFrom(foregroundColor: Colors.red), + onPressed: + () => Navigator.of( + dialogContext, + ).pop(_UnsavedChangesAction.discard), + child: const Text('Chiudi senza salvare'), + ), + ElevatedButton( + onPressed: + () => Navigator.of( + dialogContext, + ).pop(_UnsavedChangesAction.saveAndClose), + child: const Text('Salva e chiudi'), + ), + ], + ); + }, + ); } Color _getStatusColor(OperationStatus status) { @@ -153,194 +160,204 @@ class _OperationFormScreenState extends State { Widget build(BuildContext context) { final theme = Theme.of(context); - return BlocConsumer( - listenWhen: (previous, current) => previous.status != current.status, - listener: (context, state) { - if (state.status == OperationFormStatus.ready && !_isInitialized) { - _syncTextControllers(state.operation); - } - - // 🥷 ORA POPPA SOLO SE L'INTENTO ERA QUELLO DI USCIRE! - if (state.status == OperationFormStatus.success) { - if (_isClosingIntent) { - Navigator.of(context).pop(); - } else { - // È stato un salvataggio background (Pick Files o QR). - // Non facciamo nulla, l'utente resta sulla pagina e i file vengono caricati! - } - } else if (state.status == OperationFormStatus.successAndAddAnother) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Operazione salvata! Inserisci la prossima'), - ), - ); - _freeTextSubtypeController.clear(); - _freeTextDescriptionController.clear(); - _referenceController.clear(); - } else if (state.status == OperationFormStatus.failure) { - ScaffoldMessenger.of(context).showSnackBar( - SnackBar( - content: Text(state.errorMessage ?? 'Errore di salvataggio'), - backgroundColor: Colors.red, - ), + return BlocListener( + listener: (listContext, listState) { + if (listState.status == OperationDetailsListStatus.ready || + listState.status == OperationDetailsListStatus.updated) { + context.read().updateOperationDetailsList( + listState.details, ); } }, - builder: (context, state) { - if (!_isInitialized && - (widget.operationId != null || widget.existingOperation != null) && - state.status == OperationFormStatus.loading) { - return const Scaffold( - body: Center(child: CircularProgressIndicator()), - ); - } - - final displayStatus = - state.operation.status == OperationStatus.draft && - state.operation.id == null - ? OperationStatus.success - : state.operation.status; - - return Scaffold( - appBar: AppBar( - title: Text( - state.operation.id == null - ? 'Nuova Pratica - Operatore: ${state.operation.staffDisplayName}' - : 'Modifica Pratica - Operatore: ${state.operation.staffDisplayName}', - ), - actions: - displayStatus != OperationStatus.success && - displayStatus != OperationStatus.draft - ? [ - Padding( - padding: const EdgeInsets.only(right: 16.0), - child: Chip( - label: Text( - displayStatus.displayName, - style: const TextStyle( - color: Colors.white, - fontSize: 12, + child: BlocConsumer( + listener: (formContext, formState) { + if (formState.status == OperationFormStatus.ready && + !_isInitialized) { + _syncTextControllers(formState.operation); + } + if ((formState.status == OperationFormStatus.success && + _isClosingIntent) || + formState.status == OperationFormStatus.discarded) { + Navigator.of(formContext).pop(); + } else if (formState.status == OperationFormStatus.failure) { + ScaffoldMessenger.of(formContext).showSnackBar( + SnackBar( + content: Text( + 'Si è verificato un errore. ${formState.errorMessage}', + ), + backgroundColor: Colors.red, + ), + ); + } + }, + builder: (formContext, formState) { + if (!_isInitialized && + (widget.operationId != null || widget.operation != null) && + formState.status == OperationFormStatus.loading) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + return PopScope( + canPop: !formState.hasUnsavedChanges, + onPopInvokedWithResult: (didPop, result) async { + if (didPop) return; + final action = await _showUnsavedChangesDialog(formContext); + if (!formContext.mounted || + action == null || + action == _UnsavedChangesAction.cancel) { + return; + } + if (action == _UnsavedChangesAction.saveAndClose) { + _saveOperation( + targetStatus: formState.operation.status, + isClosingIntent: true, + ); + } else if (action == _UnsavedChangesAction.discard) { + formContext.read().discardAndExit(); + } + }, + child: Scaffold( + appBar: AppBar( + leading: IconButton( + icon: const Icon(Icons.arrow_back), + onPressed: () { + Navigator.maybePop(formContext); + }, + ), + title: Row( + children: [ + Flexible( + child: Text( + 'Addetto selezionato: ${formState.operation.staffDisplayName}', + overflow: TextOverflow.ellipsis, + ), + ), + if (formState.hasUnsavedChanges) ...[ + const SizedBox(width: 8), + Tooltip( + message: 'Modifiche non salvate', + child: Container( + width: 10, + height: 10, + decoration: const BoxDecoration( + color: Colors.orange, + shape: BoxShape.circle, ), ), - backgroundColor: _getStatusColor(displayStatus), ), - ), - ] - : null, - ), - body: Form( - key: _formKey, - child: FocusTraversalGroup( - policy: WidgetOrderTraversalPolicy(), - child: LayoutBuilder( - builder: (context, constraints) { - final isUltraWide = constraints.maxWidth > 1400; - final isDesktop = constraints.maxWidth > 900; - - return SingleChildScrollView( - padding: const EdgeInsets.all(16.0), - child: Center( - child: ConstrainedBox( - constraints: BoxConstraints( - maxWidth: isUltraWide - ? 1600 - : (isDesktop ? 1200 : 800), - ), - child: _buildResponsiveLayout( - isUltraWide, - isDesktop, - state, - displayStatus, + ], + ], + ), + actions: [ + Padding( + padding: const EdgeInsets.only(right: 10), + child: Chip( + label: Text( + formState.operation.status.displayName, + style: const TextStyle( + color: Colors.white, + fontSize: 12, ), ), + backgroundColor: _getStatusColor( + formState.operation.status, + ), ), - ); - }, - ), - ), - ), - bottomNavigationBar: SafeArea( - child: Container( - padding: const EdgeInsets.all(16.0), - decoration: BoxDecoration( - color: theme.scaffoldBackgroundColor, - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.05), - blurRadius: 10, - offset: const Offset(0, -3), ), ], ), - child: Row( - children: [ - Expanded( - flex: 1, - child: ElevatedButton( - style: ElevatedButton.styleFrom( - backgroundColor: - displayStatus != OperationStatus.success && - displayStatus != OperationStatus.draft - ? _getStatusColor(displayStatus) - : null, - foregroundColor: - displayStatus != OperationStatus.success && - displayStatus != OperationStatus.draft - ? Colors.white - : null, - ), - onPressed: state.status == OperationFormStatus.saving - ? null - : () => _saveOperation( - keepAdding: false, - targetStatus: displayStatus, + body: Form( + key: _formKey, + child: FocusTraversalGroup( + policy: WidgetOrderTraversalPolicy(), + child: LayoutBuilder( + builder: (context, constraints) { + final isUltraWide = constraints.maxWidth > 1400; + final isDesktop = constraints.maxWidth > 900; + return SingleChildScrollView( + padding: const EdgeInsets.all(16.0), + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: + isUltraWide + ? 1600 + : isDesktop + ? 1200 + : 800, ), - child: state.status == OperationFormStatus.saving - ? const SizedBox( - width: 20, - height: 20, - child: CircularProgressIndicator( - color: Colors.white, - strokeWidth: 2, + child: _buildResponsiveLayout( + isUltraWide, + isDesktop, + formState, + ), + ), + ), + ); + }, + ), + ), + ), + bottomNavigationBar: SafeArea( + child: Container( + padding: const EdgeInsets.all(16.0), + decoration: BoxDecoration( + color: theme.scaffoldBackgroundColor, + boxShadow: [ + BoxShadow( + color: Colors.black.withValues(alpha: 0.05), + blurRadius: 10, + offset: const Offset(0, -3), + ), + ], + ), + child: Row( + children: [ + Expanded( + flex: 1, + child: ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: _getStatusColor( + formState.operation.status, + ), + foregroundColor: Colors.white, + ), + onPressed: + () => _saveOperation( + targetStatus: formState.operation.status, + isClosingIntent: true, ), - ) - : const Text('Salva ed Esci'), - ), - ), - const SizedBox(width: 12), - Expanded( - flex: 1, - child: OutlinedButton( - onPressed: state.status == OperationFormStatus.saving - ? null - : () => _saveOperation( - keepAdding: true, - targetStatus: displayStatus, - ), - child: const Text( - 'Salva e Aggiungi Altro', - textAlign: TextAlign.center, + child: + formState.status == OperationFormStatus.saving + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator( + color: Colors.white, + strokeWidth: 2, + ), + ) + : const Text('Salva e chiudi'), + ), ), - ), + ], ), - ], + ), ), ), - ), - ); - }, + ); + }, + ), ); } - // --- LOGICA DI IMPAGINAZIONE RESPONSIVE --- Widget _buildResponsiveLayout( bool isUltraWide, bool isDesktop, OperationFormState state, - OperationStatus displayStatus, ) { if (isUltraWide) { - // 3 COLONNE return Column( children: [ Row( @@ -351,52 +368,35 @@ class _OperationFormScreenState extends State { children: [_cardAnagrafica(state), _cardEsito(state)], ), ), - const SizedBox(width: 24), - Expanded(child: Column(children: [_cardDettagli(state)])), - const SizedBox(width: 24), - Expanded(child: Column(children: [_cardNote(state)])), + const SizedBox(width: 18), + Expanded(child: _cardAllegati(state)), + const SizedBox(width: 18), + Expanded(child: _cardNote(state)), ], ), - _cardAllegati(state), + _cardDettagli(state), ], ); } else if (isDesktop) { - // 2 COLONNE - return Row( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Expanded( - child: Column( - children: [ - _cardAnagrafica(state), - _cardEsito(state), - _cardAllegati(state), - ], - ), - ), - const SizedBox(width: 24), - Expanded( - child: Column(children: [_cardDettagli(state), _cardNote(state)]), - ), - ], - ); + return Row(children: []); } else { - // 1 COLONNA (Mobile) - return Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - children: [ - _cardAnagrafica(state), - _cardEsito(state), - _cardDettagli(state), - _cardNote(state), - _cardAllegati(state), - ], - ); + return Column(children: []); } } // --- LE CARD MODULARIZZATE E COLORATE --- + Widget _cardDettagli(OperationFormState state) { + return _buildCard( + title: 'Dettagli Servizi', + icon: Icons.design_services, + themeColor: Colors.deepOrange, + children: [ + const OperationDetailsSection(), + ], + ); + } + Widget _cardAnagrafica(OperationFormState state) { return _buildCard( title: 'Cliente e Riferimento', @@ -412,7 +412,7 @@ class _OperationFormScreenState extends State { TextFormField( controller: _referenceController, decoration: const InputDecoration( - labelText: 'Riferimento (es. Telefono, Targa...)', + labelText: 'Riferimenti', prefixIcon: Icon(Icons.tag), ), ), @@ -492,120 +492,6 @@ class _OperationFormScreenState extends State { ); } - Widget _cardDettagli(OperationFormState state) { - return _buildCard( - title: 'Dettagli Servizio', - icon: Icons.design_services, - themeColor: Colors.deepOrange, - children: [ - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: [ - ChoiceChip( - label: const Text('Privato (Domestico)'), - selected: !state.operation.isBusiness, - selectedColor: Colors.blue.withValues(alpha: 0.2), - checkmarkColor: Colors.blue.shade700, - onSelected: (selected) { - if (selected) { - context.read().updateFields( - isBusiness: false, - ); - } - }, - ), - const SizedBox(width: 12), - ChoiceChip( - label: const Text('Business (P.IVA)'), - selected: state.operation.isBusiness, - selectedColor: Colors.orange.withValues(alpha: 0.2), - checkmarkColor: Colors.orange.shade700, - onSelected: (selected) { - if (selected) { - context.read().updateFields( - isBusiness: true, - ); - } - }, - ), - ], - ), - ), - const Divider(height: 32), - Wrap( - spacing: 8.0, - runSpacing: 8.0, - children: _availableTypes.map((type) { - return ChoiceChip( - label: Text(type), - selected: state.operation.type == type, - onSelected: (selected) { - if (selected) { - // 1. Recuperiamo i provider caricati in memoria - final allProviders = context - .read() - .state - .providers; - - // 2. Recuperiamo il provider di default del negozio dalla sessione - final defaultProviderId = context - .read() - .state - .currentStore - ?.defaultProviderId; - - // 3. Spariamo tutto nel metodo "tuttofare" - context.read().setTypeWithSmartDefaults( - newType: type, - allProviders: allProviders, - defaultProviderId: defaultProviderId, - ); - } - }, - ); - }).toList(), - ), - const Divider(height: 32), - Row( - children: [ - const Text( - 'Quantità:', - style: TextStyle(fontWeight: FontWeight.bold), - ), - const Spacer(), - IconButton( - icon: const Icon(Icons.remove_circle_outline), - onPressed: state.operation.quantity > 1 - ? () => context.read().updateFields( - quantity: state.operation.quantity - 1, - ) - : null, - ), - Text( - '${state.operation.quantity}', - style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), - ), - IconButton( - icon: const Icon(Icons.add_circle_outline), - onPressed: () => context.read().updateFields( - quantity: state.operation.quantity + 1, - ), - ), - ], - ), - const Divider(height: 32), - OperationDetailsSection( - currentOp: state.operation, - currentType: state.operation.type, - freeTextSubtypeController: _freeTextSubtypeController, - freeTextDescriptionController: _freeTextDescriptionController, - durationQuickPicks: _buildDurationQuickPicks(), - ), - ], - ); - } - Widget _cardNote(OperationFormState state) { return _buildCard( title: 'Note Interne', @@ -613,7 +499,7 @@ class _OperationFormScreenState extends State { themeColor: Colors.teal, children: [ TextFormField( - controller: _noteController, + controller: _notesController, minLines: 14, maxLines: 500, decoration: InputDecoration( @@ -641,7 +527,6 @@ class _OperationFormScreenState extends State { parentType: AttachmentParentType.operation, parentId: state.operation.id, titleForUpload: state.operation.customer?.name ?? 'Nuova Pratica', - onEnsureEntitySaved: _ensureEntitySaved, // 🥷 Il nuovo nome! ), ], ); @@ -693,46 +578,4 @@ class _OperationFormScreenState extends State { ), ); } - - Widget _buildDurationQuickPicks() { - final durations = [3, 6, 12, 24, 30, 36, 48]; - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - const Text( - "Imposta durata rapida (mesi):", - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w600, - color: Colors.grey, - ), - ), - const SizedBox(height: 8), - SingleChildScrollView( - scrollDirection: Axis.horizontal, - child: Row( - children: durations.map((months) { - return Padding( - padding: const EdgeInsets.only(right: 8.0), - child: ActionChip( - label: Text("$months m"), - backgroundColor: Colors.blue.withValues(alpha: 0.05), - onPressed: () { - final now = DateTime.now(); - context.read().updateFields( - expirationDate: DateTime( - now.year, - now.month + months, - now.day, - ), - ); - }, - ), - ); - }).toList(), - ), - ), - ], - ); - } } diff --git a/lib/features/operations/ui/operation_list_screen.dart b/lib/features/operations/ui/operation_list_screen.dart index 00e1fa5..78f72a3 100644 --- a/lib/features/operations/ui/operation_list_screen.dart +++ b/lib/features/operations/ui/operation_list_screen.dart @@ -5,6 +5,7 @@ import 'package:flux/core/routes/routes.dart'; import 'package:flux/core/widgets/staff_selector_modal.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/operations/blocs/operation_list_cubit.dart'; +import 'package:flux/features/operations/models/operation_detail_model.dart'; import 'package:flux/features/operations/models/operation_model.dart'; import 'package:go_router/go_router.dart'; @@ -199,7 +200,7 @@ class _OperationListScreenState extends State { maxCrossAxisExtent: 420, // Larghezza bilanciata per le card su desktop mainAxisExtent: - 175, // Altezza controllata per evitare buchi bianchi + 185, // Altezza controllata per evitare buchi bianchi crossAxisSpacing: 16, mainAxisSpacing: 16, ), @@ -405,8 +406,8 @@ class _RichOperationCard extends StatelessWidget { } } - Color _getTypeColor(String type) { - switch (type) { + Color _getTypeColor(String? type) { + switch (type?.toUpperCase()) { case 'FIN': return Colors.deepPurple; case 'TELEPASS': @@ -426,11 +427,84 @@ class _RichOperationCard extends StatelessWidget { } } + IconData? _getIconForType(String? type, String? subtype) { + if (type?.toLowerCase() == 'energy') { + if (subtype?.toLowerCase() == 'luce') return Icons.bolt; + if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department; + } + return null; + } + + Widget _buildDetailItem(BuildContext context, OperationDetailModel detail) { + final typeColor = _getTypeColor(detail.type); + final providerColor = detail.provider?.displayColor ?? Colors.blueGrey; + final icon = _getIconForType(detail.type, detail.subType); + + final typeLabel = (detail.subType != null && detail.subType!.isNotEmpty) + ? '${detail.type ?? ''} (${detail.subType})' + : (detail.type ?? 'Dettaglio'); + + return Container( + padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4), + decoration: BoxDecoration( + color: typeColor.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(6), + border: Border.all( + color: typeColor.withValues(alpha: 0.25), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (icon != null) ...[ + Icon(icon, size: 12, color: typeColor), + const SizedBox(width: 4), + ], + Text( + typeLabel, + style: TextStyle( + color: typeColor, + fontWeight: FontWeight.bold, + fontSize: 11, + ), + ), + if (detail.provider?.name != null && detail.provider!.name.isNotEmpty) ...[ + const SizedBox(width: 6), + Container( + padding: const EdgeInsets.symmetric(horizontal: 5, vertical: 1.5), + decoration: BoxDecoration( + color: providerColor.withValues(alpha: 0.15), + borderRadius: BorderRadius.circular(4), + ), + child: Text( + detail.provider!.name, + style: TextStyle( + color: providerColor, + fontWeight: FontWeight.w600, + fontSize: 10, + ), + ), + ), + ], + if (detail.model?.name != null && detail.model!.name.isNotEmpty) ...[ + const SizedBox(width: 4), + Text( + '• ${detail.model!.name}', + style: TextStyle( + color: Colors.grey[700], + fontSize: 10, + ), + ), + ], + ], + ), + ); + } + @override Widget build(BuildContext context) { final theme = Theme.of(context); final statusColor = _getStatusColor(operation.status); - final typeColor = _getTypeColor(operation.type); return Card( margin: EdgeInsets.zero, // Gestito dai margini dei padri (griglia/lista) @@ -460,7 +534,7 @@ class _RichOperationCard extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - // --- LINEA HEADER --- + // --- RIGA 1: RIFERIMENTO E DATA --- Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -500,9 +574,9 @@ class _RichOperationCard extends StatelessWidget { ), const SizedBox(height: 8), - // --- LINEA CENTRALE: CLIENTE + INSERTO OPERATIVO --- + // --- RIGA 2: NOME CLIENTE E CHIP PRIVATO / BUSINESS --- Row( - crossAxisAlignment: CrossAxisAlignment.start, + crossAxisAlignment: CrossAxisAlignment.center, children: [ Expanded( child: Text( @@ -511,67 +585,11 @@ class _RichOperationCard extends StatelessWidget { fontWeight: FontWeight.bold, fontSize: 15, ), - maxLines: 2, + maxLines: 1, overflow: TextOverflow.ellipsis, ), ), const SizedBox(width: 8), - - // 🥷 IL RE DEL SERVICE: Il tipo operazione svetta con box e contrasto ad hoc - Container( - padding: const EdgeInsets.symmetric( - horizontal: 8, - vertical: 4, - ), - decoration: BoxDecoration( - color: typeColor.withValues(alpha: 0.12), - borderRadius: BorderRadius.circular(6), - border: Border.all( - color: typeColor.withValues(alpha: 0.25), - ), - ), - child: Row( - mainAxisSize: MainAxisSize.min, - children: [ - if (_getIconForType( - operation.type, - operation.subType, - ) != - null) ...[ - Icon( - _getIconForType( - operation.type, - operation.subType, - ), - size: 13, - color: typeColor, - ), - const SizedBox(width: 4), - ], - Text( - (operation.subType != null && - operation.subType!.isNotEmpty) - ? operation.subType! - : operation.type, - style: TextStyle( - color: typeColor, - fontWeight: FontWeight.bold, - fontSize: 11, - ), - ), - ], - ), - ), - ], - ), - const SizedBox(height: 10), - - // --- LINEA DEI TAG TECNICI --- - Wrap( - spacing: 6, - runSpacing: 4, - children: [ - // Tag Target Espanso (Privato / Business) _MiniChip( label: operation.isBusiness ? 'Business' : 'Privato', icon: operation.isBusiness @@ -579,28 +597,31 @@ class _RichOperationCard extends StatelessWidget { : Icons.person, color: operation.isBusiness ? Colors.indigo : Colors.teal, ), - - // Tag Gestore (Agganciato dinamicamente al displayColor generato dall'esadecimale del DB!) - if (operation.provider != null) - _MiniChip( - label: operation.provider?.name ?? 'Gestore', - color: - operation.provider?.displayColor ?? Colors.blueGrey, - ), - - // Specifiche addizionali del Finanziamento - if (operation.type == 'Fin' && operation.modelId != null) - _MiniChip( - label: operation.modelDisplayName ?? 'Prodotto', - icon: Icons.devices, - color: Colors.deepPurple, - ), ], ), + const SizedBox(height: 8), + + // --- RIGA 3: LISTA DEI VARI DETTAGLI (TIPO E PROVIDER) --- + if (operation.details.isEmpty) + Text( + 'Nessun dettaglio', + style: theme.textTheme.labelSmall?.copyWith( + color: Colors.grey[500], + fontStyle: FontStyle.italic, + ), + ) + else + Wrap( + spacing: 6, + runSpacing: 4, + children: operation.details + .map((detail) => _buildDetailItem(context, detail)) + .toList(), + ), const Spacer(), - // --- FOOTER CARD: AGENTE + CHIP STATO --- + // --- RIGA 4: NOME ADDETTO E STATO --- Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ @@ -647,14 +668,6 @@ class _RichOperationCard extends StatelessWidget { ), ); } - - IconData? _getIconForType(String type, String? subtype) { - if (type == 'Energy') { - if (subtype?.toLowerCase() == 'luce') return Icons.bolt; - if (subtype?.toLowerCase() == 'gas') return Icons.local_fire_department; - } - return null; - } } // Micro Widget di supporto per i tag interni diff --git a/lib/features/operations/ui/widgets/details_section.dart b/lib/features/operations/ui/widgets/details_section.dart deleted file mode 100644 index ff23429..0000000 --- a/lib/features/operations/ui/widgets/details_section.dart +++ /dev/null @@ -1,265 +0,0 @@ -import 'package:flutter/material.dart'; -import 'package:flutter_bloc/flutter_bloc.dart'; -import 'package:flux/core/widgets/shared_forms/model_section.dart'; -import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart'; -import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart'; -import 'package:flux/features/operations/blocs/operation_form_cubit.dart'; -import 'package:flux/features/operations/models/operation_model.dart'; - -class OperationDetailsSection extends StatelessWidget { - final OperationModel? currentOp; - final String currentType; - final TextEditingController freeTextSubtypeController; - final TextEditingController freeTextDescriptionController; - final Widget durationQuickPicks; - - const OperationDetailsSection({ - super.key, - required this.currentOp, - required this.currentType, - required this.freeTextSubtypeController, - required this.freeTextDescriptionController, - required this.durationQuickPicks, - }); - - void _showProviderModal(BuildContext context, String operationType) { - final OperationFormCubit cubit = context.read(); - showModalBottomSheet( - context: context, - isScrollControlled: true, - shape: const RoundedRectangleBorder( - borderRadius: BorderRadius.vertical(top: Radius.circular(16)), - ), - builder: (modalContext) { - return DraggableScrollableSheet( - initialChildSize: 0.5, - minChildSize: 0.4, - maxChildSize: 0.8, - expand: false, - builder: (_, scrollController) { - return Column( - children: [ - Padding( - padding: const EdgeInsets.all(16.0), - child: Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: [ - Text( - 'Seleziona Gestore', - style: Theme.of(context).textTheme.titleLarge, - ), - IconButton( - icon: const Icon(Icons.close), - onPressed: () => Navigator.pop(modalContext), - ), - ], - ), - ), - const Divider(), - Expanded( - child: BlocBuilder( - builder: (context, state) { - if (state.status == ProviderListStatus.loading) { - return const Center(child: CircularProgressIndicator()); - } - - // 🥷 IL TOCCO DEL NINJA: Filtriamo usando direttamente l'Extension sul Modello! - final filteredProviders = state.providers.where((p) { - return p.supportsOperation(operationType) && p.isActive; - }).toList(); - - if (filteredProviders.isEmpty) { - return const Center( - child: Text( - 'Nessun gestore compatibile con questo servizio.', - style: TextStyle(color: Colors.grey), - ), - ); - } - - return BlocProvider.value( - value: cubit, - child: ListView.builder( - controller: scrollController, - itemCount: filteredProviders.length, - itemBuilder: (context, index) { - final provider = filteredProviders[index]; - return ListTile( - leading: const Icon(Icons.business), - title: Text( - provider.name, - style: const TextStyle( - fontWeight: FontWeight.bold, - ), - ), - // Facoltativo: mostra i ruoli sotto al nome - subtitle: Text( - provider.roles - .map((r) => r.displayValue) - .join(', '), - style: const TextStyle(fontSize: 12), - maxLines: 1, - overflow: TextOverflow.ellipsis, - ), - onTap: () { - context - .read() - .updateProvider(provider); - Navigator.pop(modalContext); - }, - ); - }, - ), - ); - }, - ), - ), - ], - ); - }, - ); - }, - ); - } - - @override - Widget build(BuildContext context) { - final theme = Theme.of(context); - - return Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - // PROVIDER (Mostrato quasi sempre) - ListTile( - title: const Text('Seleziona Gestore'), - subtitle: Text( - (currentOp?.provider != null) - ? currentOp!.provider!.name - : 'Nessun gestore selezionato', - style: TextStyle( - color: - (currentOp?.provider == null || - currentOp!.provider!.name.isEmpty) - ? Colors.grey - : null, - fontWeight: - (currentOp?.provider == null || - currentOp!.provider!.name.isEmpty) - ? FontWeight.normal - : FontWeight.bold, - ), - ), - trailing: const Icon(Icons.arrow_drop_down), - shape: RoundedRectangleBorder( - side: BorderSide(color: theme.dividerColor), - borderRadius: BorderRadius.circular(8), - ), - onTap: () => _showProviderModal(context, currentType), - ), - const SizedBox(height: 16), - - // 1. SCENARIO ENERGY (Dropdown Fisso) - if (currentType == 'Energy') ...[ - DropdownButtonFormField( - initialValue: - (currentOp?.subType != null && currentOp!.subType!.isNotEmpty) - ? currentOp!.subType - : null, - decoration: const InputDecoration(labelText: 'Dettaglio Fornitura'), - items: [ - 'Luce', - 'Gas', - ].map((s) => DropdownMenuItem(value: s, child: Text(s))).toList(), - onChanged: (val) { - if (val != null) { - context.read().updateFields(subType: val); - } - }, - ), - const SizedBox(height: 16), - TextFormField( - controller: freeTextDescriptionController, - decoration: InputDecoration( - labelText: currentType == 'Energy' - ? 'Offerta scelta' - : 'Nome del servizio/offerta', - ), - ), - const SizedBox(height: 16), - ], - - // 2. SCENARIO FIN (Ricerca Modello/Prodotto) - if (currentType == 'Fin') ...[ - SharedModelSection( - label: 'Seleziona Dispositivo/Prodotto', - modelId: currentOp?.modelId, - modelName: currentOp?.modelDisplayName, - onModelSelected: (id, name) { - context.read().updateFields( - modelId: id, - modelDisplayName: name, - ); - }, - ), - const SizedBox(height: 16), - ], - - // 3. SCENARIO ENTERTAINMENT O CUSTOM (Testo libero) - if (currentType == 'Entertainment' || currentType == 'Altro') ...[ - TextFormField( - controller: freeTextSubtypeController, - decoration: InputDecoration( - labelText: currentType == 'Entertainment' - ? 'Piattaforma (es. Netflix, DAZN, Spotify...)' - : 'Specifica il servizio (es. Monopattino)', - ), - ), - const SizedBox(height: 16), - ], - - // SCADENZA (Reattivo per tipi complessi) - if ([ - 'Energy', - 'Fin', - 'Entertainment', - 'Altro', - ].contains(currentType)) ...[ - const SizedBox(height: 8), - durationQuickPicks, // Passiamo i chips dall'esterno - const SizedBox(height: 16), - ListTile( - title: const Text('Data di Scadenza Effettiva'), - subtitle: Text( - currentOp?.expirationDate != null - ? "${currentOp!.expirationDate!.day}/${currentOp!.expirationDate!.month}/${currentOp!.expirationDate!.year}" - : 'Nessuna scadenza impostata', - style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16), - ), - trailing: const Icon(Icons.calendar_month, color: Colors.blue), - tileColor: Colors.blue.withValues(alpha: 0.05), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(12), - side: const BorderSide(color: Colors.blue, width: 0.5), - ), - onTap: () async { - final date = await showDatePicker( - context: context, - initialDate: - currentOp?.expirationDate ?? - DateTime.now().add(const Duration(days: 365)), - firstDate: DateTime.now(), - lastDate: DateTime.now().add(const Duration(days: 3650)), - ); - if (date != null && context.mounted) { - context.read().updateFields( - expirationDate: date, - ); - } - }, - ), - const SizedBox(height: 16), - ], - ], - ); - } -} diff --git a/lib/features/operations/ui/widgets/operation_details_section.dart b/lib/features/operations/ui/widgets/operation_details_section.dart new file mode 100644 index 0000000..e46f493 --- /dev/null +++ b/lib/features/operations/ui/widgets/operation_details_section.dart @@ -0,0 +1,809 @@ +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/widgets/shared_forms/model_section.dart'; +import 'package:flux/features/master_data/providers/blocs/provider_list_cubit.dart'; +import 'package:flux/features/master_data/providers/models/provider_model_extensions.dart'; +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'; + +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); + + return BlocBuilder( + builder: (context, listState) { + final details = listState.details; + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Dettagli Servizi (${details.length})', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + ElevatedButton.icon( + onPressed: () => _openDetailFormModal(context), + icon: const Icon(Icons.add, size: 18), + label: const Text('Aggiungi Dettaglio'), + ), + ], + ), + const SizedBox(height: 12), + if (details.isEmpty) + Container( + width: double.infinity, + padding: const EdgeInsets.all(24.0), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest.withValues( + alpha: 0.3, + ), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: theme.dividerColor.withValues(alpha: 0.5), + ), + ), + child: Column( + children: [ + Icon( + Icons.playlist_add, + size: 40, + color: Colors.grey.shade400, + ), + const SizedBox(height: 8), + Text( + 'Nessun dettaglio aggiunto', + style: TextStyle( + fontWeight: FontWeight.bold, + color: Colors.grey.shade700, + ), + ), + const SizedBox(height: 4), + Text( + 'Premi "+ Aggiungi Dettaglio" per inserire un servizio per questa pratica.', + style: TextStyle( + fontSize: 12, + color: Colors.grey.shade600, + ), + textAlign: TextAlign.center, + ), + ], + ), + ) + else + ListView.separated( + shrinkWrap: true, + physics: const NeverScrollableScrollPhysics(), + itemCount: details.length, + separatorBuilder: (_, _) => const SizedBox(height: 8), + itemBuilder: (context, index) { + final detail = details[index]; + return _buildDetailTile(context, detail, index); + }, + ), + ], + ); + }, + ); + } + + Widget _buildDetailTile( + BuildContext context, + OperationDetailModel detail, + int index, + ) { + final typeColor = _getTypeColor(detail.type); + final providerColor = detail.provider?.displayColor ?? Colors.blueGrey; + + final typeText = + (detail.subType != null && detail.subType!.isNotEmpty) + ? '${detail.type ?? ''} (${detail.subType})' + : (detail.type ?? 'Dettaglio'); + + return Card( + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(10), + side: BorderSide(color: typeColor.withValues(alpha: 0.3)), + ), + child: Padding( + padding: const EdgeInsets.all(12.0), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: typeColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: Icon( + _getIconForType(detail.type, detail.subType), + color: typeColor, + size: 20, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Text( + typeText, + style: TextStyle( + fontWeight: FontWeight.bold, + color: typeColor, + fontSize: 14, + ), + ), + if (detail.provider?.name != null && + detail.provider!.name.isNotEmpty) ...[ + const SizedBox(width: 8), + Chip( + visualDensity: VisualDensity.compact, + padding: EdgeInsets.zero, + label: Text( + detail.provider!.name, + style: TextStyle( + color: providerColor, + fontSize: 11, + fontWeight: FontWeight.bold, + ), + ), + backgroundColor: providerColor.withValues( + alpha: 0.15, + ), + side: BorderSide( + color: providerColor.withValues(alpha: 0.3), + ), + ), + ], + ], + ), + if (detail.model?.name != null && + detail.model!.name.isNotEmpty) ...[ + const SizedBox(height: 4), + Row( + children: [ + const Icon(Icons.devices, size: 14, color: Colors.grey), + const SizedBox(width: 4), + Text( + detail.model!.name, + style: const TextStyle(fontSize: 12), + ), + ], + ), + ], + if (detail.description != null && + detail.description!.isNotEmpty) ...[ + const SizedBox(height: 4), + Text( + detail.description!, + style: TextStyle(fontSize: 12, color: Colors.grey[700]), + ), + ], + if (detail.expirationDate != null) ...[ + const SizedBox(height: 4), + Row( + children: [ + const Icon( + Icons.calendar_month, + size: 14, + color: Colors.blue, + ), + const SizedBox(width: 4), + Text( + 'Scadenza: ${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}', + style: const TextStyle( + fontSize: 11, + color: Colors.blue, + ), + ), + ], + ), + ], + ], + ), + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + icon: const Icon(Icons.edit, size: 18), + onPressed: + () => _openDetailFormModal( + context, + existingDetail: detail, + index: index, + ), + ), + IconButton( + icon: const Icon( + Icons.delete_outline, + size: 18, + color: Colors.red, + ), + onPressed: () { + context + .read() + .deleteOperationDetail(index); + }, + ), + ], + ), + ], + ), + ), + ); + } + + void _openDetailFormModal( + BuildContext context, { + OperationDetailModel? existingDetail, + int? index, + }) { + final listCubit = context.read(); + final allProviders = context.read().state.providers; + final defaultProviderId = + context.read().state.currentStore?.defaultProviderId; + + showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (sheetContext) { + return BlocProvider( + create: + (_) => OperationDetailsFormCubit( + initialDetail: existingDetail, + editingIndex: index, + allProviders: allProviders, + defaultProviderId: defaultProviderId, + ), + child: _OperationDetailFormSheet(listCubit: listCubit), + ); + }, + ); + } + + 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; + } + } + + IconData _getIconForType(String? type, String? subtype) { + if (type?.toLowerCase() == '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; + } + } +} + +class _OperationDetailFormSheet extends StatefulWidget { + final OperationDetailsListCubit listCubit; + + const _OperationDetailFormSheet({required this.listCubit}); + + @override + State<_OperationDetailFormSheet> createState() => + _OperationDetailFormSheetState(); +} + +class _OperationDetailFormSheetState + extends State<_OperationDetailFormSheet> { + late TextEditingController _subtypeController; + late TextEditingController _descriptionController; + + @override + void initState() { + super.initState(); + final initialDetail = + context.read().state.operationDetail; + _subtypeController = TextEditingController( + text: initialDetail.subType ?? '', + ); + _descriptionController = TextEditingController( + text: initialDetail.description ?? '', + ); + } + + @override + void dispose() { + _subtypeController.dispose(); + _descriptionController.dispose(); + super.dispose(); + } + + void _showProviderModal(BuildContext context, String operationType) { + final formCubit = context.read(); + showModalBottomSheet( + context: context, + isScrollControlled: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(16)), + ), + builder: (modalContext) { + return DraggableScrollableSheet( + initialChildSize: 0.5, + minChildSize: 0.4, + maxChildSize: 0.8, + expand: false, + builder: (_, scrollController) { + return Column( + children: [ + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + 'Seleziona Gestore', + style: Theme.of(context).textTheme.titleLarge, + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(modalContext), + ), + ], + ), + ), + const Divider(), + Expanded( + child: BlocBuilder( + builder: (context, state) { + if (state.status == ProviderListStatus.loading) { + return const Center(child: CircularProgressIndicator()); + } + + final filteredProviders = + state.providers.where((p) { + return p.supportsOperation(operationType) && + p.isActive; + }).toList(); + + if (filteredProviders.isEmpty) { + return const Center( + child: Text( + 'Nessun gestore compatibile con questo servizio.', + style: TextStyle(color: Colors.grey), + ), + ); + } + + return ListView.builder( + controller: scrollController, + itemCount: filteredProviders.length, + itemBuilder: (context, index) { + final provider = filteredProviders[index]; + return ListTile( + leading: const Icon(Icons.business), + title: Text( + provider.name, + style: const TextStyle( + fontWeight: FontWeight.bold, + ), + ), + subtitle: Text( + provider.roles + .map((r) => r.displayValue) + .join(', '), + style: const TextStyle(fontSize: 12), + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + onTap: () { + formCubit.setProvider(provider); + Navigator.pop(modalContext); + }, + ); + }, + ); + }, + ), + ), + ], + ); + }, + ); + }, + ); + } + + Widget _buildDurationQuickPicks(BuildContext context) { + final durations = [3, 6, 12, 24, 30, 36, 48]; + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text( + "Imposta durata rapida (mesi):", + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w600, + color: Colors.grey, + ), + ), + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: + durations.map((months) { + return Padding( + padding: const EdgeInsets.only(right: 8.0), + child: ActionChip( + label: Text("$months m"), + backgroundColor: Colors.blue.withValues(alpha: 0.05), + onPressed: () { + final now = DateTime.now(); + context + .read() + .updateFields( + expirationDate: DateTime( + now.year, + now.month + months, + now.day, + ), + ); + }, + ), + ); + }).toList(), + ), + ), + ], + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + + return DraggableScrollableSheet( + initialChildSize: 0.75, + minChildSize: 0.5, + maxChildSize: 0.95, + expand: false, + builder: (_, scrollController) { + return BlocBuilder< + OperationDetailsFormCubit, + OperationDetailsFormState + >( + builder: (context, formState) { + final detail = formState.operationDetail; + final currentType = detail.type ?? 'AL'; + + return Padding( + padding: EdgeInsets.only( + bottom: MediaQuery.of(context).viewInsets.bottom, + ), + child: Column( + children: [ + // Header Bottom Sheet + Padding( + padding: const EdgeInsets.all(16.0), + child: Row( + mainAxisAlignment: MainAxisAlignment.spaceBetween, + children: [ + Text( + formState.isEditing + ? 'Modifica Dettaglio Servizio' + : 'Nuovo Dettaglio Servizio', + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + IconButton( + icon: const Icon(Icons.close), + onPressed: () => Navigator.pop(context), + ), + ], + ), + ), + const Divider(height: 1), + Expanded( + child: ListView( + controller: scrollController, + padding: const EdgeInsets.all(16.0), + children: [ + // 1. Tipo Servizio (Wrap di Chips) + const Text( + 'Tipo Servizio', + style: TextStyle(fontWeight: FontWeight.bold), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8.0, + runSpacing: 8.0, + children: + OperationDetailsSection._availableTypes.map(( + type, + ) { + return ChoiceChip( + label: Text(type), + selected: currentType == type, + onSelected: (selected) { + if (selected) { + final allProviders = + context + .read() + .state + .providers; + final defaultProviderId = + context + .read() + .state + .currentStore + ?.defaultProviderId; + + context + .read() + .setTypeWithSmartDefaults( + newType: type, + allProviders: allProviders, + defaultProviderId: + defaultProviderId, + ); + } + }, + ); + }).toList(), + ), + const SizedBox(height: 16), + + // 2. Seleziona Gestore + ListTile( + title: const Text('Seleziona Gestore'), + subtitle: Text( + (detail.provider != null) + ? detail.provider!.name + : 'Nessun gestore selezionato', + style: TextStyle( + color: + (detail.provider == null || + detail.provider!.name.isEmpty) + ? Colors.grey + : null, + fontWeight: + (detail.provider == null || + detail.provider!.name.isEmpty) + ? FontWeight.normal + : FontWeight.bold, + ), + ), + trailing: const Icon(Icons.arrow_drop_down), + shape: RoundedRectangleBorder( + side: BorderSide(color: theme.dividerColor), + borderRadius: BorderRadius.circular(8), + ), + onTap: () => _showProviderModal(context, currentType), + ), + const SizedBox(height: 16), + + // 3. Scenario Energy (Dropdown Fisso) + if (currentType == 'Energy') ...[ + DropdownButtonFormField( + initialValue: + (detail.subType != null && + detail.subType!.isNotEmpty) + ? detail.subType + : 'Luce', + decoration: const InputDecoration( + labelText: 'Dettaglio Fornitura', + ), + items: + ['Luce', 'Gas'] + .map( + (s) => DropdownMenuItem( + value: s, + child: Text(s), + ), + ) + .toList(), + onChanged: (val) { + if (val != null) { + context + .read() + .updateFields(subType: val); + } + }, + ), + const SizedBox(height: 16), + TextFormField( + controller: _descriptionController, + decoration: const InputDecoration( + labelText: 'Offerta scelta', + ), + onChanged: (val) { + context + .read() + .updateFields(description: val); + }, + ), + const SizedBox(height: 16), + ], + + // 4. Scenario Fin (Ricerca Modello/Prodotto) + if (currentType == 'Fin') ...[ + SharedModelSection( + label: 'Seleziona Dispositivo/Prodotto', + modelId: detail.modelId, + modelName: detail.model?.nameWithBrand, + onModelSelected: (id, name) { + context + .read() + .updateFields(modelId: id); + }, + ), + const SizedBox(height: 16), + ], + + // 5. Scenario Entertainment o Custom (Testo libero) + if (currentType == 'Entertainment' || + currentType == 'Altro') ...[ + TextFormField( + controller: _subtypeController, + decoration: InputDecoration( + labelText: + currentType == 'Entertainment' + ? 'Piattaforma (es. Netflix, DAZN, Spotify...)' + : 'Specifica il servizio (es. Monopattino)', + ), + onChanged: (val) { + context + .read() + .updateFields(subType: val); + }, + ), + const SizedBox(height: 16), + ], + + // 6. Scadenza (Reattiva per tipi complessi) + if ([ + 'Energy', + 'Fin', + 'Entertainment', + 'Altro', + ].contains(currentType)) ...[ + _buildDurationQuickPicks(context), + const SizedBox(height: 16), + ListTile( + title: const Text('Data di Scadenza Effettiva'), + subtitle: Text( + detail.expirationDate != null + ? "${detail.expirationDate!.day}/${detail.expirationDate!.month}/${detail.expirationDate!.year}" + : 'Nessuna scadenza impostata', + style: const TextStyle( + fontWeight: FontWeight.bold, + fontSize: 16, + ), + ), + trailing: const Icon( + Icons.calendar_month, + color: Colors.blue, + ), + tileColor: Colors.blue.withValues(alpha: 0.05), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12), + side: const BorderSide( + color: Colors.blue, + width: 0.5, + ), + ), + onTap: () async { + final date = await showDatePicker( + context: context, + initialDate: + detail.expirationDate ?? + DateTime.now().add( + const Duration(days: 365), + ), + firstDate: DateTime.now(), + lastDate: DateTime.now().add( + const Duration(days: 3650), + ), + ); + if (date != null && context.mounted) { + context + .read() + .updateFields(expirationDate: date); + } + }, + ), + const SizedBox(height: 16), + ], + + // Pulsante di conferma + ElevatedButton( + style: ElevatedButton.styleFrom( + minimumSize: const Size.fromHeight(48), + ), + onPressed: () { + final finalDetail = formState.operationDetail; + + if (formState.isEditing) { + widget.listCubit.updateOperationDetail( + formState.editingIndex!, + finalDetail, + ); + } else { + widget.listCubit.addOperationDetail(finalDetail); + } + + Navigator.pop(context); + }, + child: Text( + formState.isEditing + ? 'Salva Modifiche' + : 'Aggiungi Dettaglio', + ), + ), + ], + ), + ), + ], + ), + ); + }, + ); + }, + ); + } +} diff --git a/lib/main.dart b/lib/main.dart index 92e3c2c..9e3a9d6 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -36,12 +36,12 @@ import 'package:url_launcher/url_launcher.dart'; String? initialRecoveryFragment; void main() async { WidgetsFlutterBinding.ensureInitialized(); + await dotenv.load(fileName: ".env"); await init(); final initialUri = Uri.base; if (initialUri.fragment.contains('access_token=')) { initialRecoveryFragment = initialUri.fragment; } - await dotenv.load(fileName: ".env"); // RIMUOVE IL CARATTERE # DAGLI URL WEB! usePathUrlStrategy(); // Lo Scudo Ninja: Inizializziamo Firebase SOLO sulle piattaforme supportate diff --git a/macos/Podfile b/macos/Podfile index ff5ddb3..73a6b1e 100644 --- a/macos/Podfile +++ b/macos/Podfile @@ -38,5 +38,8 @@ end post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_macos_build_settings(target) + target.build_configurations.each do |config| + config.build_settings['MACOSX_DEPLOYMENT_TARGET'] = '10.15' + end end end diff --git a/macos/Podfile.lock b/macos/Podfile.lock index 67cab97..4ddcfb3 100644 --- a/macos/Podfile.lock +++ b/macos/Podfile.lock @@ -5,33 +5,33 @@ PODS: - FlutterMacOS - file_selector_macos (0.0.1): - FlutterMacOS - - Firebase/CoreOnly (12.13.0): - - FirebaseCore (~> 12.13.0) - - Firebase/Messaging (12.13.0): + - Firebase/CoreOnly (12.15.0): + - FirebaseCore (~> 12.15.0) + - Firebase/Messaging (12.15.0): - Firebase/CoreOnly - - FirebaseMessaging (~> 12.13.0) - - firebase_core (4.9.0): - - Firebase/CoreOnly (~> 12.13.0) + - FirebaseMessaging (~> 12.15.0) + - firebase_core (4.11.0): + - Firebase/CoreOnly (~> 12.15.0) - FlutterMacOS - - firebase_messaging (16.2.2): - - Firebase/CoreOnly (~> 12.13.0) - - Firebase/Messaging (~> 12.13.0) + - firebase_messaging (16.4.1): + - Firebase/CoreOnly (~> 12.15.0) + - Firebase/Messaging (~> 12.15.0) - firebase_core - FlutterMacOS - - FirebaseCore (12.13.0): - - FirebaseCoreInternal (~> 12.13.0) + - FirebaseCore (12.15.0): + - FirebaseCoreInternal (~> 12.15.0) - GoogleUtilities/Environment (~> 8.1) - GoogleUtilities/Logger (~> 8.1) - - FirebaseCoreInternal (12.13.0): + - FirebaseCoreInternal (12.15.0): - "GoogleUtilities/NSData+zlib (~> 8.1)" - - FirebaseInstallations (12.13.0): - - FirebaseCore (~> 12.13.0) + - FirebaseInstallations (12.15.0): + - FirebaseCore (~> 12.15.0) - GoogleUtilities/Environment (~> 8.1) - GoogleUtilities/UserDefaults (~> 8.1) - PromisesObjC (~> 2.4) - - FirebaseMessaging (12.13.0): - - FirebaseCore (~> 12.13.0) - - FirebaseInstallations (~> 12.13.0) + - FirebaseMessaging (12.15.0): + - FirebaseCore (~> 12.15.0) + - FirebaseInstallations (~> 12.15.0) - GoogleDataTransport (~> 10.1) - GoogleUtilities/AppDelegateSwizzler (~> 8.1) - GoogleUtilities/Environment (~> 8.1) @@ -39,31 +39,31 @@ PODS: - GoogleUtilities/UserDefaults (~> 8.1) - nanopb (~> 3.30910.0) - FlutterMacOS (1.0.0) - - GoogleDataTransport (10.1.0): + - GoogleDataTransport (10.1.1): - nanopb (~> 3.30910.0) - PromisesObjC (~> 2.4) - - GoogleUtilities/AppDelegateSwizzler (8.1.0): + - GoogleUtilities/AppDelegateSwizzler (8.1.2): - GoogleUtilities/Environment - GoogleUtilities/Logger - GoogleUtilities/Network - GoogleUtilities/Privacy - - GoogleUtilities/Environment (8.1.0): + - GoogleUtilities/Environment (8.1.2): - GoogleUtilities/Privacy - - GoogleUtilities/Logger (8.1.0): + - GoogleUtilities/Logger (8.1.2): - GoogleUtilities/Environment - GoogleUtilities/Privacy - - GoogleUtilities/Network (8.1.0): + - GoogleUtilities/Network (8.1.2): - GoogleUtilities/Logger - "GoogleUtilities/NSData+zlib" - GoogleUtilities/Privacy - GoogleUtilities/Reachability - - "GoogleUtilities/NSData+zlib (8.1.0)": + - "GoogleUtilities/NSData+zlib (8.1.2)": - GoogleUtilities/Privacy - - GoogleUtilities/Privacy (8.1.0) - - GoogleUtilities/Reachability (8.1.0): + - GoogleUtilities/Privacy (8.1.2) + - GoogleUtilities/Reachability (8.1.2): - GoogleUtilities/Logger - GoogleUtilities/Privacy - - GoogleUtilities/UserDefaults (8.1.0): + - GoogleUtilities/UserDefaults (8.1.2): - GoogleUtilities/Logger - GoogleUtilities/Privacy - nanopb (3.30910.0): @@ -77,7 +77,7 @@ PODS: - FlutterMacOS - printing (1.0.0): - FlutterMacOS - - PromisesObjC (2.4.0) + - PromisesObjC (2.4.1) - shared_preferences_foundation (0.0.1): - Flutter - FlutterMacOS @@ -137,24 +137,24 @@ SPEC CHECKSUMS: app_links: 05a6ec2341985eb05e9f97dc63f5837c39895c3f file_picker: 7584aae6fa07a041af2b36a2655122d42f578c1a file_selector_macos: 9e9e068e90ebee155097d00e89ae91edb2374db7 - Firebase: 7d62445aeabdaea36f7d372f33052fed9a72514f - firebase_core: 8a780c7f989df0ca42dcd55332fc1b203f11f848 - firebase_messaging: 3cb926039fe036f6b92834334d6e23ab33007f1f - FirebaseCore: 58905958aa00a061397a0fd759ae4b55bddb3576 - FirebaseCoreInternal: 37bee58388fc6d183f0ab1b32d69ae44f2cf8aad - FirebaseInstallations: 134bde50e477628ded76070efdb12d515d53f948 - FirebaseMessaging: 30564b85d2f81a96f9d312bd23acf8186ff092ae + Firebase: a8539b633d474fbeb654c7043f9c1649e274045b + firebase_core: 4922bf7ac16c97fb67008a1a00842059b345b0d9 + firebase_messaging: 6c506190a7499e67e644957961f86efe1ac1c3e3 + FirebaseCore: 2e86a4ea1684d4381707069e4a6d89ac808e901e + FirebaseCoreInternal: 6ab6a02c94446c026d2cf35cf5383842ebaa4992 + FirebaseInstallations: eb29ccbf64eaedf86fd5b2ccc7fabde567660b52 + FirebaseMessaging: 40017d7bc8457ee295b0f41d480a80fdabc9994e FlutterMacOS: d0db08ddef1a9af05a5ec4b724367152bb0500b1 - GoogleDataTransport: aae35b7ea0c09004c3797d53c8c41f66f219d6a7 - GoogleUtilities: 00c88b9a86066ef77f0da2fab05f65d7768ed8e1 + GoogleDataTransport: a24e58982ab3ba2f64d79613e027fe7f57e88539 + GoogleUtilities: 766ace00c6b10d8148408f329d10c4f051931850 nanopb: fad817b59e0457d11a5dfbde799381cd727c1275 package_info_plus: f0052d280d17aa382b932f399edf32507174e870 pdfx: 1e79f57f7a6ce2f4a4c30f21fa54d3dc82441b51 - printing: c4cf83c78fd684f9bc318e6aadc18972aa48f617 - PromisesObjC: f5707f49cb48b9636751c5b2e7d227e43fba9f47 + printing: 7916ffaaede65713863e621de9a4742d9fa723b9 + PromisesObjC: 752c3227f599e3467650e47ea36f433eeb10c273 shared_preferences_foundation: 7036424c3d8ec98dfe75ff1667cb0cd531ec82bb url_launcher_macos: f87a979182d112f911de6820aefddaf56ee9fbfd -PODFILE CHECKSUM: 54d867c82ac51cbd61b565781b9fada492027009 +PODFILE CHECKSUM: 180da7a1dbc1d932db021ebc8007656e7c46dd99 -COCOAPODS: 1.16.2 +COCOAPODS: 1.17.0