From 6d2c563ce2192628ff4fb9116747d3f2035cd0a9 Mon Sep 17 00:00:00 2001 From: Mark M2 Macbook Date: Wed, 2 Dec 2026 18:26:45 +0100 Subject: [PATCH] feat: add customer orders feature with management, forms, and PDF export --- lib/core/enums_and_consts/consts.dart | 1 + .../enums_and_consts/contact_preference.dart | 106 ++ lib/core/layout/app_shell.dart | 5 + lib/core/routes/app_router.dart | 62 + lib/core/routes/routes.dart | 2 + .../contact_preference_section.dart | 141 ++ .../shared_forms/customer_section.dart | 74 +- .../attachments/blocs/attachments_bloc.dart | 8 + .../attachments/blocs/attachments_state.dart | 3 +- .../data/attachments_repository.dart | 4 + .../attachments/models/attachment_model.dart | 7 + .../blocs/customer_order_form_cubit.dart | 320 +++++ .../blocs/customer_order_form_state.dart | 52 + .../blocs/customer_order_list_cubit.dart | 159 +++ .../blocs/customer_order_list_state.dart | 75 + .../data/customer_orders_repository.dart | 198 +++ .../models/customer_order_model.dart | 254 ++++ .../models/customer_order_status.dart | 99 ++ .../ui/customer_order_form_screen.dart | 1260 +++++++++++++++++ .../ui/customer_order_list_screen.dart | 770 ++++++++++ .../customer_order_label_pdf_service.dart | 116 ++ .../customers/blocs/customer_form_cubit.dart | 8 +- .../customers/models/customer_model.dart | 22 +- .../customers/ui/customer_form_screen.dart | 15 +- .../customers/ui/quick_customer_dialog.dart | 17 +- lib/features/home/ui/home_screen.dart | 16 + .../tickets/blocs/ticket_form_cubit.dart | 31 +- lib/features/tickets/models/ticket_model.dart | 10 + .../tickets/ui/ticket_form_screen.dart | 26 +- lib/service_locator.dart | 6 + pubspec.yaml | 2 +- .../migrations/20261202_customer_orders.sql | 92 ++ .../models/customer_order_model_test.dart | 142 ++ 33 files changed, 4081 insertions(+), 22 deletions(-) create mode 100644 lib/core/enums_and_consts/contact_preference.dart create mode 100644 lib/core/widgets/shared_forms/contact_preference_section.dart create mode 100644 lib/features/customer_orders/blocs/customer_order_form_cubit.dart create mode 100644 lib/features/customer_orders/blocs/customer_order_form_state.dart create mode 100644 lib/features/customer_orders/blocs/customer_order_list_cubit.dart create mode 100644 lib/features/customer_orders/blocs/customer_order_list_state.dart create mode 100644 lib/features/customer_orders/data/customer_orders_repository.dart create mode 100644 lib/features/customer_orders/models/customer_order_model.dart create mode 100644 lib/features/customer_orders/models/customer_order_status.dart create mode 100644 lib/features/customer_orders/ui/customer_order_form_screen.dart create mode 100644 lib/features/customer_orders/ui/customer_order_list_screen.dart create mode 100644 lib/features/customer_orders/utils/customer_order_label_pdf_service.dart create mode 100644 supabase/migrations/20261202_customer_orders.sql create mode 100644 test/features/customer_orders/models/customer_order_model_test.dart diff --git a/lib/core/enums_and_consts/consts.dart b/lib/core/enums_and_consts/consts.dart index 93658c1..6937c1a 100644 --- a/lib/core/enums_and_consts/consts.dart +++ b/lib/core/enums_and_consts/consts.dart @@ -5,6 +5,7 @@ class Tables { static const String campaigns = 'campaigns'; static const String companies = 'companies'; static const String customers = 'customers'; + static const String customerOrders = 'customer_orders'; static const String documentSequences = 'document_sequences'; static const String models = 'models'; static const String notes = 'notes'; diff --git a/lib/core/enums_and_consts/contact_preference.dart b/lib/core/enums_and_consts/contact_preference.dart new file mode 100644 index 0000000..7f14dd0 --- /dev/null +++ b/lib/core/enums_and_consts/contact_preference.dart @@ -0,0 +1,106 @@ +import 'package:flutter/material.dart'; +import 'package:font_awesome_flutter/font_awesome_flutter.dart'; + +/// Modalità di avviso preferita del cliente (condivisa tra Ordini Clienti e Ticket Assistenza) +enum ContactPreference { + whatsappPrimary( + value: 'whatsapp_primary', + label: 'WhatsApp (Principale)', + shortLabel: 'WA Principale', + materialIcon: Icons.chat_bubble_outline_rounded, + color: Colors.green, + usesAlternativePhone: false, + isWhatsapp: true, + isCall: false, + isEmail: false, + ), + whatsappAlternative( + value: 'whatsapp_alternative', + label: 'WhatsApp (Recapito Alternativo)', + shortLabel: 'WA Alternativo', + materialIcon: Icons.chat_bubble_outline_rounded, + color: Colors.teal, + usesAlternativePhone: true, + isWhatsapp: true, + isCall: false, + isEmail: false, + ), + callPrimary( + value: 'call_primary', + label: 'Telefonata (Principale)', + shortLabel: 'Tel. Principale', + materialIcon: Icons.phone_outlined, + color: Colors.blue, + usesAlternativePhone: false, + isWhatsapp: false, + isCall: true, + isEmail: false, + ), + callAlternative( + value: 'call_alternative', + label: 'Telefonata (Recapito Alternativo)', + shortLabel: 'Tel. Alternativo', + materialIcon: Icons.phone_forwarded_outlined, + color: Colors.indigo, + usesAlternativePhone: true, + isWhatsapp: false, + isCall: true, + isEmail: false, + ), + email( + value: 'email', + label: 'Email', + shortLabel: 'Email', + materialIcon: Icons.alternate_email_rounded, + color: Colors.deepOrange, + usesAlternativePhone: false, + isWhatsapp: false, + isCall: false, + isEmail: true, + ); + + final String value; + final String label; + final String shortLabel; + final IconData materialIcon; + final Color color; + final bool usesAlternativePhone; + final bool isWhatsapp; + final bool isCall; + final bool isEmail; + + const ContactPreference({ + required this.value, + required this.label, + required this.shortLabel, + required this.materialIcon, + required this.color, + required this.usesAlternativePhone, + required this.isWhatsapp, + required this.isCall, + required this.isEmail, + }); + + Widget buildIcon({double size = 16, Color? overrideColor}) { + final c = overrideColor ?? color; + if (isWhatsapp) { + return FaIcon(FontAwesomeIcons.whatsapp, size: size, color: c); + } + return Icon(materialIcon, size: size, color: c); + } + + static ContactPreference fromString( + String? val, { + ContactPreference fallback = ContactPreference.whatsappPrimary, + }) { + if (val == null || val.trim().isEmpty) return fallback; + final clean = val.trim().toLowerCase(); + for (final item in ContactPreference.values) { + if (item.value.toLowerCase() == clean || + item.name.toLowerCase() == clean) { + return item; + } + } + return fallback; + } +} diff --git a/lib/core/layout/app_shell.dart b/lib/core/layout/app_shell.dart index a5c5000..581c694 100644 --- a/lib/core/layout/app_shell.dart +++ b/lib/core/layout/app_shell.dart @@ -143,6 +143,11 @@ class _AppMenuState extends State { Routes.tickets, '/tickets', ), + _SubMenuItem( + 'Ordini Clienti', + Routes.customerOrders, + '/orders', + ), _SubMenuItem('Tasks', Routes.tasks, '/tasks'), _SubMenuItem('Sticky Notes', Routes.notes, '/notes'), ], diff --git a/lib/core/routes/app_router.dart b/lib/core/routes/app_router.dart index 62c0570..17db4e4 100644 --- a/lib/core/routes/app_router.dart +++ b/lib/core/routes/app_router.dart @@ -12,6 +12,11 @@ import 'package:flux/features/auth/ui/auth_screen.dart'; import 'package:flux/features/auth/ui/set_password_screen.dart'; import 'package:flux/features/company/bloc/company_settings_cubit.dart'; import 'package:flux/features/company/ui/company_settings_screen.dart'; +import 'package:flux/features/customer_orders/blocs/customer_order_form_cubit.dart'; +import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/ui/customer_order_form_screen.dart'; +import 'package:flux/features/customer_orders/ui/customer_order_list_screen.dart'; import 'package:flux/features/customers/blocs/customer_form_cubit.dart'; import 'package:flux/features/customers/blocs/customers_list_cubit.dart'; import 'package:flux/features/customers/models/customer_model.dart'; @@ -120,6 +125,9 @@ class AppRouter { if (sessionState.status == SessionStatus.unauthenticated) { // Se sta già andando alle uniche altre pagine pubbliche, lascialo andare if (isGoingToLogin || isGoingToSetPassword) return null; + if (path != '/' && path.isNotEmpty) { + pendingRoute = state.uri.toString(); + } // Altrimenti bloccalo e mandalo al login return '/login'; } @@ -334,6 +342,14 @@ class AppRouter { name: Routes.tickets, builder: (context, state) => const TicketListScreen(), ), + GoRoute( + path: '/orders', + name: Routes.customerOrders, + builder: (context, state) => BlocProvider( + create: (_) => sl(), + child: const CustomerOrderListScreen(), + ), + ), GoRoute( path: '/notes', name: Routes.notes, @@ -618,6 +634,52 @@ class AppRouter { }, ), + GoRoute( + path: '/orders/form/:id', + name: Routes.customerOrderForm, + builder: (context, state) { + final String pathId = state.pathParameters['id'] ?? 'new'; + final record = + state.extra + as ({ + StaffMemberModel? createdBy, + CustomerOrderModel? order, + })?; + + final String? realOrderId; + if (pathId == 'new') { + realOrderId = null; + } else if (record?.order?.id != null) { + realOrderId = record!.order!.id; + } else { + realOrderId = pathId; + } + + context.read().loadCustomers(); + + return MultiBlocProvider( + providers: [ + BlocProvider( + create: (_) => AttachmentsBloc( + parentId: realOrderId, + parentType: AttachmentParentType.customerOrder, + ), + ), + BlocProvider( + create: (_) => CustomerOrderFormCubit( + createdBy: record?.createdBy, + existingOrder: record?.order, + ), + ), + ], + child: CustomerOrderFormScreen( + orderId: realOrderId, + order: record?.order, + ), + ); + }, + ), + GoRoute( path: '/upload/:type/:id', name: Routes.upload, diff --git a/lib/core/routes/routes.dart b/lib/core/routes/routes.dart index 5e7717f..b9bcf7b 100644 --- a/lib/core/routes/routes.dart +++ b/lib/core/routes/routes.dart @@ -31,4 +31,6 @@ class Routes { static const String targetForm = 'target-form'; static const String targetDetail = 'target-detail'; static const String financing = 'financing'; + static const String customerOrders = 'customer-orders'; + static const String customerOrderForm = 'customer-order-form'; } diff --git a/lib/core/widgets/shared_forms/contact_preference_section.dart b/lib/core/widgets/shared_forms/contact_preference_section.dart new file mode 100644 index 0000000..604c41c --- /dev/null +++ b/lib/core/widgets/shared_forms/contact_preference_section.dart @@ -0,0 +1,141 @@ +import 'package:flutter/material.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; +import 'package:flux/features/customers/models/customer_model.dart'; + +class ContactPreferenceSection extends StatelessWidget { + final ContactPreference selectedPreference; + final ValueChanged onPreferenceChanged; + final CustomerModel? customer; + final TextEditingController? alternativePhoneController; + final bool alwaysShowAlternativePhone; + + const ContactPreferenceSection({ + super.key, + required this.selectedPreference, + required this.onPreferenceChanged, + this.customer, + this.alternativePhoneController, + this.alwaysShowAlternativePhone = false, + }); + + String _resolveTargetDestination() { + final altText = + alternativePhoneController?.text.trim().isNotEmpty == true + ? alternativePhoneController!.text.trim() + : (customer?.alternativePhoneNumber.trim() ?? ''); + + if (selectedPreference.isEmail) { + return customer?.email.trim() ?? ''; + } + if (selectedPreference.usesAlternativePhone) { + return altText; + } + return customer?.phoneNumber.trim() ?? ''; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final showAltField = + alwaysShowAlternativePhone || selectedPreference.usesAlternativePhone; + final destination = _resolveTargetDestination(); + + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Modalità di Avviso Cliente', + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: ContactPreference.values.map((pref) { + final isSelected = pref == selectedPreference; + return ChoiceChip( + selected: isSelected, + showCheckmark: false, + avatar: pref.buildIcon( + size: 15, + overrideColor: isSelected ? pref.color : Colors.grey.shade600, + ), + label: Text( + pref.shortLabel, + style: TextStyle( + fontSize: 12.5, + fontWeight: isSelected ? FontWeight.bold : FontWeight.w500, + color: isSelected ? pref.color : null, + ), + ), + selectedColor: pref.color.withValues(alpha: 0.15), + side: BorderSide( + color: isSelected + ? pref.color.withValues(alpha: 0.6) + : theme.dividerColor.withValues(alpha: 0.35), + ), + onSelected: (_) => onPreferenceChanged(pref), + ); + }).toList(), + ), + if (customer != null) ...[ + const SizedBox(height: 8), + Row( + children: [ + Icon( + destination.isNotEmpty + ? Icons.check_circle_outline_rounded + : Icons.warning_amber_rounded, + size: 15, + color: destination.isNotEmpty ? Colors.green : Colors.orange, + ), + const SizedBox(width: 6), + Expanded( + child: Text( + destination.isNotEmpty + ? 'Verrà avvisato su: $destination (${selectedPreference.label})' + : 'Attenzione: nessun recapito impostato per "${selectedPreference.label}"', + style: TextStyle( + fontSize: 12, + color: destination.isNotEmpty + ? theme.colorScheme.onSurfaceVariant + : Colors.orange.shade800, + fontWeight: destination.isNotEmpty + ? FontWeight.normal + : FontWeight.w600, + ), + ), + ), + ], + ), + ], + if (showAltField && alternativePhoneController != null) ...[ + const SizedBox(height: 12), + TextFormField( + controller: alternativePhoneController, + keyboardType: TextInputType.phone, + decoration: InputDecoration( + labelText: selectedPreference.usesAlternativePhone + ? 'Recapito Alternativo *' + : 'Recapito Alternativo (opzionale)', + hintText: 'Es. telefono coniuge / ufficio...', + prefixIcon: const Icon(Icons.phone_forwarded_outlined), + helperText: customer != null + ? 'Se compilato, verrà salvato anche sull\'anagrafica del cliente' + : null, + ), + validator: (val) { + if (selectedPreference.usesAlternativePhone && + (val == null || val.trim().isEmpty)) { + return 'Inserisci il recapito alternativo per avvisare il cliente'; + } + return null; + }, + ), + ], + ], + ); + } +} diff --git a/lib/core/widgets/shared_forms/customer_section.dart b/lib/core/widgets/shared_forms/customer_section.dart index 05d199f..704879e 100644 --- a/lib/core/widgets/shared_forms/customer_section.dart +++ b/lib/core/widgets/shared_forms/customer_section.dart @@ -85,6 +85,7 @@ class SharedCustomerSection extends StatelessWidget { ), if (hasCustomer && (customer!.phoneNumber.isNotEmpty || + customer!.alternativePhoneNumber.isNotEmpty || customer!.email.isNotEmpty)) ...[ const SizedBox(height: 12), // Un po' più di respiro dal box sopra // Mettiamo i contatti in un Container con un po' di stile per farli sembrare una "Contact Card" integrata @@ -148,8 +149,79 @@ class SharedCustomerSection extends StatelessWidget { ], ), - // Sezione divisoria se ci sono entrambi + // --- RIGA RECAPITO ALTERNATIVO --- if (customer!.phoneNumber.isNotEmpty && + customer!.alternativePhoneNumber.isNotEmpty) + const Divider(height: 8, thickness: 0.5), + + if (customer!.alternativePhoneNumber.isNotEmpty) + Row( + children: [ + IconButton( + visualDensity: VisualDensity.compact, + onPressed: () => launchUrl( + Uri.parse( + 'https://wa.me/39${customer!.alternativePhoneNumber}', + ), + ), + icon: const FaIcon( + FontAwesomeIcons.whatsapp, + color: Colors.teal, + size: 20, + ), + tooltip: 'WhatsApp su recapito alternativo', + ), + const SizedBox(width: 8), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + SelectableText( + customer!.alternativePhoneNumber, + style: const TextStyle( + fontSize: 14, + fontWeight: FontWeight.w500, + ), + ), + Text( + 'Recapito alternativo', + style: TextStyle( + fontSize: 10.5, + color: Colors.grey.shade600, + ), + ), + ], + ), + ), + IconButton( + visualDensity: VisualDensity.compact, + onPressed: () { + Clipboard.setData( + ClipboardData( + text: customer!.alternativePhoneNumber, + ), + ); + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Recapito alternativo copiato!'), + duration: Duration(seconds: 2), + ), + ); + }, + icon: const Icon( + Icons.copy, + size: 18, + color: Colors.grey, + ), + tooltip: 'Copia', + ), + ], + ), + + // Sezione divisoria se c'è email dopo un telefono + if ((customer!.phoneNumber.isNotEmpty || + customer!.alternativePhoneNumber.isNotEmpty) && customer!.email.isNotEmpty) const Divider(height: 8, thickness: 0.5), diff --git a/lib/features/attachments/blocs/attachments_bloc.dart b/lib/features/attachments/blocs/attachments_bloc.dart index d1abe38..a0df8f4 100644 --- a/lib/features/attachments/blocs/attachments_bloc.dart +++ b/lib/features/attachments/blocs/attachments_bloc.dart @@ -225,6 +225,10 @@ class AttachmentsBloc extends Bloc { state.parentType == AttachmentParentType.ticket ? '' : null, customerId: state.parentType == AttachmentParentType.customer ? '' : null, + customerOrderId: + state.parentType == AttachmentParentType.customerOrder + ? '' + : null, name: file.name.fileNameWithoutExtension(), extension: file.name.fileExtension(), storagePath: '', @@ -433,6 +437,8 @@ class AttachmentsBloc extends Bloc { return file.copyWith(shippingDocumentId: event.targetId); case AttachmentParentType.note: return file.copyWith(noteId: event.targetId); + case AttachmentParentType.customerOrder: + return file.copyWith(customerOrderId: event.targetId); } } return file; @@ -609,6 +615,8 @@ class AttachmentsBloc extends Bloc { return Bucket.companyDocuments; case AttachmentParentType.note: return Bucket.documents; + case AttachmentParentType.customerOrder: + return Bucket.documents; } } } diff --git a/lib/features/attachments/blocs/attachments_state.dart b/lib/features/attachments/blocs/attachments_state.dart index 16e9474..d6fb77d 100644 --- a/lib/features/attachments/blocs/attachments_state.dart +++ b/lib/features/attachments/blocs/attachments_state.dart @@ -7,7 +7,8 @@ enum AttachmentParentType { ticket('ticket_id'), customer('customer_id'), shippingDocument('shipping_document_id'), - note('note_id'); + note('note_id'), + customerOrder('customer_order_id'); final String dbColumn; const AttachmentParentType(this.dbColumn); diff --git a/lib/features/attachments/data/attachments_repository.dart b/lib/features/attachments/data/attachments_repository.dart index 751b7d0..2884f48 100644 --- a/lib/features/attachments/data/attachments_repository.dart +++ b/lib/features/attachments/data/attachments_repository.dart @@ -46,6 +46,8 @@ class AttachmentsRepository { return 'shipping_document_id'; case AttachmentParentType.note: return 'note_id'; + case AttachmentParentType.customerOrder: + return 'customer_order_id'; } } @@ -200,6 +202,8 @@ class AttachmentsRepository { AttachmentParentType.ticket: file.ticketId, AttachmentParentType.customer: file.customerId, AttachmentParentType.shippingDocument: file.shippingDocumentId, + AttachmentParentType.note: file.noteId, + AttachmentParentType.customerOrder: file.customerOrderId, }; // 2. Simuliamo la rimozione del collegamento per il contesto attuale diff --git a/lib/features/attachments/models/attachment_model.dart b/lib/features/attachments/models/attachment_model.dart index 1ce6055..b551161 100644 --- a/lib/features/attachments/models/attachment_model.dart +++ b/lib/features/attachments/models/attachment_model.dart @@ -26,6 +26,7 @@ class AttachmentModel extends Equatable { final String? ticketId; final String? shippingDocumentId; final String? noteId; + final String? customerOrderId; final String name; final String extension; final String? storagePath; @@ -44,6 +45,7 @@ class AttachmentModel extends Equatable { this.ticketId, this.shippingDocumentId, this.noteId, + this.customerOrderId, required this.name, required this.extension, this.storagePath, @@ -71,6 +73,7 @@ class AttachmentModel extends Equatable { ticketId, shippingDocumentId, noteId, + customerOrderId, name, extension, storagePath, @@ -122,6 +125,7 @@ class AttachmentModel extends Equatable { String? ticketId, String? shippingDocumentId, String? noteId, + String? customerOrderId, String? name, String? extension, String? storagePath, @@ -139,6 +143,7 @@ class AttachmentModel extends Equatable { ticketId: ticketId ?? this.ticketId, shippingDocumentId: shippingDocumentId ?? this.shippingDocumentId, noteId: noteId ?? this.noteId, + customerOrderId: customerOrderId ?? this.customerOrderId, name: name ?? this.name, extension: extension ?? this.extension, storagePath: storagePath ?? this.storagePath, @@ -161,6 +166,7 @@ class AttachmentModel extends Equatable { ticketId: map['ticket_id'] as String?, shippingDocumentId: map['shipping_document_id'] as String?, noteId: map['note_id'] as String?, + customerOrderId: map['customer_order_id'] as String?, name: map['name'] as String, extension: map['extension'] as String, storagePath: map['storage_path'] as String?, @@ -185,6 +191,7 @@ class AttachmentModel extends Equatable { 'ticket_id': ticketId, 'shipping_document_id': shippingDocumentId, 'note_id': noteId, + 'customer_order_id': customerOrderId, 'file_size': fileSize, 'company_id': companyId, 'thumbnail_path': thumbnailPath, diff --git a/lib/features/customer_orders/blocs/customer_order_form_cubit.dart b/lib/features/customer_orders/blocs/customer_order_form_cubit.dart new file mode 100644 index 0000000..82d063e --- /dev/null +++ b/lib/features/customer_orders/blocs/customer_order_form_cubit.dart @@ -0,0 +1,320 @@ +import 'package:equatable/equatable.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; +import 'package:flux/features/customer_orders/data/customer_orders_repository.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/features/customers/data/customer_repository.dart'; +import 'package:flux/features/customers/models/customer_model.dart'; +import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; +import 'package:flux/service_locator.dart'; + +part 'customer_order_form_state.dart'; + +class CustomerOrderFormCubit extends Cubit { + final CustomerOrdersRepository _repository = sl(); + final CustomerRepository _customerRepository = sl(); + final SessionCubit _sessionCubit = sl(); + + CustomerOrderFormCubit({ + StaffMemberModel? createdBy, + CustomerOrderModel? existingOrder, + }) : super( + CustomerOrderFormState( + order: + existingOrder ?? + CustomerOrderModel.empty().copyWith( + createdById: createdBy?.id, + createdByName: createdBy?.name, + ), + ), + ); + + Future initForm({ + String? orderId, + CustomerOrderModel? existingOrder, + }) async { + final companyId = _sessionCubit.state.company?.id ?? ''; + + if (existingOrder != null && existingOrder.id != null) { + emit( + state.copyWith( + order: existingOrder, + status: CustomerOrderFormStatus.ready, + ), + ); + _loadAvailableTags(companyId); + // Aggiorniamo anche in background con i dettagli freschi (es. da scansione o relazioni) + final fresh = await _repository.getOrderById(existingOrder.id!); + if (fresh != null && !isClosed) { + emit(state.copyWith(order: fresh)); + } + return; + } + + if (orderId != null && orderId.isNotEmpty) { + emit(state.copyWith(status: CustomerOrderFormStatus.loading)); + final fetched = await _repository.getOrderById(orderId); + if (fetched == null) { + emit( + state.copyWith( + status: CustomerOrderFormStatus.failure, + errorMessage: 'Ordine non trovato.', + ), + ); + return; + } + emit( + state.copyWith( + order: fetched, + status: CustomerOrderFormStatus.ready, + ), + ); + _loadAvailableTags(companyId); + return; + } + + // Nuovo ordine + final currentStore = _sessionCubit.state.currentStore; + final currentStaff = _sessionCubit.state.currentStaffMember; + final newOrder = state.order.copyWith( + companyId: companyId, + storeId: currentStore?.id, + storeDisplayName: currentStore?.name, + createdById: state.order.createdById ?? currentStaff?.id, + createdByName: state.order.createdByName ?? currentStaff?.name, + orderDate: DateTime.now(), + status: CustomerOrderStatus.toOrder, + ); + emit( + state.copyWith( + order: newOrder, + status: CustomerOrderFormStatus.ready, + ), + ); + _loadAvailableTags(companyId); + } + + Future _loadAvailableTags(String companyId) async { + if (companyId.isEmpty) return; + final tags = await _repository.fetchDistinctTags(companyId); + if (!isClosed) { + emit(state.copyWith(availableTags: tags)); + } + } + + void updateCustomer(CustomerModel customer) { + final currentAlt = state.order.alternativePhoneNumber?.trim() ?? ''; + final resolvedAlt = currentAlt.isNotEmpty + ? currentAlt + : (customer.alternativePhoneNumber.trim().isNotEmpty + ? customer.alternativePhoneNumber.trim() + : null); + emit( + state.copyWith( + order: state.order.copyWith( + customerId: customer.id, + customer: customer, + alternativePhoneNumber: resolvedAlt, + ), + ), + ); + } + + void updateFields({ + DateTime? orderDate, + String? storeId, + String? storeDisplayName, + String? productDescription, + int? quantity, + String? notes, + double? price, + double? deposit, + String? externalCode, + CustomerOrderStatus? status, + ContactPreference? contactPreference, + String? alternativePhoneNumber, + bool? customerNotified, + }) { + DateTime? notifiedAt = state.order.customerNotifiedAt; + bool clearNotifiedAt = false; + if (customerNotified != null) { + if (customerNotified && !state.order.customerNotified) { + notifiedAt = DateTime.now(); + } else if (!customerNotified) { + clearNotifiedAt = true; + } + } + + emit( + state.copyWith( + order: state.order.copyWith( + orderDate: orderDate ?? state.order.orderDate, + storeId: storeId ?? state.order.storeId, + storeDisplayName: storeDisplayName ?? state.order.storeDisplayName, + productDescription: + productDescription ?? state.order.productDescription, + quantity: quantity ?? state.order.quantity, + notes: notes ?? state.order.notes, + price: price ?? state.order.price, + deposit: deposit ?? state.order.deposit, + externalCode: externalCode ?? state.order.externalCode, + status: status ?? state.order.status, + contactPreference: contactPreference ?? state.order.contactPreference, + alternativePhoneNumber: + alternativePhoneNumber ?? state.order.alternativePhoneNumber, + customerNotified: customerNotified ?? state.order.customerNotified, + customerNotifiedAt: notifiedAt, + clearCustomerNotifiedAt: clearNotifiedAt, + ), + ), + ); + } + + void addTag(String rawTag) { + final clean = rawTag.trim(); + if (clean.isEmpty) return; + final exists = state.order.tags.any( + (t) => t.toLowerCase() == clean.toLowerCase(), + ); + if (exists) return; + + final updatedTags = [...state.order.tags, clean]; + final updatedAvailable = state.availableTags.any( + (t) => t.toLowerCase() == clean.toLowerCase(), + ) + ? state.availableTags + : ([...state.availableTags, clean] + ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase()))); + + emit( + state.copyWith( + order: state.order.copyWith(tags: updatedTags), + availableTags: updatedAvailable, + ), + ); + } + + void removeTag(String tag) { + final updatedTags = state.order.tags.where((t) => t != tag).toList(); + emit(state.copyWith(order: state.order.copyWith(tags: updatedTags))); + } + + /// Salva l'ordine (o crea bozza per allegati / QR) + Future saveOrder({ + CustomerOrderStatus? overrideStatus, + bool silentForAttachment = false, + }) async { + final previousStatus = state.order.status; + final orderToSave = overrideStatus != null + ? state.order.copyWith(status: overrideStatus) + : state.order; + + if (orderToSave.customerId == null || orderToSave.customerId!.isEmpty) { + emit( + state.copyWith( + status: CustomerOrderFormStatus.failure, + errorMessage: 'Seleziona un cliente prima di salvare.', + ), + ); + return null; + } + + if (orderToSave.productDescription.trim().isEmpty) { + emit( + state.copyWith( + status: CustomerOrderFormStatus.failure, + errorMessage: 'Inserisci il prodotto richiesto dal cliente.', + ), + ); + return null; + } + + if (!silentForAttachment) { + emit(state.copyWith(status: CustomerOrderFormStatus.saving)); + } + + try { + final CustomerOrderModel saved; + if (orderToSave.id == null || orderToSave.id!.isEmpty) { + saved = await _repository.insertOrder(orderToSave); + } else { + saved = await _repository.updateOrder(orderToSave); + } + + await _syncCustomerAlternativePhone(orderToSave); + + final transitionedToArrived = + saved.status == CustomerOrderStatus.arrived && + previousStatus != CustomerOrderStatus.arrived; + + emit( + state.copyWith( + status: silentForAttachment + ? CustomerOrderFormStatus.ready + : CustomerOrderFormStatus.saved, + order: saved, + justMarkedArrived: transitionedToArrived, + errorMessage: null, + ), + ); + return saved; + } catch (e) { + emit( + state.copyWith( + status: CustomerOrderFormStatus.failure, + errorMessage: e.toString(), + ), + ); + return null; + } + } + + Future markCustomerNotified(bool notified) async { + final now = DateTime.now(); + final updated = state.order.copyWith( + customerNotified: notified, + customerNotifiedAt: notified ? now : null, + clearCustomerNotifiedAt: !notified, + ); + emit(state.copyWith(order: updated)); + if (updated.id != null && updated.id!.isNotEmpty) { + try { + final saved = await _repository.updateOrder(updated); + if (!isClosed) { + emit(state.copyWith(order: saved)); + } + } catch (_) {} + } + } + + Future deleteOrder() async { + final id = state.order.id; + if (id == null || id.isEmpty) return; + emit(state.copyWith(status: CustomerOrderFormStatus.saving)); + try { + await _repository.deleteOrder(id); + emit(state.copyWith(status: CustomerOrderFormStatus.deleted)); + } catch (e) { + emit( + state.copyWith( + status: CustomerOrderFormStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + + Future _syncCustomerAlternativePhone(CustomerOrderModel order) async { + final customer = order.customer; + final newAlt = order.alternativePhoneNumber?.trim() ?? ''; + if (customer == null || customer.id == null || newAlt.isEmpty) return; + if (customer.alternativePhoneNumber.trim() == newAlt) return; + try { + await _customerRepository.updateCustomer( + customer.copyWith(alternativePhoneNumber: newAlt), + ); + } catch (_) {} + } +} diff --git a/lib/features/customer_orders/blocs/customer_order_form_state.dart b/lib/features/customer_orders/blocs/customer_order_form_state.dart new file mode 100644 index 0000000..f16ac8d --- /dev/null +++ b/lib/features/customer_orders/blocs/customer_order_form_state.dart @@ -0,0 +1,52 @@ +part of 'customer_order_form_cubit.dart'; + +enum CustomerOrderFormStatus { + initial, + loading, + ready, + saving, + saved, + deleted, + failure, +} + +class CustomerOrderFormState extends Equatable { + final CustomerOrderFormStatus status; + final CustomerOrderModel order; + final List availableTags; + final String? errorMessage; + final bool justMarkedArrived; + + const CustomerOrderFormState({ + this.status = CustomerOrderFormStatus.initial, + required this.order, + this.availableTags = const [], + this.errorMessage, + this.justMarkedArrived = false, + }); + + CustomerOrderFormState copyWith({ + CustomerOrderFormStatus? status, + CustomerOrderModel? order, + List? availableTags, + String? errorMessage, + bool? justMarkedArrived, + }) { + return CustomerOrderFormState( + status: status ?? this.status, + order: order ?? this.order, + availableTags: availableTags ?? this.availableTags, + errorMessage: errorMessage, + justMarkedArrived: justMarkedArrived ?? false, + ); + } + + @override + List get props => [ + status, + order, + availableTags, + errorMessage, + justMarkedArrived, + ]; +} diff --git a/lib/features/customer_orders/blocs/customer_order_list_cubit.dart b/lib/features/customer_orders/blocs/customer_order_list_cubit.dart new file mode 100644 index 0000000..0397032 --- /dev/null +++ b/lib/features/customer_orders/blocs/customer_order_list_cubit.dart @@ -0,0 +1,159 @@ +import 'dart:async'; +import 'package:equatable/equatable.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/features/customer_orders/data/customer_orders_repository.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/service_locator.dart'; + +part 'customer_order_list_state.dart'; + +class CustomerOrderListCubit extends Cubit { + final CustomerOrdersRepository _repository = sl(); + final SessionCubit _sessionCubit = sl(); + StreamSubscription? _ordersSubscription; + Timer? _searchDebounce; + + CustomerOrderListCubit() : super(const CustomerOrderListState()) { + _ordersSubscription = _repository.onOrdersChanged.listen((_) { + loadOrders(silent: true); + loadTags(); + }); + } + + Future init() async { + await Future.wait([loadOrders(), loadTags()]); + } + + Future loadTags() async { + final companyId = _sessionCubit.state.company?.id; + if (companyId == null || companyId.isEmpty) return; + final tags = await _repository.fetchDistinctTags(companyId); + if (!isClosed) { + emit(state.copyWith(availableTags: tags)); + } + } + + Future loadOrders({bool silent = false}) async { + final companyId = _sessionCubit.state.company?.id; + if (companyId == null || companyId.isEmpty) return; + + if (!silent) { + emit(state.copyWith(status: CustomerOrderListStatus.loading)); + } + + try { + final orders = await _repository.fetchOrders( + companyId: companyId, + quickFilter: state.quickFilter, + storeId: state.storeIdFilter, + searchTerm: state.searchTerm, + dateRange: state.dateRange, + selectedTags: state.selectedTags, + ); + if (!isClosed) { + emit( + state.copyWith( + status: CustomerOrderListStatus.success, + orders: orders, + errorMessage: null, + ), + ); + } + } catch (e) { + if (!isClosed) { + emit( + state.copyWith( + status: CustomerOrderListStatus.failure, + errorMessage: e.toString(), + ), + ); + } + } + } + + void setQuickFilter(CustomerOrderQuickFilter filter) { + if (state.quickFilter == filter) return; + emit(state.copyWith(quickFilter: filter)); + loadOrders(); + } + + void setSearchTerm(String query) { + _searchDebounce?.cancel(); + emit( + state.copyWith( + searchTerm: query, + clearSearchTerm: query.trim().isEmpty, + ), + ); + _searchDebounce = Timer(const Duration(milliseconds: 350), () { + loadOrders(); + }); + } + + void setStoreFilter(String? storeId) { + emit( + state.copyWith( + storeIdFilter: storeId, + clearStoreFilter: storeId == null || storeId.isEmpty, + ), + ); + loadOrders(); + } + + void setDateRange(DateTimeRange? range) { + emit( + state.copyWith( + dateRange: range, + clearDateRange: range == null, + ), + ); + loadOrders(); + } + + void toggleTagFilter(String tag) { + final updated = List.from(state.selectedTags); + if (updated.contains(tag)) { + updated.remove(tag); + } else { + updated.add(tag); + } + emit(state.copyWith(selectedTags: updated)); + loadOrders(); + } + + void resetFilters() { + emit( + state.copyWith( + quickFilter: CustomerOrderQuickFilter.active, + clearStoreFilter: true, + clearSearchTerm: true, + clearDateRange: true, + selectedTags: const [], + ), + ); + loadOrders(); + } + + Future quickUpdateStatus( + CustomerOrderModel order, + CustomerOrderStatus newStatus, + ) async { + try { + await _repository.updateOrder(order.copyWith(status: newStatus)); + } catch (e) { + if (!isClosed) { + emit(state.copyWith(errorMessage: e.toString())); + } + } + } + + @override + Future close() { + _ordersSubscription?.cancel(); + _searchDebounce?.cancel(); + return super.close(); + } +} diff --git a/lib/features/customer_orders/blocs/customer_order_list_state.dart b/lib/features/customer_orders/blocs/customer_order_list_state.dart new file mode 100644 index 0000000..48cf2e9 --- /dev/null +++ b/lib/features/customer_orders/blocs/customer_order_list_state.dart @@ -0,0 +1,75 @@ +part of 'customer_order_list_cubit.dart'; + +enum CustomerOrderListStatus { initial, loading, success, failure } + +class CustomerOrderListState extends Equatable { + final CustomerOrderListStatus status; + final List orders; + final List availableTags; + final CustomerOrderQuickFilter quickFilter; + final String? storeIdFilter; + final String? searchTerm; + final DateTimeRange? dateRange; + final List selectedTags; + final String? errorMessage; + + const CustomerOrderListState({ + this.status = CustomerOrderListStatus.initial, + this.orders = const [], + this.availableTags = const [], + this.quickFilter = CustomerOrderQuickFilter.active, + this.storeIdFilter, + this.searchTerm, + this.dateRange, + this.selectedTags = const [], + this.errorMessage, + }); + + bool get hasAdvancedFilters => + (storeIdFilter != null && storeIdFilter!.isNotEmpty) || + (searchTerm != null && searchTerm!.trim().isNotEmpty) || + dateRange != null || + selectedTags.isNotEmpty; + + CustomerOrderListState copyWith({ + CustomerOrderListStatus? status, + List? orders, + List? availableTags, + CustomerOrderQuickFilter? quickFilter, + String? storeIdFilter, + bool clearStoreFilter = false, + String? searchTerm, + bool clearSearchTerm = false, + DateTimeRange? dateRange, + bool clearDateRange = false, + List? selectedTags, + String? errorMessage, + }) { + return CustomerOrderListState( + status: status ?? this.status, + orders: orders ?? this.orders, + availableTags: availableTags ?? this.availableTags, + quickFilter: quickFilter ?? this.quickFilter, + storeIdFilter: clearStoreFilter + ? null + : (storeIdFilter ?? this.storeIdFilter), + searchTerm: clearSearchTerm ? null : (searchTerm ?? this.searchTerm), + dateRange: clearDateRange ? null : (dateRange ?? this.dateRange), + selectedTags: selectedTags ?? this.selectedTags, + errorMessage: errorMessage, + ); + } + + @override + List get props => [ + status, + orders, + availableTags, + quickFilter, + storeIdFilter, + searchTerm, + dateRange, + selectedTags, + errorMessage, + ]; +} diff --git a/lib/features/customer_orders/data/customer_orders_repository.dart b/lib/features/customer_orders/data/customer_orders_repository.dart new file mode 100644 index 0000000..c31c297 --- /dev/null +++ b/lib/features/customer_orders/data/customer_orders_repository.dart @@ -0,0 +1,198 @@ +import 'dart:async'; +import 'package:flutter/material.dart'; +import 'package:flux/core/enums_and_consts/consts.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/service_locator.dart'; +import 'package:supabase_flutter/supabase_flutter.dart'; + +class CustomerOrdersRepository { + final SupabaseClient _supabase = sl(); + + final StreamController _ordersChangedController = + StreamController.broadcast(); + + Stream get onOrdersChanged => _ordersChangedController.stream; + + void notifyOrdersChanged() { + if (!_ordersChangedController.isClosed) { + _ordersChangedController.add(null); + } + } + + static const String _selectRelations = ''' + *, + ${Tables.customers}(*), + ${Tables.stores}(*), + ${Tables.staffMembers}(*), + ${Tables.attachments}(*) + '''; + + Future getOrderById(String id) async { + try { + final response = await _supabase + .from(Tables.customerOrders) + .select(_selectRelations) + .eq('id', id) + .single(); + return CustomerOrderModel.fromMap(response); + } catch (e) { + debugPrint('Errore getOrderById ($id): $e'); + return null; + } + } + + Future> fetchOrders({ + required String companyId, + CustomerOrderQuickFilter quickFilter = CustomerOrderQuickFilter.active, + String? storeId, + String? searchTerm, + DateTimeRange? dateRange, + List selectedTags = const [], + }) async { + try { + var query = _supabase + .from(Tables.customerOrders) + .select(_selectRelations) + .eq('company_id', companyId); + + final statuses = quickFilter.dbStatuses; + if (statuses != null && statuses.isNotEmpty) { + query = query.inFilter('status', statuses); + } + + if (storeId != null && storeId.isNotEmpty) { + query = query.eq('store_id', storeId); + } + + if (dateRange != null) { + final start = DateTime( + dateRange.start.year, + dateRange.start.month, + dateRange.start.day, + ); + final end = DateTime( + dateRange.end.year, + dateRange.end.month, + dateRange.end.day, + 23, + 59, + 59, + 999, + ); + query = query + .gte('order_date', start.toUtc().toIso8601String()) + .lte('order_date', end.toUtc().toIso8601String()); + } + + if (selectedTags.isNotEmpty) { + query = query.overlaps('tags', selectedTags); + } + + if (searchTerm != null && searchTerm.trim().isNotEmpty) { + final cleanTerm = searchTerm.trim().replaceAll(',', ' '); + List matchingCustomerIds = []; + + try { + final custRes = await _supabase + .from(Tables.customers) + .select('id') + .eq('company_id', companyId) + .or('name.ilike.%$cleanTerm%,phone_number.ilike.%$cleanTerm%,alternative_phone_number.ilike.%$cleanTerm%'); + matchingCustomerIds = (custRes as List) + .map((row) => row['id'].toString()) + .toList(); + } catch (_) {} + + if (matchingCustomerIds.isNotEmpty) { + final idsJoined = matchingCustomerIds.join(','); + query = query.or( + 'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%,customer_id.in.($idsJoined)', + ); + } else { + query = query.or( + 'product_description.ilike.%$cleanTerm%,notes.ilike.%$cleanTerm%,external_code.ilike.%$cleanTerm%', + ); + } + } + + final response = await query.order('order_date', ascending: false); + + return (response as List) + .map((map) => CustomerOrderModel.fromMap(map as Map)) + .toList(); + } catch (e) { + debugPrint('Errore fetchOrders: $e'); + throw Exception('Impossibile caricare gli ordini: $e'); + } + } + + /// Recupera l'elenco ordinato di tutte le etichette (tags) già usate nell'azienda per l'autocomplete + Future> fetchDistinctTags(String companyId) async { + try { + final response = await _supabase + .from(Tables.customerOrders) + .select('tags') + .eq('company_id', companyId) + .not('tags', 'is', null); + + final Set distinct = {}; + for (final row in (response as List)) { + final rawList = row['tags'] as List?; + if (rawList != null) { + for (final tag in rawList) { + final clean = tag.toString().trim(); + if (clean.isNotEmpty) distinct.add(clean); + } + } + } + final sorted = distinct.toList() + ..sort((a, b) => a.toLowerCase().compareTo(b.toLowerCase())); + return sorted; + } catch (e) { + debugPrint('Errore fetchDistinctTags: $e'); + return const []; + } + } + + Future insertOrder(CustomerOrderModel order) async { + try { + final res = await _supabase + .from(Tables.customerOrders) + .insert(order.toMap()) + .select(_selectRelations) + .single(); + notifyOrdersChanged(); + return CustomerOrderModel.fromMap(res); + } catch (e) { + debugPrint('Errore insertOrder: $e'); + throw Exception('Errore nella creazione dell\'ordine: $e'); + } + } + + Future updateOrder(CustomerOrderModel order) async { + try { + final res = await _supabase + .from(Tables.customerOrders) + .update(order.toMap()) + .eq('id', order.id!) + .select(_selectRelations) + .single(); + notifyOrdersChanged(); + return CustomerOrderModel.fromMap(res); + } catch (e) { + debugPrint('Errore updateOrder: $e'); + throw Exception('Errore nell\'aggiornamento dell\'ordine: $e'); + } + } + + Future deleteOrder(String id) async { + try { + await _supabase.from(Tables.customerOrders).delete().eq('id', id); + notifyOrdersChanged(); + } catch (e) { + debugPrint('Errore deleteOrder: $e'); + throw Exception('Errore nell\'eliminazione dell\'ordine: $e'); + } + } +} diff --git a/lib/features/customer_orders/models/customer_order_model.dart b/lib/features/customer_orders/models/customer_order_model.dart new file mode 100644 index 0000000..c8e1f91 --- /dev/null +++ b/lib/features/customer_orders/models/customer_order_model.dart @@ -0,0 +1,254 @@ +import 'package:equatable/equatable.dart'; +import 'package:flux/core/enums_and_consts/consts.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; +import 'package:flux/core/utils/extensions.dart'; +import 'package:flux/features/attachments/models/attachment_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/features/customers/models/customer_model.dart'; + +class CustomerOrderModel extends Equatable { + final String? id; + final DateTime? createdAt; + final DateTime? updatedAt; + final DateTime orderDate; + final String companyId; + final String? storeId; + final String? storeDisplayName; + final String? createdById; + final String? createdByName; + final String? customerId; + final CustomerModel? customer; + final String productDescription; + final int quantity; + final String notes; + final double price; + final double deposit; + final String externalCode; + final CustomerOrderStatus status; + final List tags; + final ContactPreference contactPreference; + final String? alternativePhoneNumber; + final bool customerNotified; + final DateTime? customerNotifiedAt; + final List attachments; + + const CustomerOrderModel({ + this.id, + this.createdAt, + this.updatedAt, + required this.orderDate, + required this.companyId, + this.storeId, + this.storeDisplayName, + this.createdById, + this.createdByName, + this.customerId, + this.customer, + this.productDescription = '', + this.quantity = 1, + this.notes = '', + this.price = 0.0, + this.deposit = 0.0, + this.externalCode = '', + this.status = CustomerOrderStatus.toOrder, + this.tags = const [], + this.contactPreference = ContactPreference.whatsappPrimary, + this.alternativePhoneNumber, + this.customerNotified = false, + this.customerNotifiedAt, + this.attachments = const [], + }); + + /// Importo residuo da incassare in cassa al netto dell'eventuale acconto + double get remainingAmount => + (price - deposit) > 0 ? (price - deposit) : 0.0; + + /// URL deep link codificato nel QR dell'etichetta prodotto + String get deepLinkUrl => + id != null && id!.isNotEmpty ? 'https://flux.catelli.it/orders/form/$id' : ''; + + /// Recapito effettivo da usare in base alla preferenza scelta + String get effectiveContactDestination { + if (contactPreference.isEmail) { + return customer?.email.trim() ?? ''; + } + if (contactPreference.usesAlternativePhone) { + final orderAlt = alternativePhoneNumber?.trim() ?? ''; + if (orderAlt.isNotEmpty) return orderAlt; + return customer?.alternativePhoneNumber.trim() ?? ''; + } + return customer?.phoneNumber.trim() ?? ''; + } + + factory CustomerOrderModel.empty() => CustomerOrderModel( + orderDate: DateTime.now(), + companyId: '', + ); + + CustomerOrderModel copyWith({ + String? id, + DateTime? createdAt, + DateTime? updatedAt, + DateTime? orderDate, + String? companyId, + String? storeId, + String? storeDisplayName, + String? createdById, + String? createdByName, + String? customerId, + CustomerModel? customer, + String? productDescription, + int? quantity, + String? notes, + double? price, + double? deposit, + String? externalCode, + CustomerOrderStatus? status, + List? tags, + ContactPreference? contactPreference, + String? alternativePhoneNumber, + bool? customerNotified, + DateTime? customerNotifiedAt, + bool clearCustomerNotifiedAt = false, + List? attachments, + }) { + return CustomerOrderModel( + id: id ?? this.id, + createdAt: createdAt ?? this.createdAt, + updatedAt: updatedAt ?? this.updatedAt, + orderDate: orderDate ?? this.orderDate, + companyId: companyId ?? this.companyId, + storeId: storeId ?? this.storeId, + storeDisplayName: storeDisplayName ?? this.storeDisplayName, + createdById: createdById ?? this.createdById, + createdByName: createdByName ?? this.createdByName, + customerId: customerId ?? this.customerId, + customer: customer ?? this.customer, + productDescription: productDescription ?? this.productDescription, + quantity: quantity != null ? (quantity < 1 ? 1 : quantity) : this.quantity, + notes: notes ?? this.notes, + price: price ?? this.price, + deposit: deposit ?? this.deposit, + externalCode: externalCode ?? this.externalCode, + status: status ?? this.status, + tags: tags ?? this.tags, + contactPreference: contactPreference ?? this.contactPreference, + alternativePhoneNumber: + alternativePhoneNumber ?? this.alternativePhoneNumber, + customerNotified: customerNotified ?? this.customerNotified, + customerNotifiedAt: clearCustomerNotifiedAt + ? null + : (customerNotifiedAt ?? this.customerNotifiedAt), + attachments: attachments ?? this.attachments, + ); + } + + factory CustomerOrderModel.fromMap(Map map) { + final rawQty = (map['quantity'] as num?)?.toInt() ?? 1; + final rawTags = (map['tags'] as List?) + ?.map((e) => e.toString().trim()) + .where((e) => e.isNotEmpty) + .toList() ?? + const []; + + final createdAtLocal = map['created_at'] != null + ? DateTime.parse(map['created_at'] as String).toLocal() + : null; + + return CustomerOrderModel( + id: map['id'] as String?, + createdAt: createdAtLocal, + updatedAt: map['updated_at'] != null + ? DateTime.parse(map['updated_at'] as String).toLocal() + : null, + orderDate: map['order_date'] != null + ? DateTime.parse(map['order_date'] as String).toLocal() + : (createdAtLocal ?? DateTime.now()), + companyId: map['company_id'] as String? ?? '', + storeId: map['store_id'] as String?, + storeDisplayName: (map[Tables.stores]?['name'] as String?)?.myFormat(), + createdById: map['created_by_id'] as String?, + createdByName: (map[Tables.staffMembers]?['name'] as String?)?.myFormat(), + customerId: map['customer_id'] as String?, + customer: map[Tables.customers] != null + ? CustomerModel.fromMap( + map[Tables.customers] as Map, + ) + : null, + productDescription: map['product_description'] as String? ?? '', + quantity: rawQty < 1 ? 1 : rawQty, + notes: map['notes'] as String? ?? '', + price: (map['price'] as num?)?.toDouble() ?? 0.0, + deposit: (map['deposit'] as num?)?.toDouble() ?? 0.0, + externalCode: map['external_code'] as String? ?? '', + status: CustomerOrderStatus.fromString(map['status'] as String?), + tags: rawTags, + contactPreference: ContactPreference.fromString( + map['contact_preference'] as String?, + ), + alternativePhoneNumber: map['alternative_phone_number'] as String?, + customerNotified: map['customer_notified'] as bool? ?? false, + customerNotifiedAt: map['customer_notified_at'] != null + ? DateTime.parse(map['customer_notified_at'] as String).toLocal() + : null, + attachments: (map[Tables.attachments] as List?) + ?.map( + (x) => AttachmentModel.fromMap(x as Map), + ) + .toList() ?? + const [], + ); + } + + Map toMap() { + return { + if (id != null && id!.isNotEmpty) 'id': id, + 'order_date': orderDate.toUtc().toIso8601String(), + 'company_id': companyId, + 'store_id': storeId, + if (createdById != null && createdById!.isNotEmpty) + 'created_by_id': createdById, + 'customer_id': customerId, + 'product_description': productDescription.trim(), + 'quantity': quantity < 1 ? 1 : quantity, + 'notes': notes.trim(), + 'price': price, + 'deposit': deposit, + 'external_code': externalCode.trim(), + 'status': status.value, + 'tags': tags.map((t) => t.trim()).where((t) => t.isNotEmpty).toList(), + 'contact_preference': contactPreference.value, + 'alternative_phone_number': alternativePhoneNumber?.trim(), + 'customer_notified': customerNotified, + 'customer_notified_at': customerNotifiedAt?.toUtc().toIso8601String(), + }; + } + + @override + List get props => [ + id, + createdAt, + updatedAt, + orderDate, + companyId, + storeId, + storeDisplayName, + createdById, + createdByName, + customerId, + customer, + productDescription, + quantity, + notes, + price, + deposit, + externalCode, + status, + tags, + contactPreference, + alternativePhoneNumber, + customerNotified, + customerNotifiedAt, + attachments, + ]; +} diff --git a/lib/features/customer_orders/models/customer_order_status.dart b/lib/features/customer_orders/models/customer_order_status.dart new file mode 100644 index 0000000..a69945c --- /dev/null +++ b/lib/features/customer_orders/models/customer_order_status.dart @@ -0,0 +1,99 @@ +import 'package:flutter/material.dart'; + +/// Stato del ciclo di vita di un Ordine Cliente +enum CustomerOrderStatus { + toOrder( + value: 'to_order', + label: 'Da ordinare', + icon: Icons.shopping_cart_checkout_rounded, + color: Colors.deepOrange, + isActive: true, + ), + ordered( + value: 'ordered', + label: 'Ordinato', + icon: Icons.local_shipping_outlined, + color: Colors.blue, + isActive: true, + ), + arrived( + value: 'arrived', + label: 'Arrivato', + icon: Icons.inventory_2_rounded, + color: Colors.teal, + isActive: true, + ), + delivered( + value: 'delivered', + label: 'Consegnato', + icon: Icons.check_circle_rounded, + color: Colors.green, + isActive: false, + ), + cancelled( + value: 'cancelled', + label: 'Annullato', + icon: Icons.cancel_outlined, + color: Colors.grey, + isActive: false, + ); + + final String value; + final String label; + final IconData icon; + final Color color; + final bool isActive; + + const CustomerOrderStatus({ + required this.value, + required this.label, + required this.icon, + required this.color, + required this.isActive, + }); + + static CustomerOrderStatus fromString(String? val) { + if (val == null || val.trim().isEmpty) return CustomerOrderStatus.toOrder; + final clean = val.trim().toLowerCase(); + for (final s in CustomerOrderStatus.values) { + if (s.value == clean || s.name.toLowerCase() == clean) { + return s; + } + } + return CustomerOrderStatus.toOrder; + } +} + +/// Filtro rapido di stato nella lista Ordini Clienti +enum CustomerOrderQuickFilter { + active('Da ultimare'), + toOrder('Da ordinare'), + ordered('Ordinati'), + arrived('Arrivati'), + delivered('Consegnati'), + all('Tutti'); + + final String label; + const CustomerOrderQuickFilter(this.label); + + List? get dbStatuses { + switch (this) { + case CustomerOrderQuickFilter.active: + return [ + CustomerOrderStatus.toOrder.value, + CustomerOrderStatus.ordered.value, + CustomerOrderStatus.arrived.value, + ]; + case CustomerOrderQuickFilter.toOrder: + return [CustomerOrderStatus.toOrder.value]; + case CustomerOrderQuickFilter.ordered: + return [CustomerOrderStatus.ordered.value]; + case CustomerOrderQuickFilter.arrived: + return [CustomerOrderStatus.arrived.value]; + case CustomerOrderQuickFilter.delivered: + return [CustomerOrderStatus.delivered.value]; + case CustomerOrderQuickFilter.all: + return null; + } + } +} diff --git a/lib/features/customer_orders/ui/customer_order_form_screen.dart b/lib/features/customer_orders/ui/customer_order_form_screen.dart new file mode 100644 index 0000000..c8769a5 --- /dev/null +++ b/lib/features/customer_orders/ui/customer_order_form_screen.dart @@ -0,0 +1,1260 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/widgets/shared_forms/attachments_section.dart'; +import 'package:flux/core/widgets/shared_forms/contact_preference_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/customer_orders/blocs/customer_order_form_cubit.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart'; +import 'package:flux/features/master_data/store/bloc/store_cubit.dart'; +import 'package:intl/intl.dart'; +import 'package:printing/printing.dart'; +import 'package:url_launcher/url_launcher.dart'; + +class CustomerOrderFormScreen extends StatefulWidget { + final String? orderId; + final CustomerOrderModel? order; + + const CustomerOrderFormScreen({super.key, this.orderId, this.order}); + + @override + State createState() => + _CustomerOrderFormScreenState(); +} + +class _CustomerOrderFormScreenState extends State { + final _formKey = GlobalKey(); + + final _productCtrl = TextEditingController(); + final _notesCtrl = TextEditingController(); + final _depositCtrl = TextEditingController(); + final _priceCtrl = TextEditingController(); + final _externalCodeCtrl = TextEditingController(); + final _altPhoneCtrl = TextEditingController(); + + bool _isInitialized = false; + bool _closeAfterSave = false; + + @override + void initState() { + super.initState(); + context.read().loadStores(); + context.read().initForm( + orderId: widget.orderId, + existingOrder: widget.order, + ); + + final currentState = context.read().state; + if (currentState.status == CustomerOrderFormStatus.ready && + !_isInitialized) { + _syncControllers(currentState.order); + } + } + + @override + void dispose() { + _productCtrl.dispose(); + _notesCtrl.dispose(); + _depositCtrl.dispose(); + _priceCtrl.dispose(); + _externalCodeCtrl.dispose(); + _altPhoneCtrl.dispose(); + super.dispose(); + } + + void _syncControllers(CustomerOrderModel order) { + if (_productCtrl.text.isEmpty) { + _productCtrl.text = order.productDescription; + } + if (_notesCtrl.text.isEmpty) { + _notesCtrl.text = order.notes; + } + if (_depositCtrl.text.isEmpty && order.deposit > 0) { + _depositCtrl.text = order.deposit.toStringAsFixed(2); + } + if (_priceCtrl.text.isEmpty && order.price > 0) { + _priceCtrl.text = order.price.toStringAsFixed(2); + } + if (_externalCodeCtrl.text.isEmpty) { + _externalCodeCtrl.text = order.externalCode; + } + if (_altPhoneCtrl.text.isEmpty && order.alternativePhoneNumber != null) { + _altPhoneCtrl.text = order.alternativePhoneNumber!; + } + _isInitialized = true; + } + + double _parseAmount(String raw) { + final normalized = raw.trim().replaceAll(',', '.'); + return double.tryParse(normalized) ?? 0.0; + } + + void _flushControllersToCubit() { + context.read().updateFields( + productDescription: _productCtrl.text.trim(), + notes: _notesCtrl.text.trim(), + deposit: _parseAmount(_depositCtrl.text), + price: _parseAmount(_priceCtrl.text), + externalCode: _externalCodeCtrl.text.trim(), + alternativePhoneNumber: _altPhoneCtrl.text.trim(), + ); + } + + Future _submitSave({ + CustomerOrderStatus? overrideStatus, + bool closeAfter = true, + }) async { + if (!_formKey.currentState!.validate()) return; + _flushControllersToCubit(); + _closeAfterSave = closeAfter; + await context.read().saveOrder( + overrideStatus: overrideStatus, + ); + } + + Future _printQrLabel(CustomerOrderModel order) async { + if (order.id == null || order.id!.isEmpty) return; + final service = CustomerOrderLabelPdfService(); + await Printing.layoutPdf( + name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}', + onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(), + ); + } + + Future _launchCustomerContact(CustomerOrderModel order) async { + final dest = order.effectiveContactDestination; + if (dest.isEmpty) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Nessun recapito disponibile per il canale scelto.'), + backgroundColor: Colors.orange, + ), + ); + return; + } + + final customerName = order.customer?.name ?? 'Cliente'; + final storePart = order.storeDisplayName?.isNotEmpty == true + ? ' presso il punto vendita ${order.storeDisplayName}' + : ''; + final message = + 'Gentile $customerName, ti avvisiamo che il prodotto ordinato (${order.productDescription}) è arrivato$storePart ed è pronto per il ritiro!'; + + Uri? uri; + if (order.contactPreference.isWhatsapp) { + final cleanPhone = dest.replaceAll(RegExp(r'[^0-9+]'), ''); + final normalized = cleanPhone.startsWith('+') + ? cleanPhone.substring(1) + : (cleanPhone.startsWith('39') ? cleanPhone : '39$cleanPhone'); + uri = Uri.parse( + 'https://wa.me/$normalized?text=${Uri.encodeComponent(message)}', + ); + } else if (order.contactPreference.isCall) { + uri = Uri.parse('tel:$dest'); + } else if (order.contactPreference.isEmail) { + uri = Uri.parse( + 'mailto:$dest?subject=${Uri.encodeComponent('Il tuo ordine è arrivato!')}&body=${Uri.encodeComponent(message)}', + ); + } + + if (uri != null) { + await launchUrl(uri, mode: LaunchMode.externalApplication); + if (mounted && !order.customerNotified) { + context.read().markCustomerNotified(true); + } + } + } + + Future _showArrivedLabelPrompt(CustomerOrderModel order) async { + await showDialog( + context: context, + builder: (dialogCtx) { + return AlertDialog( + title: const Row( + children: [ + Icon(Icons.inventory_2_rounded, color: Colors.teal), + SizedBox(width: 8), + Expanded(child: Text('Prodotto segnato come Arrivato!')), + ], + ), + content: const Text( + 'Vuoi stampare subito l\'etichetta adesiva con il QR Code da applicare sul prodotto?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogCtx), + child: const Text('Più tardi'), + ), + FilledButton.icon( + icon: const Icon(Icons.print_rounded, size: 18), + label: const Text('Stampa Etichetta QR'), + onPressed: () { + Navigator.pop(dialogCtx); + _printQrLabel(order); + }, + ), + ], + ); + }, + ); + } + + Future _confirmDelete(BuildContext context) async { + final cubit = context.read(); + final ok = await showDialog( + context: context, + builder: (ctx) => AlertDialog( + title: const Text('Elimina Ordine'), + content: const Text( + 'Sei sicuro di voler eliminare definitivamente questo ordine cliente?', + ), + actions: [ + TextButton( + onPressed: () => Navigator.pop(ctx, false), + child: const Text('Annulla'), + ), + FilledButton( + style: FilledButton.styleFrom(backgroundColor: Colors.red), + onPressed: () => Navigator.pop(ctx, true), + child: const Text('Elimina'), + ), + ], + ), + ); + if (ok == true) { + await cubit.deleteOrder(); + } + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final dateTimeFmt = DateFormat('dd/MM/yyyy HH:mm'); + + return BlocConsumer( + listener: (context, state) async { + if (state.status == CustomerOrderFormStatus.ready && !_isInitialized) { + _syncControllers(state.order); + } + + if (state.order.id != null && state.order.id!.isNotEmpty) { + final attBloc = context.read(); + if (attBloc.state.parentId != state.order.id) { + attBloc.add(ParentEntitySavedEvent(state.order.id!)); + } + } + + if (state.status == CustomerOrderFormStatus.deleted) { + Navigator.of(context).pop(); + return; + } + + if (state.status == CustomerOrderFormStatus.failure && + state.errorMessage != null) { + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text(state.errorMessage!), + backgroundColor: Colors.red, + ), + ); + return; + } + + if (state.status == CustomerOrderFormStatus.saved) { + if (state.justMarkedArrived) { + await _showArrivedLabelPrompt(state.order); + } + if (_closeAfterSave && context.mounted) { + Navigator.of(context).pop(); + } else if (context.mounted) { + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Ordine aggiornato con successo!'), + backgroundColor: Colors.teal, + duration: Duration(seconds: 2), + ), + ); + } + } + }, + builder: (context, state) { + if (!_isInitialized && + state.status == CustomerOrderFormStatus.loading) { + return const Scaffold( + body: Center(child: CircularProgressIndicator()), + ); + } + + final order = state.order; + final isExisting = order.id != null && order.id!.isNotEmpty; + + return Scaffold( + appBar: AppBar( + title: Text( + isExisting ? 'Dettaglio Ordine Cliente' : 'Nuovo Ordine Cliente', + ), + actions: [ + if (isExisting) ...[ + IconButton( + tooltip: 'Stampa Etichetta QR', + icon: const Icon(Icons.qr_code_2_rounded), + onPressed: () async { + _flushControllersToCubit(); + await _printQrLabel( + context.read().state.order, + ); + }, + ), + IconButton( + tooltip: 'Elimina ordine', + icon: const Icon(Icons.delete_outline, color: Colors.red), + onPressed: () => _confirmDelete(context), + ), + ], + const SizedBox(width: 8), + ], + ), + body: Form( + key: _formKey, + child: LayoutBuilder( + builder: (context, constraints) { + final isDesktop = constraints.maxWidth > 920; + + return SingleChildScrollView( + padding: const EdgeInsets.all(16.0), + child: Center( + child: ConstrainedBox( + constraints: BoxConstraints( + maxWidth: isDesktop ? 1240 : 760, + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Metadata creazione / ultima modifica + if (order.createdAt != null) + Padding( + padding: const EdgeInsets.only( + left: 4, + right: 4, + bottom: 12, + ), + child: Wrap( + spacing: 20, + runSpacing: 4, + children: [ + Text( + 'Creato: ${dateTimeFmt.format(order.createdAt!)}', + style: TextStyle( + fontSize: 12, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + if (order.updatedAt != null) + Text( + 'Ultima modifica: ${dateTimeFmt.format(order.updatedAt!)}', + style: TextStyle( + fontSize: 12, + color: + theme.colorScheme.onSurfaceVariant, + ), + ), + if (order.createdByName != null && + order.createdByName!.isNotEmpty) + Text( + 'Inserito da: ${order.createdByName}', + style: TextStyle( + fontSize: 12, + color: + theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + + // ======================================================== + // BOX IN EVIDENZA CASSA & CONSEGNA (es. scansione QR!) + // ======================================================== + if (isExisting && + (order.status == CustomerOrderStatus.arrived || + order.status == + CustomerOrderStatus.delivered)) + _buildCassaCheckoutBanner(context, theme, order), + + if (isDesktop) + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Column( + children: [ + _buildOrderRequestCard( + context, + theme, + order, + ), + _buildAttachmentsCard(context, order), + ], + ), + ), + const SizedBox(width: 18), + Expanded( + child: _buildManagementCard( + context, + theme, + state, + ), + ), + ], + ) + else ...[ + _buildOrderRequestCard(context, theme, order), + _buildManagementCard(context, theme, state), + _buildAttachmentsCard(context, order), + ], + ], + ), + ), + ), + ); + }, + ), + ), + 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: [ + if (isExisting) ...[ + Expanded( + child: OutlinedButton.icon( + icon: const Icon(Icons.save_outlined), + label: const Text('Salva modifiche'), + onPressed: + state.status == CustomerOrderFormStatus.saving + ? null + : () => _submitSave(closeAfter: false), + ), + ), + const SizedBox(width: 12), + ], + Expanded( + flex: 2, + child: FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: order.status.color, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 14), + ), + icon: state.status == CustomerOrderFormStatus.saving + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Icon(Icons.check_rounded), + label: Text( + isExisting ? 'Salva e Chiudi' : 'Crea Ordine Cliente', + ), + onPressed: state.status == CustomerOrderFormStatus.saving + ? null + : () => _submitSave(closeAfter: true), + ), + ), + ], + ), + ), + ), + ); + }, + ); + } + + // ========================================================================= + // BANNER CASSA & CONSEGNA RAPIDA (Per scansione QR code sul prodotto!) + // ========================================================================= + Widget _buildCassaCheckoutBanner( + BuildContext context, + ThemeData theme, + CustomerOrderModel order, + ) { + final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€'); + final livePrice = _parseAmount(_priceCtrl.text) > 0 + ? _parseAmount(_priceCtrl.text) + : order.price; + final liveDeposit = _parseAmount(_depositCtrl.text) > 0 + ? _parseAmount(_depositCtrl.text) + : order.deposit; + final toPay = (livePrice - liveDeposit) > 0 ? (livePrice - liveDeposit) : 0.0; + final code = _externalCodeCtrl.text.trim().isNotEmpty + ? _externalCodeCtrl.text.trim() + : order.externalCode; + final isDelivered = order.status == CustomerOrderStatus.delivered; + + return Container( + margin: const EdgeInsets.only(bottom: 20), + padding: const EdgeInsets.all(20), + decoration: BoxDecoration( + gradient: LinearGradient( + colors: isDelivered + ? [ + Colors.green.shade600.withValues(alpha: 0.12), + Colors.green.shade50.withValues(alpha: 0.25), + ] + : [ + Colors.teal.shade600.withValues(alpha: 0.14), + Colors.cyan.shade50.withValues(alpha: 0.3), + ], + begin: Alignment.topLeft, + end: Alignment.bottomRight, + ), + borderRadius: BorderRadius.circular(18), + border: Border.all( + color: isDelivered ? Colors.green : Colors.teal, + width: 1.8, + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Icon( + isDelivered + ? Icons.check_circle_rounded + : Icons.point_of_sale_rounded, + color: isDelivered ? Colors.green.shade700 : Colors.teal.shade700, + size: 26, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + isDelivered + ? 'ORDINE GIÀ CONSEGNATO AL CLIENTE' + : 'RIEPILOGO CASSA & CONSEGNA AL CLIENTE', + style: TextStyle( + fontWeight: FontWeight.w900, + fontSize: 14, + letterSpacing: 0.5, + color: isDelivered + ? Colors.green.shade800 + : Colors.teal.shade900, + ), + ), + ), + OutlinedButton.icon( + icon: const Icon(Icons.qr_code_2_rounded, size: 18), + label: const Text('Etichetta QR'), + style: OutlinedButton.styleFrom( + visualDensity: VisualDensity.compact, + ), + onPressed: () { + _flushControllersToCubit(); + _printQrLabel( + context.read().state.order, + ); + }, + ), + ], + ), + const Divider(height: 24), + Wrap( + spacing: 24, + runSpacing: 14, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + // Cliente + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'CLIENTE', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + Text( + order.customer?.name ?? 'Cliente sconosciuto', + style: theme.textTheme.titleLarge?.copyWith( + fontWeight: FontWeight.w900, + ), + ), + ], + ), + + // Codice Cassa copiabile + Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: theme.dividerColor.withValues(alpha: 0.5), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'CODICE DA BATTERE IN CASSA', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w800, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + Text( + code.isNotEmpty ? code : 'Non inserito', + style: TextStyle( + fontSize: 18, + fontWeight: FontWeight.w900, + color: code.isNotEmpty + ? theme.colorScheme.primary + : Colors.grey, + ), + ), + ], + ), + if (code.isNotEmpty) ...[ + const SizedBox(width: 8), + IconButton( + tooltip: 'Copia codice cassa', + visualDensity: VisualDensity.compact, + icon: const Icon(Icons.copy_rounded, size: 18), + onPressed: () { + Clipboard.setData(ClipboardData(text: code)); + ScaffoldMessenger.of(context).showSnackBar( + SnackBar( + content: Text('Codice "$code" copiato!'), + duration: const Duration(seconds: 2), + ), + ); + }, + ), + ], + ], + ), + ), + + // Prezzo & Da Saldare + Container( + padding: const EdgeInsets.symmetric( + horizontal: 14, + vertical: 8, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surface, + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.teal.withValues(alpha: 0.4), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + liveDeposit > 0 + ? 'DA INCASSARE (Prezzo ${currencyFmt.format(livePrice)} - Acconto ${currencyFmt.format(liveDeposit)})' + : 'PREZZO DA INCASSARE', + style: TextStyle( + fontSize: 10, + fontWeight: FontWeight.w800, + color: theme.colorScheme.onSurfaceVariant, + ), + ), + Text( + livePrice > 0 + ? currencyFmt.format(toPay) + : 'Prezzo non impostato', + style: TextStyle( + fontSize: 20, + fontWeight: FontWeight.w900, + color: Colors.teal.shade700, + ), + ), + ], + ), + ), + ], + ), + + if (!isDelivered) ...[ + const SizedBox(height: 16), + Wrap( + spacing: 10, + runSpacing: 10, + children: [ + FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: Colors.green.shade600, + foregroundColor: Colors.white, + ), + icon: const Icon(Icons.check_circle_outline_rounded), + label: const Text('Consegna al Cliente'), + onPressed: () => _submitSave( + overrideStatus: CustomerOrderStatus.delivered, + closeAfter: true, + ), + ), + OutlinedButton.icon( + icon: order.contactPreference.buildIcon(size: 16), + label: Text( + order.customerNotified + ? 'Ricontatta (${order.contactPreference.shortLabel})' + : 'Avvisa Cliente (${order.contactPreference.shortLabel})', + ), + onPressed: () { + _flushControllersToCubit(); + _launchCustomerContact( + context.read().state.order, + ); + }, + ), + TextButton.icon( + style: TextButton.styleFrom(foregroundColor: Colors.red), + icon: const Icon(Icons.cancel_outlined, size: 18), + label: const Text('Annulla Ordine'), + onPressed: () => _submitSave( + overrideStatus: CustomerOrderStatus.cancelled, + closeAfter: true, + ), + ), + ], + ), + ], + ], + ), + ); + } + + // ========================================================================= + // CARD 1: RICHIESTA ORDINE & CLIENTE (Inserimento rapido al banco) + // ========================================================================= + Widget _buildOrderRequestCard( + BuildContext context, + ThemeData theme, + CustomerOrderModel order, + ) { + final dateFmt = DateFormat('dd/MM/yyyy'); + + return _buildCard( + title: 'Richiesta Cliente', + icon: Icons.shopping_bag_outlined, + themeColor: Colors.indigo, + headerTrailing: InkWell( + borderRadius: BorderRadius.circular(8), + onTap: () async { + final picked = await showDatePicker( + context: context, + initialDate: order.orderDate, + firstDate: DateTime(2023), + lastDate: DateTime.now().add(const Duration(days: 365)), + ); + if (picked != null && context.mounted) { + final now = DateTime.now(); + context.read().updateFields( + orderDate: DateTime( + picked.year, + picked.month, + picked.day, + now.hour, + now.minute, + ), + ); + } + }, + child: Container( + padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 6), + decoration: BoxDecoration( + color: Colors.indigo.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(8), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon( + Icons.calendar_today_outlined, + size: 15, + color: Colors.indigo, + ), + const SizedBox(width: 6), + Text( + dateFmt.format(order.orderDate), + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.bold, + color: Colors.indigo, + ), + ), + ], + ), + ), + ), + children: [ + // Selettore Negozio (se l'azienda ha più punti vendita) + BlocBuilder( + builder: (context, storeState) { + if (storeState.stores.length <= 1) return const SizedBox.shrink(); + return Padding( + padding: const EdgeInsets.only(bottom: 16), + child: DropdownButtonFormField( + initialValue: + storeState.stores.any((s) => s.id == order.storeId) + ? order.storeId + : null, + decoration: const InputDecoration( + labelText: 'Punto Vendita di Ritiro', + prefixIcon: Icon(Icons.storefront_outlined), + ), + items: storeState.stores + .map( + (s) => DropdownMenuItem(value: s.id, child: Text(s.name)), + ) + .toList(), + onChanged: (val) { + final store = storeState.stores.firstWhere( + (s) => s.id == val, + ); + context.read().updateFields( + storeId: store.id, + storeDisplayName: store.name, + ); + }, + ), + ); + }, + ), + + // Cliente + SharedCustomerSection( + customer: order.customer, + onCustomerSelected: (customer) { + if (_altPhoneCtrl.text.trim().isEmpty && + customer.alternativePhoneNumber.trim().isNotEmpty) { + _altPhoneCtrl.text = customer.alternativePhoneNumber.trim(); + } + context.read().updateCustomer(customer); + }, + ), + const SizedBox(height: 18), + + // Prodotto + Quantità + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: TextFormField( + controller: _productCtrl, + decoration: const InputDecoration( + labelText: 'Prodotto richiesto *', + hintText: 'Es. Cover MagSafe iPhone 16 Pro Nera...', + prefixIcon: Icon(Icons.inventory_2_outlined), + ), + validator: (val) => (val == null || val.trim().isEmpty) + ? 'Inserisci cosa desidera ordinare il cliente' + : null, + ), + ), + const SizedBox(width: 12), + Container( + decoration: BoxDecoration( + border: Border.all( + color: theme.dividerColor.withValues(alpha: 0.6), + ), + borderRadius: BorderRadius.circular(10), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + IconButton( + tooltip: 'Riduci quantità', + icon: const Icon(Icons.remove, size: 18), + onPressed: order.quantity > 1 + ? () => context + .read() + .updateFields(quantity: order.quantity - 1) + : null, + ), + Text( + '${order.quantity}', + style: const TextStyle( + fontSize: 16, + fontWeight: FontWeight.bold, + ), + ), + IconButton( + tooltip: 'Aumenta quantità', + icon: const Icon(Icons.add, size: 18), + onPressed: () => context + .read() + .updateFields(quantity: order.quantity + 1), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 18), + + // Modalità di Avviso Cliente + ContactPreferenceSection( + selectedPreference: order.contactPreference, + customer: order.customer, + alternativePhoneController: _altPhoneCtrl, + onPreferenceChanged: (pref) { + context.read().updateFields( + contactPreference: pref, + ); + }, + ), + const SizedBox(height: 18), + + // Eventuale acconto lasciato subito + Note + TextFormField( + controller: _depositCtrl, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + decoration: const InputDecoration( + labelText: 'Acconto lasciato dal cliente (€) - opzionale', + prefixIcon: Icon(Icons.savings_outlined), + ), + onChanged: (_) => setState(() {}), + ), + const SizedBox(height: 16), + TextFormField( + controller: _notesCtrl, + minLines: 3, + maxLines: 10, + decoration: const InputDecoration( + labelText: 'Note / Dettagli aggiuntivi (colore, link, modello...)', + alignLabelWithHint: true, + prefixIcon: Icon(Icons.notes_outlined), + ), + ), + ], + ); + } + + // ========================================================================= + // CARD 2: LAVORAZIONE ORDINE, ETICHETTE & DATI CASSA + // ========================================================================= + Widget _buildManagementCard( + BuildContext context, + ThemeData theme, + CustomerOrderFormState state, + ) { + final order = state.order; + final dateTimeFmt = DateFormat('dd/MM/yyyy HH:mm'); + + return _buildCard( + title: 'Gestione Ordine, Etichette & Cassa', + icon: Icons.sell_outlined, + themeColor: Colors.teal, + children: [ + // Stato Ordine + Text( + 'Stato Lavorazione', + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Wrap( + spacing: 8, + runSpacing: 8, + children: CustomerOrderStatus.values.map((s) { + final selected = order.status == s; + return ChoiceChip( + selected: selected, + showCheckmark: false, + avatar: Icon( + s.icon, + size: 16, + color: selected ? s.color : Colors.grey.shade600, + ), + label: Text( + s.label, + style: TextStyle( + fontWeight: selected ? FontWeight.bold : FontWeight.w500, + color: selected ? s.color : null, + ), + ), + selectedColor: s.color.withValues(alpha: 0.16), + side: BorderSide( + color: selected + ? s.color.withValues(alpha: 0.65) + : theme.dividerColor.withValues(alpha: 0.35), + ), + onSelected: (_) { + context.read().updateFields(status: s); + }, + ); + }).toList(), + ), + const SizedBox(height: 20), + + // Etichette con Autocomplete sulle etichette già esistenti + Text( + 'Etichette (con autocompletamento)', + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 8), + Autocomplete( + optionsBuilder: (TextEditingValue textEditingValue) { + final query = textEditingValue.text.trim().toLowerCase(); + final unusedTags = state.availableTags.where( + (t) => + !order.tags.any((ot) => ot.toLowerCase() == t.toLowerCase()), + ); + if (query.isEmpty) return unusedTags; + return unusedTags.where((t) => t.toLowerCase().contains(query)); + }, + onSelected: (String selection) { + context.read().addTag(selection); + }, + fieldViewBuilder: + (context, textController, focusNode, onFieldSubmitted) { + return TextField( + controller: textController, + focusNode: focusNode, + decoration: InputDecoration( + hintText: + 'Scrivi un\'etichetta (es. Amazon, Fornitore, Urgente) e premi Invio...', + prefixIcon: const Icon(Icons.label_outline_rounded), + suffixIcon: IconButton( + tooltip: 'Aggiungi etichetta', + icon: const Icon(Icons.add_circle_outline), + onPressed: () { + final val = textController.text.trim(); + if (val.isNotEmpty) { + context.read().addTag(val); + textController.clear(); + } + }, + ), + ), + onSubmitted: (val) { + if (val.trim().isNotEmpty) { + context.read().addTag(val); + textController.clear(); + focusNode.requestFocus(); + } + }, + ); + }, + ), + if (order.tags.isNotEmpty) ...[ + const SizedBox(height: 10), + Wrap( + spacing: 8, + runSpacing: 6, + children: order.tags + .map( + (tag) => InputChip( + label: Text( + '#$tag', + style: const TextStyle(fontWeight: FontWeight.bold), + ), + backgroundColor: Colors.deepPurple.withValues(alpha: 0.1), + onDeleted: () => + context.read().removeTag(tag), + ), + ) + .toList(), + ), + ], + const SizedBox(height: 20), + + // Codice Esterno (da battere in cassa) & Prezzo di vendita + Row( + children: [ + Expanded( + child: TextFormField( + controller: _externalCodeCtrl, + decoration: const InputDecoration( + labelText: 'Codice Esterno (Cassa)', + hintText: 'Codice articolo...', + prefixIcon: Icon(Icons.qr_code_scanner_rounded), + ), + onChanged: (_) => setState(() {}), + ), + ), + const SizedBox(width: 12), + Expanded( + child: TextFormField( + controller: _priceCtrl, + keyboardType: const TextInputType.numberWithOptions( + decimal: true, + ), + decoration: const InputDecoration( + labelText: 'Prezzo Vendita (€)', + prefixIcon: Icon(Icons.euro_rounded), + ), + onChanged: (_) => setState(() {}), + ), + ), + ], + ), + const SizedBox(height: 18), + + // Sezione Avviso Cliente + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: order.customerNotified + ? Colors.green.withValues(alpha: 0.08) + : theme.colorScheme.surfaceContainerHighest.withValues( + alpha: 0.4, + ), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: order.customerNotified + ? Colors.green.withValues(alpha: 0.4) + : theme.dividerColor.withValues(alpha: 0.3), + ), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + SwitchListTile( + contentPadding: EdgeInsets.zero, + title: const Text( + 'Cliente avvisato dell\'arrivo', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14), + ), + subtitle: Text( + order.customerNotified && order.customerNotifiedAt != null + ? 'Avvisato il ${dateTimeFmt.format(order.customerNotifiedAt!)}' + : 'Non ancora avvisato (${order.contactPreference.label})', + style: const TextStyle(fontSize: 12), + ), + value: order.customerNotified, + onChanged: (val) => context + .read() + .markCustomerNotified(val), + ), + if (order.customer != null) + Align( + alignment: Alignment.centerRight, + child: TextButton.icon( + icon: order.contactPreference.buildIcon(size: 15), + label: Text( + 'Contatta ora su ${order.contactPreference.shortLabel}', + ), + onPressed: () { + _flushControllersToCubit(); + _launchCustomerContact( + context.read().state.order, + ); + }, + ), + ), + ], + ), + ), + ], + ); + } + + // ========================================================================= + // CARD 3: ALLEGATI & FOTO PRODOTTO + // ========================================================================= + Widget _buildAttachmentsCard(BuildContext context, CustomerOrderModel order) { + return _buildCard( + title: 'Foto e Allegati', + icon: Icons.attach_file_rounded, + themeColor: Colors.deepPurple, + children: [ + SharedAttachmentsSection( + parentType: AttachmentParentType.customerOrder, + parentId: order.id, + titleForUpload: order.customer?.name ?? 'Nuovo Ordine', + onEnsureEntitySaved: () async { + if (!_formKey.currentState!.validate()) return null; + _flushControllersToCubit(); + final saved = await context + .read() + .saveOrder(silentForAttachment: true); + return saved?.id; + }, + ), + ], + ); + } + + Widget _buildCard({ + required String title, + required IconData icon, + Widget? customIconWidget, + required Color themeColor, + required List children, + Widget? headerTrailing, + }) { + return Card( + margin: const EdgeInsets.only(bottom: 20), + elevation: 0, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(16), + side: BorderSide(color: themeColor.withValues(alpha: 0.3), width: 1), + ), + child: Padding( + padding: const EdgeInsets.all(20.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(8), + decoration: BoxDecoration( + color: themeColor.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(8), + ), + child: customIconWidget ?? Icon(icon, color: themeColor), + ), + const SizedBox(width: 12), + Expanded( + child: Text( + title, + style: Theme.of(context).textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + color: themeColor, + ), + ), + ), + ?headerTrailing, + ], + ), + const Divider(height: 28), + ...children, + ], + ), + ), + ); + } +} diff --git a/lib/features/customer_orders/ui/customer_order_list_screen.dart b/lib/features/customer_orders/ui/customer_order_list_screen.dart new file mode 100644 index 0000000..972b854 --- /dev/null +++ b/lib/features/customer_orders/ui/customer_order_list_screen.dart @@ -0,0 +1,770 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/core/routes/routes.dart'; +import 'package:flux/core/theme/theme.dart'; +import 'package:flux/core/widgets/staff_selector_modal.dart'; +import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart'; +import 'package:flux/features/master_data/store/bloc/store_cubit.dart'; +import 'package:go_router/go_router.dart'; +import 'package:intl/intl.dart'; +import 'package:printing/printing.dart'; + +class CustomerOrderListScreen extends StatefulWidget { + const CustomerOrderListScreen({super.key}); + + @override + State createState() => + _CustomerOrderListScreenState(); +} + +class _CustomerOrderListScreenState extends State { + final TextEditingController _searchCtrl = TextEditingController(); + + @override + void initState() { + super.initState(); + context.read().init(); + context.read().loadStores(); + } + + @override + void dispose() { + _searchCtrl.dispose(); + super.dispose(); + } + + Future _createNewOrder(BuildContext context) async { + final createdBy = await getStaffMember(context); + if (createdBy == null || !context.mounted) return; + context.pushNamed( + Routes.customerOrderForm, + pathParameters: {'id': 'new'}, + extra: (createdBy: createdBy, order: null), + ); + } + + Future _pickDateRange( + BuildContext context, + DateTimeRange? current, + ) async { + final picked = await showDateRangePicker( + context: context, + firstDate: DateTime(2023), + lastDate: DateTime.now().add(const Duration(days: 365)), + initialDateRange: current, + ); + if (picked != null && context.mounted) { + context.read().setDateRange(picked); + } + } + + Future _printLabel(BuildContext context, CustomerOrderModel order) async { + final service = CustomerOrderLabelPdfService(); + await Printing.layoutPdf( + name: 'Etichetta_Ordine_${order.customer?.name ?? order.id}', + onLayout: (_) async => (await service.generateOrderLabelPdf(order)).save(), + ); + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final dateFmt = DateFormat('dd/MM/yyyy'); + final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€'); + + return BlocBuilder( + builder: (context, state) { + return Scaffold( + backgroundColor: theme.colorScheme.surface, + floatingActionButton: FloatingActionButton.extended( + onPressed: () => _createNewOrder(context), + icon: const Icon(Icons.add_shopping_cart_rounded), + label: const Text('Nuovo Ordine'), + ), + body: SafeArea( + child: LayoutBuilder( + builder: (context, constraints) { + final isMobile = constraints.maxWidth < 650; + final hPad = isMobile ? 16.0 : 24.0; + + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // --- HEADER & FILTRI --- + Padding( + padding: EdgeInsets.fromLTRB(hPad, 16, hPad, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + children: [ + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Ordini Clienti', + style: (isMobile + ? theme.textTheme.titleLarge + : theme.textTheme.headlineSmall) + ?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + 'Richieste prodotti, etichette acquisti e ritiri in cassa', + style: theme.textTheme.bodySmall + ?.copyWith( + color: theme + .colorScheme + .onSurfaceVariant, + ), + ), + ], + ), + ), + IconButton( + tooltip: 'Aggiorna lista', + onPressed: () => context + .read() + .init(), + icon: const Icon(Icons.refresh_rounded), + ), + ], + ), + const SizedBox(height: 12), + + // Barra ricerca + Data + Negozio + Wrap( + spacing: 10, + runSpacing: 10, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + SizedBox( + width: isMobile ? double.infinity : 320, + child: TextField( + controller: _searchCtrl, + onChanged: (val) => context + .read() + .setSearchTerm(val), + decoration: InputDecoration( + hintText: + 'Cerca cliente, prodotto, codice cassa...', + prefixIcon: const Icon( + Icons.search, + size: 20, + ), + isDense: true, + suffixIcon: + _searchCtrl.text.trim().isNotEmpty + ? IconButton( + icon: const Icon( + Icons.clear, + size: 18, + ), + onPressed: () { + _searchCtrl.clear(); + context + .read< + CustomerOrderListCubit + >() + .setSearchTerm(''); + }, + ) + : null, + ), + ), + ), + + // Filtro Date + OutlinedButton.icon( + icon: Icon( + Icons.date_range_outlined, + size: 18, + color: state.dateRange != null + ? theme.colorScheme.primary + : null, + ), + label: Text( + state.dateRange != null + ? '${dateFmt.format(state.dateRange!.start)} - ${dateFmt.format(state.dateRange!.end)}' + : 'Filtra Date', + ), + onPressed: () => + _pickDateRange(context, state.dateRange), + ), + if (state.dateRange != null) + IconButton( + tooltip: 'Rimuovi filtro date', + visualDensity: VisualDensity.compact, + onPressed: () => context + .read() + .setDateRange(null), + icon: const Icon(Icons.close, size: 18), + ), + + // Filtro Negozio + BlocBuilder( + builder: (context, storeState) { + if (storeState.stores.length <= 1) { + return const SizedBox.shrink(); + } + return DropdownButtonHideUnderline( + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 12, + ), + decoration: BoxDecoration( + border: Border.all( + color: theme.dividerColor.withValues( + alpha: 0.5, + ), + ), + borderRadius: BorderRadius.circular(8), + ), + child: DropdownButton( + value: state.storeIdFilter, + hint: const Text('Tutti i negozi'), + isDense: true, + items: [ + const DropdownMenuItem( + value: null, + child: Text('Tutti i negozi'), + ), + ...storeState.stores.map( + (s) => DropdownMenuItem( + value: s.id, + child: Text(s.name), + ), + ), + ], + onChanged: (val) => context + .read() + .setStoreFilter(val), + ), + ), + ); + }, + ), + + if (state.hasAdvancedFilters) + TextButton.icon( + onPressed: () { + _searchCtrl.clear(); + context + .read() + .resetFilters(); + }, + icon: const Icon( + Icons.filter_alt_off_outlined, + size: 18, + ), + label: const Text('Azzera filtri'), + ), + ], + ), + const SizedBox(height: 10), + + // Quick Status Filters (Default: "Da ultimare") + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: CustomerOrderQuickFilter.values.map(( + f, + ) { + final selected = state.quickFilter == f; + return Padding( + padding: const EdgeInsets.only(right: 8), + child: ChoiceChip( + label: Text(f.label), + selected: selected, + onSelected: (_) => context + .read() + .setQuickFilter(f), + ), + ); + }).toList(), + ), + ), + + // Filtro Etichette (se presenti) + if (state.availableTags.isNotEmpty) ...[ + const SizedBox(height: 8), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + Icon( + Icons.label_outline_rounded, + size: 16, + color: theme.colorScheme.onSurfaceVariant, + ), + const SizedBox(width: 6), + ...state.availableTags.map((tag) { + final isSelected = state.selectedTags + .contains(tag); + return Padding( + padding: const EdgeInsets.only(right: 6), + child: FilterChip( + visualDensity: VisualDensity.compact, + label: Text( + tag, + style: const TextStyle(fontSize: 12), + ), + selected: isSelected, + onSelected: (_) => context + .read() + .toggleTagFilter(tag), + ), + ); + }), + ], + ), + ), + ], + ], + ), + ), + + const Divider(height: 1), + + // --- CORPO LISTA --- + Expanded( + child: _buildListBody( + context, + theme, + state, + hPad: hPad, + dateFmt: dateFmt, + currencyFmt: currencyFmt, + ), + ), + ], + ); + }, + ), + ), + ); + }, + ); + } + + Widget _buildListBody( + BuildContext context, + ThemeData theme, + CustomerOrderListState state, { + required double hPad, + required DateFormat dateFmt, + required NumberFormat currencyFmt, + }) { + if (state.status == CustomerOrderListStatus.loading && + state.orders.isEmpty) { + return const Center(child: CircularProgressIndicator()); + } + + if (state.status == CustomerOrderListStatus.failure) { + return Center( + child: Padding( + padding: const EdgeInsets.all(24.0), + child: Text( + 'Errore nel caricamento ordini:\n${state.errorMessage}', + textAlign: TextAlign.center, + style: TextStyle(color: theme.colorScheme.error), + ), + ), + ); + } + + if (state.orders.isEmpty) { + return Center( + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.inventory_2_outlined, + size: 56, + color: theme.colorScheme.onSurfaceVariant.withValues(alpha: 0.4), + ), + const SizedBox(height: 12), + Text( + 'Nessun ordine trovato per i filtri selezionati.', + style: TextStyle( + color: theme.colorScheme.onSurfaceVariant, + fontSize: 15, + ), + ), + ], + ), + ); + } + + return ListView.separated( + padding: EdgeInsets.fromLTRB(hPad, 14, hPad, 96), + itemCount: state.orders.length, + separatorBuilder: (_, _) => const SizedBox(height: 10), + itemBuilder: (context, index) { + final order = state.orders[index]; + return _buildOrderCard( + context, + theme, + order, + dateFmt: dateFmt, + currencyFmt: currencyFmt, + ); + }, + ); + } + + Widget _buildOrderCard( + BuildContext context, + ThemeData theme, + CustomerOrderModel order, { + required DateFormat dateFmt, + required NumberFormat currencyFmt, + }) { + final status = order.status; + final pref = order.contactPreference; + final needsCustomerAlert = + status == CustomerOrderStatus.arrived && !order.customerNotified; + + return Card( + elevation: 0, + margin: EdgeInsets.zero, + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(14), + side: BorderSide( + color: status == CustomerOrderStatus.arrived + ? Colors.teal.withValues(alpha: 0.5) + : theme.dividerColor.withValues(alpha: 0.35), + width: status == CustomerOrderStatus.arrived ? 1.4 : 1, + ), + ), + child: InkWell( + borderRadius: BorderRadius.circular(14), + onTap: () => context.pushNamed( + Routes.customerOrderForm, + pathParameters: {'id': order.id!}, + extra: (createdBy: null, order: order), + ), + child: Padding( + padding: const EdgeInsets.all(14.0), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // Riga 1: Data + Negozio + Stato cliccabile + Stampa QR rapida + Wrap( + alignment: WrapAlignment.spaceBetween, + crossAxisAlignment: WrapCrossAlignment.center, + spacing: 8, + runSpacing: 6, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.calendar_today_outlined, + size: 13, + color: context.secondaryText, + ), + const SizedBox(width: 4), + Text( + dateFmt.format(order.orderDate), + style: TextStyle( + fontSize: 12, + color: context.secondaryText, + fontWeight: FontWeight.w600, + ), + ), + if (order.storeDisplayName != null && + order.storeDisplayName!.isNotEmpty) ...[ + const SizedBox(width: 8), + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: theme.colorScheme.primary.withValues( + alpha: 0.08, + ), + borderRadius: BorderRadius.circular(6), + ), + child: Text( + order.storeDisplayName!, + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.w600, + color: theme.colorScheme.primary, + ), + ), + ), + ], + ], + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + if (needsCustomerAlert) + Container( + margin: const EdgeInsets.only(right: 6), + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 3, + ), + decoration: BoxDecoration( + color: Colors.amber.shade100, + borderRadius: BorderRadius.circular(6), + border: Border.all(color: Colors.amber.shade600), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon( + Icons.notifications_active_outlined, + size: 13, + color: Colors.amber.shade900, + ), + const SizedBox(width: 4), + Text( + 'Da avvisare', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.amber.shade900, + ), + ), + ], + ), + ) + else if (order.customerNotified) + Container( + margin: const EdgeInsets.only(right: 6), + padding: const EdgeInsets.symmetric( + horizontal: 7, + vertical: 3, + ), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(6), + ), + child: const Text( + 'Avvisato ✓', + style: TextStyle( + fontSize: 11, + fontWeight: FontWeight.bold, + color: Colors.green, + ), + ), + ), + + // Menu rapido cambio stato + PopupMenuButton( + tooltip: 'Cambia stato rapidamente', + onSelected: (newStatus) { + context + .read() + .quickUpdateStatus(order, newStatus); + }, + itemBuilder: (_) => CustomerOrderStatus.values + .map( + (s) => PopupMenuItem( + value: s, + child: Row( + children: [ + Icon(s.icon, size: 18, color: s.color), + const SizedBox(width: 8), + Text(s.label), + ], + ), + ), + ) + .toList(), + child: Container( + padding: const EdgeInsets.symmetric( + horizontal: 9, + vertical: 4, + ), + decoration: BoxDecoration( + color: status.color.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(8), + border: Border.all( + color: status.color.withValues(alpha: 0.45), + ), + ), + child: Row( + mainAxisSize: MainAxisSize.min, + children: [ + Icon(status.icon, size: 14, color: status.color), + const SizedBox(width: 5), + Text( + status.label, + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.bold, + color: status.color, + ), + ), + const SizedBox(width: 2), + Icon( + Icons.arrow_drop_down, + size: 16, + color: status.color, + ), + ], + ), + ), + ), + + if (order.id != null) ...[ + const SizedBox(width: 4), + IconButton( + tooltip: 'Stampa etichetta QR', + visualDensity: VisualDensity.compact, + onPressed: () => _printLabel(context, order), + icon: const Icon(Icons.qr_code_2_rounded, size: 20), + ), + ], + ], + ), + ], + ), + + const SizedBox(height: 8), + + // Riga 2: Prodotto + Quantità + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Expanded( + child: Text( + order.quantity > 1 + ? '${order.productDescription} ×${order.quantity}' + : order.productDescription, + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.w800, + ), + ), + ), + if (order.price > 0) ...[ + const SizedBox(width: 8), + Text( + currencyFmt.format(order.price), + style: theme.textTheme.titleSmall?.copyWith( + fontWeight: FontWeight.w800, + color: theme.colorScheme.primary, + ), + ), + ], + ], + ), + + const SizedBox(height: 6), + + // Riga 3: Cliente + Canale di avviso + Codice Cassa / Acconto + Wrap( + spacing: 12, + runSpacing: 6, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + Row( + mainAxisSize: MainAxisSize.min, + children: [ + const Icon(Icons.person_outline, size: 15), + const SizedBox(width: 4), + Text( + order.customer?.name ?? 'Cliente sconosciuto', + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 13, + ), + ), + ], + ), + Row( + mainAxisSize: MainAxisSize.min, + children: [ + pref.buildIcon(size: 14), + const SizedBox(width: 4), + Text( + pref.shortLabel, + style: TextStyle( + fontSize: 12, + color: pref.color, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + if (order.externalCode.isNotEmpty) + Container( + padding: const EdgeInsets.symmetric( + horizontal: 6, + vertical: 2, + ), + decoration: BoxDecoration( + color: theme.colorScheme.surfaceContainerHighest, + borderRadius: BorderRadius.circular(5), + ), + child: Text( + 'Cod. Cassa: ${order.externalCode}', + style: const TextStyle( + fontSize: 11.5, + fontWeight: FontWeight.w700, + ), + ), + ), + if (order.deposit > 0) + Text( + 'Acconto: ${currencyFmt.format(order.deposit)}', + style: TextStyle( + fontSize: 12, + color: Colors.teal.shade700, + fontWeight: FontWeight.w600, + ), + ), + ], + ), + + // Riga 4: Etichette (se presenti) + if (order.tags.isNotEmpty) ...[ + const SizedBox(height: 8), + Wrap( + spacing: 6, + runSpacing: 4, + children: order.tags + .map( + (tag) => Container( + padding: const EdgeInsets.symmetric( + horizontal: 8, + vertical: 2, + ), + decoration: BoxDecoration( + color: Colors.deepPurple.withValues(alpha: 0.1), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: Colors.deepPurple.withValues(alpha: 0.3), + ), + ), + child: Text( + '#$tag', + style: const TextStyle( + fontSize: 11, + fontWeight: FontWeight.w700, + color: Colors.deepPurple, + ), + ), + ), + ) + .toList(), + ), + ], + ], + ), + ), + ), + ); + } +} diff --git a/lib/features/customer_orders/utils/customer_order_label_pdf_service.dart b/lib/features/customer_orders/utils/customer_order_label_pdf_service.dart new file mode 100644 index 0000000..8c0b522 --- /dev/null +++ b/lib/features/customer_orders/utils/customer_order_label_pdf_service.dart @@ -0,0 +1,116 @@ +import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:get_it/get_it.dart'; +import 'package:intl/intl.dart'; +import 'package:pdf/pdf.dart'; +import 'package:pdf/widgets.dart' as pw; +import 'package:printing/printing.dart'; + +class CustomerOrderLabelPdfService { + /// Genera il PDF dell'etichetta prodotto con QR code, leggendo le misure + /// configurate nelle Impostazioni Azienda (fallback 40 x 30 mm). + Future generateOrderLabelPdf(CustomerOrderModel order) async { + final pdf = pw.Document(); + final font = await PdfGoogleFonts.robotoRegular(); + final boldFont = await PdfGoogleFonts.robotoBold(); + + final company = GetIt.I.get().state.company; + final widthMm = company?.labelWidth ?? 40.0; + final heightMm = company?.labelHeight ?? 30.0; + final isVertical = company?.isLabelVertical ?? false; + + final pageFormat = isVertical + ? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm) + : PdfPageFormat(widthMm * PdfPageFormat.mm, heightMm * PdfPageFormat.mm); + + final effectiveW = pageFormat.width; + final effectiveH = pageFormat.height; + final minSide = effectiveW < effectiveH ? effectiveW : effectiveH; + final qrSize = (minSide - 6 * PdfPageFormat.mm).clamp( + 14 * PdfPageFormat.mm, + 26 * PdfPageFormat.mm, + ); + + final customerName = order.customer?.name ?? 'Cliente'; + final qtySuffix = order.quantity > 1 ? ' (x${order.quantity})' : ''; + final productLine = '${order.productDescription}$qtySuffix'; + final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€'); + final priceStr = order.price > 0 ? currencyFmt.format(order.price) : ''; + final codeStr = order.externalCode.trim(); + final qrData = order.deepLinkUrl.isNotEmpty + ? order.deepLinkUrl + : (order.id ?? ''); + + pdf.addPage( + pw.Page( + pageFormat: pageFormat, + margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm), + build: (context) { + final infoBlock = pw.Column( + crossAxisAlignment: pw.CrossAxisAlignment.start, + mainAxisAlignment: pw.MainAxisAlignment.center, + mainAxisSize: pw.MainAxisSize.min, + children: [ + pw.Text( + customerName, + style: pw.TextStyle(font: boldFont, fontSize: 8.5), + maxLines: 1, + overflow: pw.TextOverflow.clip, + ), + pw.SizedBox(height: 1.5), + pw.Text( + productLine, + style: pw.TextStyle(font: font, fontSize: 7.2), + maxLines: 2, + overflow: pw.TextOverflow.clip, + ), + if (codeStr.isNotEmpty || priceStr.isNotEmpty) ...[ + pw.SizedBox(height: 2), + pw.Text( + [ + if (codeStr.isNotEmpty) 'Cod: $codeStr', + if (priceStr.isNotEmpty) priceStr, + ].join(' • '), + style: pw.TextStyle(font: boldFont, fontSize: 7.5), + maxLines: 1, + overflow: pw.TextOverflow.clip, + ), + ], + ], + ); + + final qrWidget = pw.BarcodeWidget( + barcode: pw.Barcode.qrCode(), + data: qrData, + width: qrSize, + height: qrSize, + ); + + if (effectiveH > effectiveW) { + return pw.Column( + mainAxisAlignment: pw.MainAxisAlignment.spaceBetween, + crossAxisAlignment: pw.CrossAxisAlignment.center, + children: [ + infoBlock, + pw.SizedBox(height: 2), + qrWidget, + ], + ); + } + + return pw.Row( + mainAxisAlignment: pw.MainAxisAlignment.spaceBetween, + crossAxisAlignment: pw.CrossAxisAlignment.center, + children: [ + pw.Expanded(child: infoBlock), + pw.SizedBox(width: 2 * PdfPageFormat.mm), + qrWidget, + ], + ); + }, + ), + ); + + return pdf; + } +} diff --git a/lib/features/customers/blocs/customer_form_cubit.dart b/lib/features/customers/blocs/customer_form_cubit.dart index a73bfbe..df98d28 100644 --- a/lib/features/customers/blocs/customer_form_cubit.dart +++ b/lib/features/customers/blocs/customer_form_cubit.dart @@ -65,6 +65,7 @@ class CustomerFormCubit extends Cubit { void updateFields({ String? name, String? phoneNumber, + String? alternativePhoneNumber, String? email, String? note, bool? doNotDisturb, @@ -76,6 +77,8 @@ class CustomerFormCubit extends Cubit { customer: state.customer.copyWith( name: name ?? state.customer.name, phoneNumber: phoneNumber ?? state.customer.phoneNumber, + alternativePhoneNumber: + alternativePhoneNumber ?? state.customer.alternativePhoneNumber, email: email ?? state.customer.email, note: note ?? state.customer.note, doNotDisturb: doNotDisturb ?? state.customer.doNotDisturb, @@ -112,16 +115,19 @@ class CustomerFormCubit extends Cubit { Future quickCreateCustomer({ required String name, String? phone, + String? alternativePhone, String? email, + String? note, required bool isBusiness, String? fiscalCode, }) async { final newCustomer = CustomerModel( name: name, phoneNumber: phone ?? '', + alternativePhoneNumber: alternativePhone ?? '', email: email ?? '', companyId: _sessionCubit.state.company!.id!, - note: '', + note: note ?? '', isBusiness: isBusiness, fiscalCode: fiscalCode?.trim().toUpperCase(), ); diff --git a/lib/features/customers/models/customer_model.dart b/lib/features/customers/models/customer_model.dart index f8674c5..cf2d6eb 100644 --- a/lib/features/customers/models/customer_model.dart +++ b/lib/features/customers/models/customer_model.dart @@ -7,6 +7,7 @@ class CustomerModel extends Equatable { final DateTime? createdAt; final String name; final String phoneNumber; + final String alternativePhoneNumber; final String email; final String note; final DateTime? lastContactDate; @@ -22,6 +23,7 @@ class CustomerModel extends Equatable { this.createdAt, required this.name, required this.phoneNumber, + this.alternativePhoneNumber = '', required this.email, required this.note, this.lastContactDate, @@ -39,6 +41,7 @@ class CustomerModel extends Equatable { createdAt, name, phoneNumber, + alternativePhoneNumber, email, note, lastContactDate, @@ -50,13 +53,13 @@ class CustomerModel extends Equatable { fiscalCode, ]; - factory CustomerModel.empty() => CustomerModel( + factory CustomerModel.empty() => const CustomerModel( name: '', phoneNumber: '', + alternativePhoneNumber: '', email: '', note: '', - companyId: - '', // Dovrebbe essere sempre fornito, ma lasciamo vuoto per sicurezza + companyId: '', ); CustomerModel copyWith({ @@ -64,6 +67,7 @@ class CustomerModel extends Equatable { DateTime? createdAt, String? name, String? phoneNumber, + String? alternativePhoneNumber, String? email, String? note, DateTime? lastContactDate, @@ -79,6 +83,8 @@ class CustomerModel extends Equatable { createdAt: createdAt ?? this.createdAt, name: name ?? this.name, phoneNumber: phoneNumber ?? this.phoneNumber, + alternativePhoneNumber: + alternativePhoneNumber ?? this.alternativePhoneNumber, email: email ?? this.email, note: note ?? this.note, lastContactDate: lastContactDate ?? this.lastContactDate, @@ -98,8 +104,9 @@ class CustomerModel extends Equatable { ? DateTime.parse(map['created_at']) : null, name: (map['name'] as String).myFormat(), - phoneNumber: map['phone_number'], - email: map['email'], + phoneNumber: map['phone_number'] as String? ?? '', + alternativePhoneNumber: map['alternative_phone_number'] as String? ?? '', + email: map['email'] as String? ?? '', note: map['note'] ?? '', lastContactDate: map['last_contact_date'] != null ? DateTime.parse(map['last_contact_date']) @@ -117,11 +124,14 @@ class CustomerModel extends Equatable { ); } + Map toMap() => toJson(); + Map toJson() { return { if (id != null) 'id': id, 'name': name.toLowerCase().trim(), - 'phone_number': phoneNumber, + 'phone_number': phoneNumber.trim(), + 'alternative_phone_number': alternativePhoneNumber.trim(), 'email': email.toLowerCase().trim(), 'note': note, if (lastContactDate != null) diff --git a/lib/features/customers/ui/customer_form_screen.dart b/lib/features/customers/ui/customer_form_screen.dart index 941fb87..0e03f4c 100644 --- a/lib/features/customers/ui/customer_form_screen.dart +++ b/lib/features/customers/ui/customer_form_screen.dart @@ -23,6 +23,7 @@ class _CustomerFormScreenState extends State { // Controller inizializzati con i dati del cliente (se presenti) final TextEditingController _nomeController = TextEditingController(); final TextEditingController _telefonoController = TextEditingController(); + final TextEditingController _telefonoAltController = TextEditingController(); final TextEditingController _emailController = TextEditingController(); final TextEditingController _noteController = TextEditingController(); final TextEditingController _fiscalCodeController = TextEditingController(); @@ -49,6 +50,7 @@ class _CustomerFormScreenState extends State { void dispose() { _nomeController.dispose(); _telefonoController.dispose(); + _telefonoAltController.dispose(); _emailController.dispose(); _noteController.dispose(); _fiscalCodeController.dispose(); @@ -62,6 +64,9 @@ class _CustomerFormScreenState extends State { if (_telefonoController.text.isEmpty) { _telefonoController.text = customer.phoneNumber; } + if (_telefonoAltController.text.isEmpty) { + _telefonoAltController.text = customer.alternativePhoneNumber; + } if (_emailController.text.isEmpty) { _emailController.text = customer.email; } @@ -78,6 +83,7 @@ class _CustomerFormScreenState extends State { context.read().updateFields( name: _nomeController.text.trim(), phoneNumber: _telefonoController.text.trim(), + alternativePhoneNumber: _telefonoAltController.text.trim(), email: _emailController.text.trim(), note: _noteController.text.trim(), fiscalCode: _fiscalCodeController.text.trim(), @@ -166,12 +172,19 @@ class _CustomerFormScreenState extends State { ), const SizedBox(height: 16), FluxTextField( - label: 'Telefono', + label: 'Telefono Principale', icon: Icons.phone_android_outlined, controller: _telefonoController, keyboardType: TextInputType.phone, ), const SizedBox(height: 16), + FluxTextField( + label: 'Recapito Alternativo', + icon: Icons.phone_forwarded_outlined, + controller: _telefonoAltController, + keyboardType: TextInputType.phone, + ), + const SizedBox(height: 16), FluxTextField( label: 'Email', icon: Icons.alternate_email_outlined, diff --git a/lib/features/customers/ui/quick_customer_dialog.dart b/lib/features/customers/ui/quick_customer_dialog.dart index a65ecaa..af7bb9d 100644 --- a/lib/features/customers/ui/quick_customer_dialog.dart +++ b/lib/features/customers/ui/quick_customer_dialog.dart @@ -15,6 +15,7 @@ class QuickCustomerDialog extends StatefulWidget { class _QuickCustomerDialogState extends State { late final TextEditingController _nameCtrl; final _phoneCtrl = TextEditingController(); + final _altPhoneCtrl = TextEditingController(); final _emailCtrl = TextEditingController(); final _noteCtrl = TextEditingController(); bool _isBusiness = false; @@ -33,6 +34,7 @@ class _QuickCustomerDialogState extends State { void dispose() { _nameCtrl.dispose(); _phoneCtrl.dispose(); + _altPhoneCtrl.dispose(); _emailCtrl.dispose(); _noteCtrl.dispose(); _fiscalCodeCtrl.dispose(); @@ -52,7 +54,9 @@ class _QuickCustomerDialogState extends State { isBusiness: _isBusiness, name: _nameCtrl.text.trim(), phone: _phoneCtrl.text.trim(), + alternativePhone: _altPhoneCtrl.text.trim(), email: _emailCtrl.text.trim(), + note: _noteCtrl.text.trim(), fiscalCode: _fiscalCodeCtrl.text.trim().toUpperCase(), ); @@ -117,7 +121,18 @@ class _QuickCustomerDialogState extends State { const SizedBox(height: 8), TextField( controller: _phoneCtrl, - decoration: const InputDecoration(labelText: "Telefono"), + decoration: const InputDecoration( + labelText: "Telefono Principale", + ), + keyboardType: TextInputType.phone, + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 8), + TextField( + controller: _altPhoneCtrl, + decoration: const InputDecoration( + labelText: "Recapito Alternativo (opzionale)", + ), keyboardType: TextInputType.phone, textInputAction: TextInputAction.next, ), diff --git a/lib/features/home/ui/home_screen.dart b/lib/features/home/ui/home_screen.dart index 4148c71..b78e9d8 100644 --- a/lib/features/home/ui/home_screen.dart +++ b/lib/features/home/ui/home_screen.dart @@ -375,6 +375,22 @@ class _HomeScreenState extends State { }, ), SizedBox(width: gap), + QuickActionButton( + icon: Icons.add_shopping_cart_rounded, + label: 'Ordine Cliente', + color: Colors.teal, + compact: isMobile, + onTap: () async { + StaffMemberModel? createdBy = await getStaffMember(context); + if (createdBy == null || !context.mounted) return; + context.pushNamed( + Routes.customerOrderForm, + pathParameters: {'id': 'new'}, + extra: (createdBy: createdBy, order: null), + ); + }, + ), + SizedBox(width: gap), QuickActionButton( icon: Icons.note_add, label: context.l10n.commonNote, diff --git a/lib/features/tickets/blocs/ticket_form_cubit.dart b/lib/features/tickets/blocs/ticket_form_cubit.dart index 53053ee..db46056 100644 --- a/lib/features/tickets/blocs/ticket_form_cubit.dart +++ b/lib/features/tickets/blocs/ticket_form_cubit.dart @@ -1,5 +1,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; +import 'package:flux/features/customers/data/customer_repository.dart'; import 'package:flux/features/customers/models/customer_model.dart'; import 'package:flux/features/master_data/staff/models/staff_member_model.dart'; import 'package:flux/features/tickets/models/ticket_model.dart'; @@ -11,6 +13,8 @@ import 'ticket_form_state.dart'; class TicketFormCubit extends Cubit { final TicketRepository _repository = GetIt.I.get(); + final CustomerRepository _customerRepository = + GetIt.I.get(); final SessionCubit _sessionCubit = GetIt.I.get(); // Costruttore: prepariamo subito il ticket base con i dati di chi lo crea @@ -73,13 +77,18 @@ class TicketFormCubit extends Cubit { /// 2. AGGIORNAMENTO CLIENTE (Usato dal nostro SharedCustomerSection!) void updateCustomer(CustomerModel customer) { + final existingAlt = state.ticket.alternativePhoneNumber?.trim() ?? ''; + final resolvedAlt = existingAlt.isNotEmpty + ? existingAlt + : (customer.alternativePhoneNumber.trim().isNotEmpty + ? customer.alternativePhoneNumber.trim() + : null); emit( state.copyWith( ticket: state.ticket.copyWith( customerId: customer.id, customer: customer, - alternativePhoneNumber: - state.ticket.alternativePhoneNumber ?? customer.phoneNumber, + alternativePhoneNumber: resolvedAlt, ), ), ); @@ -129,6 +138,7 @@ class TicketFormCubit extends Cubit { String? sourceSn, String? sourcePassword, String? alternativePhoneNumber, + ContactPreference? contactPreference, bool? hasCourtesyDevice, String? includedAccessories, String? publicNotes, @@ -153,6 +163,8 @@ class TicketFormCubit extends Cubit { sourceSn: sourceSn ?? state.ticket.sourceSn, alternativePhoneNumber: alternativePhoneNumber ?? state.ticket.alternativePhoneNumber, + contactPreference: + contactPreference ?? state.ticket.contactPreference, hasCourtesyDevice: hasCourtesyDevice ?? state.ticket.hasCourtesyDevice, includedAccessories: @@ -188,6 +200,7 @@ class TicketFormCubit extends Cubit { } else { savedTicket = await _repository.updateTicket(ticketToSave); } + await _syncCustomerAlternativePhone(ticketToSave); emit( state.copyWith( status: TicketFormStatus.success, @@ -368,6 +381,20 @@ class TicketFormCubit extends Cubit { } } + Future _syncCustomerAlternativePhone(TicketModel ticket) async { + final customer = ticket.customer; + final newAlt = ticket.alternativePhoneNumber?.trim() ?? ''; + if (customer == null || customer.id == null || newAlt.isEmpty) return; + if (customer.alternativePhoneNumber.trim() == newAlt) return; + try { + await _customerRepository.updateCustomer( + customer.copyWith(alternativePhoneNumber: newAlt), + ); + } catch (_) { + // Non blocchiamo il salvataggio del ticket se l'aggiornamento anagrafica fallisce + } + } + Future deleteTicket() async { final currentTicket = state.ticket; diff --git a/lib/features/tickets/models/ticket_model.dart b/lib/features/tickets/models/ticket_model.dart index 76ec24b..c45e803 100644 --- a/lib/features/tickets/models/ticket_model.dart +++ b/lib/features/tickets/models/ticket_model.dart @@ -1,4 +1,5 @@ import 'package:equatable/equatable.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; import 'package:flux/core/utils/extensions.dart'; import 'package:flux/features/customers/models/customer_model.dart'; import 'package:flux/features/tickets/models/shipping_document_model.dart'; @@ -106,6 +107,7 @@ class TicketModel extends Equatable { final String? internalNotes; final String? referenceId; final String? alternativePhoneNumber; + final ContactPreference contactPreference; final bool hasCourtesyDevice; final TicketType ticketType; final TicketStatus ticketStatus; @@ -145,6 +147,7 @@ class TicketModel extends Equatable { this.internalNotes, this.referenceId, this.alternativePhoneNumber, + this.contactPreference = ContactPreference.whatsappPrimary, this.hasCourtesyDevice = false, required this.ticketType, this.ticketStatus = TicketStatus.closed, @@ -199,6 +202,7 @@ class TicketModel extends Equatable { String? internalNotes, String? referenceId, String? alternativePhoneNumber, + ContactPreference? contactPreference, bool? hasCourtesyDevice, TicketType? ticketType, TicketStatus? ticketStatus, @@ -240,6 +244,7 @@ class TicketModel extends Equatable { referenceId: referenceId ?? this.referenceId, alternativePhoneNumber: alternativePhoneNumber ?? this.alternativePhoneNumber, + contactPreference: contactPreference ?? this.contactPreference, hasCourtesyDevice: hasCourtesyDevice ?? this.hasCourtesyDevice, ticketType: ticketType ?? this.ticketType, ticketStatus: ticketStatus ?? this.ticketStatus, @@ -292,6 +297,9 @@ class TicketModel extends Equatable { internalNotes: map['internal_notes'] as String?, referenceId: map['reference_id'] as String?, alternativePhoneNumber: map['alternative_phone_number'] as String?, + contactPreference: ContactPreference.fromString( + map['contact_preference'] as String?, + ), hasCourtesyDevice: map['has_courtesy_device'] as bool? ?? false, ticketType: TicketType.fromString(map['ticket_type'] as String), ticketStatus: TicketStatus.fromString(map['ticket_status'] as String), @@ -347,6 +355,7 @@ class TicketModel extends Equatable { 'internal_notes': internalNotes, 'reference_id': referenceId, 'alternative_phone_number': alternativePhoneNumber, + 'contact_preference': contactPreference.value, 'has_courtesy_device': hasCourtesyDevice, 'ticket_type': ticketType.value, 'ticket_status': ticketStatus.value, @@ -381,6 +390,7 @@ class TicketModel extends Equatable { publicNotes, internalNotes, alternativePhoneNumber, + contactPreference, hasCourtesyDevice, ticketType, ticketStatus, diff --git a/lib/features/tickets/ui/ticket_form_screen.dart b/lib/features/tickets/ui/ticket_form_screen.dart index a6dbc51..12c8b41 100644 --- a/lib/features/tickets/ui/ticket_form_screen.dart +++ b/lib/features/tickets/ui/ticket_form_screen.dart @@ -5,6 +5,7 @@ import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; import 'package:flux/core/routes/routes.dart'; import 'package:flux/core/widgets/shared_forms/attachments_section.dart'; +import 'package:flux/core/widgets/shared_forms/contact_preference_section.dart'; import 'package:flux/core/widgets/shared_forms/customer_section.dart'; import 'package:flux/core/widgets/shared_forms/model_section.dart'; import 'package:flux/core/widgets/staff_selector_modal.dart'; @@ -679,16 +680,25 @@ class _TicketFormScreenState extends State { const Divider(height: 32), */ SharedCustomerSection( customer: ticket.customer, - onCustomerSelected: (customer) => - context.read().updateCustomer(customer), + onCustomerSelected: (customer) { + if (_altPhoneCtrl.text.trim().isEmpty && + customer.alternativePhoneNumber.trim().isNotEmpty) { + _altPhoneCtrl.text = customer.alternativePhoneNumber.trim(); + } + context.read().updateCustomer(customer); + }, ), const SizedBox(height: 16), - TextFormField( - controller: _altPhoneCtrl, - decoration: const InputDecoration( - labelText: 'Recapito Alternativo', - prefixIcon: Icon(Icons.phone), - ), + ContactPreferenceSection( + selectedPreference: ticket.contactPreference, + customer: ticket.customer, + alternativePhoneController: _altPhoneCtrl, + alwaysShowAlternativePhone: true, + onPreferenceChanged: (pref) { + context.read().updateFields( + contactPreference: pref, + ); + }, ), ], ); diff --git a/lib/service_locator.dart b/lib/service_locator.dart index 08bec77..bf1eecd 100644 --- a/lib/service_locator.dart +++ b/lib/service_locator.dart @@ -5,6 +5,8 @@ import 'package:flux/core/theme/bloc/theme_bloc.dart'; import 'package:flux/features/attachments/data/attachments_repository.dart'; import 'package:flux/features/auth/bloc/auth_cubit.dart'; import 'package:flux/features/company/data/company_repository.dart'; +import 'package:flux/features/customer_orders/blocs/customer_order_list_cubit.dart'; +import 'package:flux/features/customer_orders/data/customer_orders_repository.dart'; import 'package:flux/features/customers/blocs/customers_list_cubit.dart'; import 'package:flux/features/customers/data/customer_repository.dart'; import 'package:flux/features/master_data/products/blocs/product_cubit.dart'; @@ -60,6 +62,9 @@ Future init() async { sl.registerLazySingleton(() => CoreRepository()); sl.registerLazySingleton(() => StoreRepository()); sl.registerLazySingleton(() => CustomerRepository()); + sl.registerLazySingleton( + () => CustomerOrdersRepository(), + ); sl.registerLazySingleton(() => ProductRepository()); sl.registerLazySingleton(() => StaffRepository()); sl.registerLazySingleton(() => OperationsRepository()); @@ -103,4 +108,5 @@ Future init() async { sl.registerFactory(() => TrackingCubit()); sl.registerFactory(() => NotesCubit()); sl.registerFactory(() => TargetListCubit()); + sl.registerFactory(() => CustomerOrderListCubit()); } diff --git a/pubspec.yaml b/pubspec.yaml index 8d4ed5f..71ded02 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,7 +1,7 @@ name: flux description: "Gestione attività negozio di telefonia" publish_to: 'none' -version: 2.6.0+94 +version: 2.7.0+95 environment: sdk: ^3.11.3 diff --git a/supabase/migrations/20261202_customer_orders.sql b/supabase/migrations/20261202_customer_orders.sql new file mode 100644 index 0000000..f644f48 --- /dev/null +++ b/supabase/migrations/20261202_customer_orders.sql @@ -0,0 +1,92 @@ +-- ========================================================================= +-- MIGRAZIONE ORDINI CLIENTI, RECAPITO ALTERNATIVO & MODALITÀ AVVISO +-- ========================================================================= + +-- 1. Aggiunta recapito alternativo ai Clienti +ALTER TABLE public.customers +ADD COLUMN IF NOT EXISTS alternative_phone_number text DEFAULT ''; + +-- 2. Aggiunta modalità di avviso preferita ai Ticket di Assistenza +ALTER TABLE public.tickets +ADD COLUMN IF NOT EXISTS contact_preference text DEFAULT 'whatsapp_primary'; + +-- 3. Creazione tabella Ordini Clienti (customer_orders) +CREATE TABLE IF NOT EXISTS public.customer_orders ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now(), + order_date timestamptz NOT NULL DEFAULT now(), + company_id uuid NOT NULL REFERENCES public.companies(id) ON DELETE CASCADE, + store_id uuid REFERENCES public.stores(id) ON DELETE SET NULL, + created_by_id uuid REFERENCES public.staff_members(id) ON DELETE SET NULL, + customer_id uuid REFERENCES public.customers(id) ON DELETE SET NULL, + product_description text NOT NULL DEFAULT '', + quantity integer NOT NULL DEFAULT 1, + notes text NOT NULL DEFAULT '', + price numeric(10, 2) NOT NULL DEFAULT 0, + deposit numeric(10, 2) NOT NULL DEFAULT 0, + external_code text NOT NULL DEFAULT '', + status text NOT NULL DEFAULT 'to_order', + tags text[] NOT NULL DEFAULT '{}', + contact_preference text NOT NULL DEFAULT 'whatsapp_primary', + alternative_phone_number text, + customer_notified boolean NOT NULL DEFAULT false, + customer_notified_at timestamptz +); + +-- Indici per filtri rapidi (azienda, stato, date, etichette GIN) +CREATE INDEX IF NOT EXISTS idx_customer_orders_company_status + ON public.customer_orders(company_id, status); + +CREATE INDEX IF NOT EXISTS idx_customer_orders_order_date + ON public.customer_orders(company_id, order_date DESC); + +CREATE INDEX IF NOT EXISTS idx_customer_orders_tags_gin + ON public.customer_orders USING GIN (tags); + +-- 4. Collegamento allegati (attachments) agli Ordini Clienti +ALTER TABLE public.attachments +ADD COLUMN IF NOT EXISTS customer_order_id uuid REFERENCES public.customer_orders(id) ON DELETE CASCADE; + +CREATE INDEX IF NOT EXISTS idx_attachments_customer_order_id + ON public.attachments(customer_order_id); + +-- 5. Trigger automatico per updated_at su customer_orders +CREATE OR REPLACE FUNCTION public.set_customer_orders_updated_at() +RETURNS TRIGGER AS $$ +BEGIN + NEW.updated_at = now(); + RETURN NEW; +END; +$$ LANGUAGE plpgsql; + +DROP TRIGGER IF EXISTS trg_customer_orders_updated_at ON public.customer_orders; + +CREATE TRIGGER trg_customer_orders_updated_at +BEFORE UPDATE ON public.customer_orders +FOR EACH ROW +EXECUTE FUNCTION public.set_customer_orders_updated_at(); + +-- 6. Row Level Security (RLS) per multi-tenancy aziendale +ALTER TABLE public.customer_orders ENABLE ROW LEVEL SECURITY; + +DROP POLICY IF EXISTS "Accesso ordini per membri azienda" ON public.customer_orders; + +CREATE POLICY "Accesso ordini per membri azienda" +ON public.customer_orders +FOR ALL +TO authenticated +USING ( + company_id IN ( + SELECT sm.company_id FROM public.staff_members sm WHERE sm.user_id = auth.uid() + UNION + SELECT c.id FROM public.companies c WHERE c.user_id = auth.uid() + ) +) +WITH CHECK ( + company_id IN ( + SELECT sm.company_id FROM public.staff_members sm WHERE sm.user_id = auth.uid() + UNION + SELECT c.id FROM public.companies c WHERE c.user_id = auth.uid() + ) +); diff --git a/test/features/customer_orders/models/customer_order_model_test.dart b/test/features/customer_orders/models/customer_order_model_test.dart new file mode 100644 index 0000000..62733e8 --- /dev/null +++ b/test/features/customer_orders/models/customer_order_model_test.dart @@ -0,0 +1,142 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:flux/core/enums_and_consts/contact_preference.dart'; +import 'package:flux/features/customer_orders/models/customer_order_model.dart'; +import 'package:flux/features/customer_orders/models/customer_order_status.dart'; +import 'package:flux/features/customers/models/customer_model.dart'; + +void main() { + group('ContactPreference enum', () { + test('fromString resolves values and falls back to whatsappPrimary', () { + expect( + ContactPreference.fromString('whatsapp_alternative'), + ContactPreference.whatsappAlternative, + ); + expect( + ContactPreference.fromString('call_primary'), + ContactPreference.callPrimary, + ); + expect( + ContactPreference.fromString('call_alternative'), + ContactPreference.callAlternative, + ); + expect( + ContactPreference.fromString('email'), + ContactPreference.email, + ); + expect( + ContactPreference.fromString(null), + ContactPreference.whatsappPrimary, + ); + }); + }); + + group('CustomerOrderStatus & CustomerOrderQuickFilter', () { + test('active quick filter includes only to_order, ordered, arrived', () { + expect(CustomerOrderQuickFilter.active.dbStatuses, [ + 'to_order', + 'ordered', + 'arrived', + ]); + expect(CustomerOrderQuickFilter.all.dbStatuses, isNull); + }); + + test('fromString parses status values cleanly', () { + expect( + CustomerOrderStatus.fromString('arrived'), + CustomerOrderStatus.arrived, + ); + expect( + CustomerOrderStatus.fromString('delivered'), + CustomerOrderStatus.delivered, + ); + expect( + CustomerOrderStatus.fromString('unknown'), + CustomerOrderStatus.toOrder, + ); + }); + }); + + group('CustomerOrderModel', () { + test('computes remainingAmount, deepLinkUrl, and effectiveContactDestination', () { + const customer = CustomerModel( + id: 'cust-1', + name: 'Mario Rossi', + phoneNumber: '3331112233', + alternativePhoneNumber: '3479998877', + email: 'mario@example.com', + note: '', + companyId: 'comp-1', + ); + + final order = CustomerOrderModel( + id: 'ord-123', + orderDate: DateTime(2026, 12, 2, 10, 30), + companyId: 'comp-1', + customerId: 'cust-1', + customer: customer, + productDescription: 'Cover MagSafe iPhone 16 Pro', + quantity: 2, + price: 29.90, + deposit: 10.00, + externalCode: 'ART-8891', + status: CustomerOrderStatus.arrived, + tags: const ['Amazon', 'Urgente'], + contactPreference: ContactPreference.whatsappAlternative, + ); + + expect(order.remainingAmount, closeTo(19.90, 0.001)); + expect( + order.deepLinkUrl, + 'https://flux.catelli.it/orders/form/ord-123', + ); + expect(order.effectiveContactDestination, '3479998877'); + + final emailOrder = order.copyWith( + contactPreference: ContactPreference.email, + ); + expect(emailOrder.effectiveContactDestination, 'mario@example.com'); + }); + + test('fromMap and toMap round-trip fields accurately', () { + final map = { + 'id': 'ord-99', + 'created_at': '2026-12-02T09:00:00.000Z', + 'updated_at': '2026-12-02T11:30:00.000Z', + 'order_date': '2026-12-02T09:00:00.000Z', + 'company_id': 'comp-1', + 'store_id': 'store-1', + 'customer_id': 'cust-1', + 'product_description': 'Vetro Temperato S24', + 'quantity': 0, // clamped to 1 + 'notes': 'Con cornice nera', + 'price': 15, + 'deposit': 5.5, + 'external_code': 'VET-024', + 'status': 'ordered', + 'tags': ['FornitoreB', 'Display'], + 'contact_preference': 'call_alternative', + 'alternative_phone_number': '0299887766', + 'customer_notified': true, + 'customer_notified_at': '2026-12-02T11:29:00.000Z', + }; + + final parsed = CustomerOrderModel.fromMap(map); + expect(parsed.id, 'ord-99'); + expect(parsed.quantity, 1); + expect(parsed.price, 15.0); + expect(parsed.deposit, 5.5); + expect(parsed.externalCode, 'VET-024'); + expect(parsed.status, CustomerOrderStatus.ordered); + expect(parsed.tags, ['FornitoreB', 'Display']); + expect(parsed.contactPreference, ContactPreference.callAlternative); + expect(parsed.customerNotified, isTrue); + expect(parsed.customerNotifiedAt, isNotNull); + + final serialized = parsed.toMap(); + expect(serialized['external_code'], 'VET-024'); + expect(serialized['status'], 'ordered'); + expect(serialized['contact_preference'], 'call_alternative'); + expect(serialized['tags'], ['FornitoreB', 'Display']); + }); + }); +}