diff --git a/lib/features/tickets/blocs/mark_ticket_returned_cubit.dart b/lib/features/tickets/blocs/mark_ticket_returned_cubit.dart new file mode 100644 index 0000000..349c842 --- /dev/null +++ b/lib/features/tickets/blocs/mark_ticket_returned_cubit.dart @@ -0,0 +1,183 @@ +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/services/email/email_service.dart'; +import 'package:flux/core/services/whatsapp/whatsapp_service.dart'; +import 'package:flux/features/tickets/data/ticket_repository.dart'; +import 'package:flux/features/tickets/models/ticket_model.dart'; +import 'package:flux/features/tickets/models/ticket_notification_result.dart'; +import 'package:flux/features/tickets/utils/ticket_notification_helper.dart'; +import 'package:flux/features/tracking/data/tracking_repository.dart'; +import 'package:flux/features/tracking/models/tracking_model.dart'; +import 'package:flux/service_locator.dart'; + +part 'mark_ticket_returned_state.dart'; + +class MarkTicketReturnedCubit extends Cubit { + final TicketRepository _ticketRepository = sl(); + final TrackingRepository _trackingRepository = sl(); + final WhatsAppService _whatsAppService = sl(); + final EmailService _emailService = sl(); + final SessionCubit _sessionCubit = sl(); + + String _lastPublicNote = ''; + + MarkTicketReturnedCubit(TicketModel ticket) + : super( + MarkTicketReturnedState( + ticket: ticket, + selectedResult: ticket.ticketResult ?? TicketResult.success, + sendAutoNotification: + ticket.contactPreference.isWhatsapp || + ticket.contactPreference.isEmail, + ), + ); + + void selectResult(TicketResult result) { + emit(state.copyWith(selectedResult: result)); + } + + void toggleSendAutoNotification(bool enabled) { + emit(state.copyWith(sendAutoNotification: enabled)); + } + + Future confirmReturn({ + required double finalPrice, + required String publicNotes, + }) async { + final current = state.ticket; + if (current.id == null || current.id!.isEmpty) return; + + emit( + state.copyWith( + step: MarkTicketReturnedStep.submitting, + clearErrorMessage: true, + clearNotificationResult: true, + ), + ); + + _lastPublicNote = publicNotes.trim(); + + try { + final updated = current.copyWith( + ticketStatus: TicketStatus.ready, + ticketResult: state.selectedResult, + customerPrice: finalPrice, + returnedAt: DateTime.now(), + resolutionNotes: _lastPublicNote.isNotEmpty + ? _lastPublicNote + : current.resolutionNotes, + ); + + await _ticketRepository.updateTicket(updated); + + final esitoText = state.selectedResult == TicketResult.success + ? 'Riparato con successo' + : 'Non riparabile / Intervento non eseguito'; + final timelineMessage = _lastPublicNote.isNotEmpty + ? 'Dispositivo rientrato dal centro assistenza ($esitoText). $_lastPublicNote È pronto per il ritiro in negozio.' + : 'Dispositivo rientrato dal centro assistenza ($esitoText). È pronto per il ritiro in negozio.'; + + await _trackingRepository.logQuickEvent( + companyId: current.companyId, + message: timelineMessage, + type: TrackingType.statusChange, + parentId: current.id!, + parentType: TrackingParentType.ticket, + staffId: + current.assignedToId ?? + _sessionCubit.state.currentStaffMember?.id ?? + '', + isInternal: false, + ); + + TicketNotificationResult? notificationResult; + if (state.sendAutoNotification && state.supportsAutoNotification) { + notificationResult = await _sendReadyNotification( + updated, + publicNote: _lastPublicNote, + ); + } + + if (!isClosed) { + emit( + state.copyWith( + step: MarkTicketReturnedStep.completed, + ticket: updated, + notificationResult: notificationResult, + clearErrorMessage: true, + ), + ); + } + } catch (e) { + if (!isClosed) { + emit( + state.copyWith( + step: MarkTicketReturnedStep.editing, + errorMessage: e.toString(), + ), + ); + } + } + } + + Future retryNotification() async { + if (state.isBusy || !state.supportsAutoNotification) return; + emit(state.copyWith(step: MarkTicketReturnedStep.retryingNotification)); + + final result = await _sendReadyNotification( + state.ticket, + publicNote: _lastPublicNote, + ); + + if (!isClosed) { + emit( + state.copyWith( + step: MarkTicketReturnedStep.completed, + notificationResult: result, + ), + ); + } + } + + Future _sendReadyNotification( + TicketModel ticket, { + String? publicNote, + }) async { + if (ticket.contactPreference.isWhatsapp) { + final phone = ticket.effectiveContactDestination; + final message = TicketNotificationHelper.buildStatusUpdateWhatsAppMessage( + ticket, + publicNote: publicNote, + ); + final waRes = await _whatsAppService.sendMessage( + phone: phone, + message: message, + linkPreview: true, + ); + return TicketNotificationResult.fromWhatsApp( + waRes, + fallbackDestination: phone, + contextLabel: 'Avviso ritiro', + ); + } + + final email = ticket.effectiveContactDestination; + final payload = TicketNotificationHelper.buildStatusUpdateEmail( + ticket, + publicNote: publicNote, + ); + final emailRes = await _emailService.sendEmail( + to: email, + subject: payload.subject, + text: payload.text, + html: payload.html, + account: EmailSenderAccount.assistenza, + ); + return TicketNotificationResult.fromEmail( + emailRes, + fallbackDestination: email, + contextLabel: 'Avviso ritiro', + ); + } +} diff --git a/lib/features/tickets/blocs/mark_ticket_returned_state.dart b/lib/features/tickets/blocs/mark_ticket_returned_state.dart new file mode 100644 index 0000000..44f2d07 --- /dev/null +++ b/lib/features/tickets/blocs/mark_ticket_returned_state.dart @@ -0,0 +1,67 @@ +part of 'mark_ticket_returned_cubit.dart'; + +enum MarkTicketReturnedStep { + editing, + submitting, + retryingNotification, + completed, +} + +class MarkTicketReturnedState extends Equatable { + final MarkTicketReturnedStep step; + final TicketModel ticket; + final TicketResult selectedResult; + final bool sendAutoNotification; + final TicketNotificationResult? notificationResult; + final String? errorMessage; + + const MarkTicketReturnedState({ + this.step = MarkTicketReturnedStep.editing, + required this.ticket, + this.selectedResult = TicketResult.success, + required this.sendAutoNotification, + this.notificationResult, + this.errorMessage, + }); + + bool get supportsAutoNotification => + ticket.contactPreference.isWhatsapp || ticket.contactPreference.isEmail; + + bool get isBusy => + step == MarkTicketReturnedStep.submitting || + step == MarkTicketReturnedStep.retryingNotification; + + MarkTicketReturnedState copyWith({ + MarkTicketReturnedStep? step, + TicketModel? ticket, + TicketResult? selectedResult, + bool? sendAutoNotification, + TicketNotificationResult? notificationResult, + bool clearNotificationResult = false, + String? errorMessage, + bool clearErrorMessage = false, + }) { + return MarkTicketReturnedState( + step: step ?? this.step, + ticket: ticket ?? this.ticket, + selectedResult: selectedResult ?? this.selectedResult, + sendAutoNotification: sendAutoNotification ?? this.sendAutoNotification, + notificationResult: clearNotificationResult + ? null + : (notificationResult ?? this.notificationResult), + errorMessage: clearErrorMessage + ? null + : (errorMessage ?? this.errorMessage), + ); + } + + @override + List get props => [ + step, + ticket, + selectedResult, + sendAutoNotification, + notificationResult, + errorMessage, + ]; +} diff --git a/lib/features/tickets/blocs/ticket_shipping_cubit.dart b/lib/features/tickets/blocs/ticket_shipping_cubit.dart index bbd6b1a..0d0bee5 100644 --- a/lib/features/tickets/blocs/ticket_shipping_cubit.dart +++ b/lib/features/tickets/blocs/ticket_shipping_cubit.dart @@ -1,6 +1,9 @@ import 'package:equatable/equatable.dart'; +import 'package:flutter/foundation.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flux/core/blocs/session/session_cubit.dart'; +import 'package:flux/core/services/email/email_service.dart'; +import 'package:flux/core/services/whatsapp/whatsapp_service.dart'; import 'package:flux/features/tickets/data/tickets_shipping_repository.dart'; import 'package:flux/features/tickets/models/shipping_document_model.dart'; import 'package:flux/features/master_data/providers/models/provider_location_model.dart'; @@ -8,7 +11,10 @@ import 'package:flux/features/master_data/providers/models/provider_model.dart'; import 'package:flux/features/settings/document_sequence/data/document_sequence_repository.dart'; import 'package:flux/features/settings/document_sequence/models/document_sequence_model.dart'; import 'package:flux/features/tickets/models/ticket_model.dart'; +import 'package:flux/features/tickets/utils/ticket_notification_helper.dart'; import 'package:flux/features/tickets/utils/ticket_shipping_pdf_service.dart'; +import 'package:flux/features/tracking/data/tracking_repository.dart'; +import 'package:flux/features/tracking/models/tracking_model.dart'; import 'package:get_it/get_it.dart'; import 'package:printing/printing.dart'; @@ -200,6 +206,14 @@ class TicketShippingCubit extends Cubit { pdfBytes: pdfBytes, newTicketStatus: newTicketStatus, ); + + // Log pubblico in timeline + notifica WhatsApp/Email per ogni ticket spedito + await _notifyShippedTickets( + tickets: state.tickets, + newTicketStatus: newTicketStatus, + providerName: provider.name, + ); + await Printing.layoutPdf( onLayout: (format) async => pdfBytes, name: 'DDT_${state.document.docNumber}.pdf', @@ -211,4 +225,72 @@ class TicketShippingCubit extends Cubit { } } } + + Future _notifyShippedTickets({ + required List tickets, + required TicketStatus newTicketStatus, + required String providerName, + }) async { + final trackingRepo = GetIt.I(); + final whatsApp = GetIt.I(); + final emailService = GetIt.I(); + final staffId = GetIt.I().state.currentStaffMember?.id ?? ''; + + for (final rawTicket in tickets) { + if (rawTicket.id == null || rawTicket.id!.isEmpty) continue; + final ticket = rawTicket.copyWith(ticketStatus: newTicketStatus); + + try { + await trackingRepo.logQuickEvent( + companyId: ticket.companyId, + message: + 'Dispositivo spedito al centro assistenza ($providerName). Ti aggiorneremo non appena rientra in negozio.', + type: TrackingType.statusChange, + parentId: ticket.id!, + parentType: TrackingParentType.ticket, + staffId: staffId, + isInternal: false, + ); + } catch (e) { + debugPrint('Errore log timeline spedizione ticket ${ticket.id}: $e'); + } + + try { + if (ticket.contactPreference.isWhatsapp) { + final phone = ticket.effectiveContactDestination; + if (phone.isNotEmpty) { + final msg = + TicketNotificationHelper.buildStatusUpdateWhatsAppMessage( + ticket, + publicNote: + 'Il dispositivo è stato spedito al centro assistenza. Ti aggiorneremo non appena rientra in negozio.', + ); + await whatsApp.sendMessage( + phone: phone, + message: msg, + linkPreview: true, + ); + } + } else if (ticket.contactPreference.isEmail) { + final email = ticket.effectiveContactDestination; + if (email.isNotEmpty) { + final payload = TicketNotificationHelper.buildStatusUpdateEmail( + ticket, + publicNote: + 'Il dispositivo è stato spedito al centro assistenza. Ti aggiorneremo non appena rientra in negozio.', + ); + await emailService.sendEmail( + to: email, + subject: payload.subject, + text: payload.text, + html: payload.html, + account: EmailSenderAccount.assistenza, + ); + } + } + } catch (e) { + debugPrint('Errore notifica spedizione ticket ${ticket.id}: $e'); + } + } + } } diff --git a/lib/features/tickets/ui/ticket_form_screen.dart b/lib/features/tickets/ui/ticket_form_screen.dart index 5570d6b..b99a3eb 100644 --- a/lib/features/tickets/ui/ticket_form_screen.dart +++ b/lib/features/tickets/ui/ticket_form_screen.dart @@ -21,6 +21,7 @@ import 'package:flux/features/tickets/models/ticket_model.dart'; import 'package:flux/core/widgets/shared_forms/staff_section.dart'; import 'package:flux/features/tickets/models/ticket_status_extension.dart'; import 'package:flux/features/tickets/ui/ticket_timeline_section.dart'; +import 'package:flux/features/tickets/ui/widgets/mark_ticket_returned_sheet.dart'; import 'package:flux/features/tickets/utils/ticket_pdf_service.dart'; import 'package:flux/features/tracking/blocs/tracking_cubit.dart'; import 'package:flux/features/tracking/models/tracking_model.dart'; @@ -698,6 +699,45 @@ class _TicketFormScreenState extends State { ), ), ], + if (ticket.ticketStatus == TicketStatus.waitingForReturn && + ticket.id != null) ...[ + Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8.0, + vertical: 8.0, + ), + child: FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: Colors.green.shade600, + foregroundColor: Colors.white, + ), + onPressed: () async { + final updated = await showMarkTicketReturnedSheet( + context, + ticket, + ); + if (updated != null && context.mounted) { + await context.read().initForm( + existingTicket: updated, + ); + if (!context.mounted) return; + _priceCtrl.text = updated.customerPrice > 0 + ? updated.customerPrice.toStringAsFixed(2) + : ''; + context.read().loadTrackings( + ticket.id!, + TrackingParentType.ticket, + ); + context.read().loadTickets( + refresh: true, + ); + } + }, + icon: const Icon(Icons.assignment_returned_rounded), + label: const Text('Segna Rientrato'), + ), + ), + ], if (ticket.ticketStatus == TicketStatus.inProgress) ...[ Padding( padding: const EdgeInsets.symmetric( diff --git a/lib/features/tickets/ui/widgets/mark_ticket_returned_sheet.dart b/lib/features/tickets/ui/widgets/mark_ticket_returned_sheet.dart new file mode 100644 index 0000000..3360623 --- /dev/null +++ b/lib/features/tickets/ui/widgets/mark_ticket_returned_sheet.dart @@ -0,0 +1,552 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_bloc/flutter_bloc.dart'; +import 'package:flux/features/tickets/blocs/mark_ticket_returned_cubit.dart'; +import 'package:flux/features/tickets/models/ticket_model.dart'; +import 'package:intl/intl.dart'; + +/// Apre la BottomSheet rapida per segnare un ticket spedito come rientrato +/// dal centro assistenza, aggiornare la timeline pubblica e avvisare il cliente. +/// Restituisce il [TicketModel] aggiornato se confermato, altrimenti `null`. +Future showMarkTicketReturnedSheet( + BuildContext context, + TicketModel ticket, +) { + return showModalBottomSheet( + context: context, + isScrollControlled: true, + useSafeArea: true, + showDragHandle: true, + shape: const RoundedRectangleBorder( + borderRadius: BorderRadius.vertical(top: Radius.circular(20)), + ), + builder: (_) => BlocProvider( + create: (_) => MarkTicketReturnedCubit(ticket), + child: _MarkTicketReturnedSheetBody(initialTicket: ticket), + ), + ); +} + +class _MarkTicketReturnedSheetBody extends StatefulWidget { + final TicketModel initialTicket; + + const _MarkTicketReturnedSheetBody({required this.initialTicket}); + + @override + State<_MarkTicketReturnedSheetBody> createState() => + _MarkTicketReturnedSheetBodyState(); +} + +class _MarkTicketReturnedSheetBodyState + extends State<_MarkTicketReturnedSheetBody> { + late final TextEditingController _priceCtrl; + final TextEditingController _notesCtrl = TextEditingController(); + + final NumberFormat _currencyFmt = NumberFormat.currency( + locale: 'it_IT', + symbol: '€', + ); + + @override + void initState() { + super.initState(); + _priceCtrl = TextEditingController( + text: widget.initialTicket.customerPrice > 0 + ? widget.initialTicket.customerPrice.toStringAsFixed(2) + : '', + ); + } + + @override + void dispose() { + _priceCtrl.dispose(); + _notesCtrl.dispose(); + super.dispose(); + } + + double _parsePrice() { + final normalized = _priceCtrl.text.trim().replaceAll(',', '.'); + return double.tryParse(normalized) ?? 0.0; + } + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final bottomInset = MediaQuery.of(context).viewInsets.bottom; + + return BlocBuilder( + builder: (context, state) { + final isCompleted = + state.step == MarkTicketReturnedStep.completed || + state.step == MarkTicketReturnedStep.retryingNotification; + + return Padding( + padding: EdgeInsets.fromLTRB(20, 4, 20, 20 + bottomInset), + child: SingleChildScrollView( + child: Center( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 540), + child: isCompleted + ? _buildCompletedView(context, theme, state) + : _buildEditingView(context, theme, state), + ), + ), + ), + ); + }, + ); + } + + Widget _buildEditingView( + BuildContext context, + ThemeData theme, + MarkTicketReturnedState state, + ) { + final ticket = state.ticket; + final pref = ticket.contactPreference; + final dest = ticket.effectiveContactDestination; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + // Header + Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.assignment_returned_rounded, + color: Colors.green, + size: 24, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Segna Rientrato e Pronto', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + const SizedBox(height: 2), + Text( + '${ticket.customer?.name ?? 'Cliente'} • ${ticket.targetModelName ?? ticket.ticketType.displayValue}${ticket.referenceId?.isNotEmpty == true ? ' (#${ticket.referenceId})' : ''}', + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + maxLines: 2, + overflow: TextOverflow.ellipsis, + ), + ], + ), + ), + ], + ), + const SizedBox(height: 18), + + // Esito lavorazione + const Text( + 'Esito riparazione:', + style: TextStyle(fontWeight: FontWeight.bold, fontSize: 13.5), + ), + const SizedBox(height: 8), + Row( + children: [ + Expanded( + child: ChoiceChip( + label: const Center(child: Text('Riparato (OK)')), + selectedColor: Colors.green.withValues(alpha: 0.2), + selected: state.selectedResult == TicketResult.success, + onSelected: state.isBusy + ? null + : (selected) { + if (selected) { + context.read().selectResult( + TicketResult.success, + ); + } + }, + ), + ), + const SizedBox(width: 10), + Expanded( + child: ChoiceChip( + label: const Center(child: Text('Non Riparato (KO)')), + selectedColor: Colors.red.withValues(alpha: 0.2), + selected: state.selectedResult == TicketResult.failure, + onSelected: state.isBusy + ? null + : (selected) { + if (selected) { + context.read().selectResult( + TicketResult.failure, + ); + } + }, + ), + ), + ], + ), + const SizedBox(height: 16), + + // Totale al ritiro + TextField( + controller: _priceCtrl, + enabled: !state.isBusy, + keyboardType: const TextInputType.numberWithOptions(decimal: true), + inputFormatters: [ + FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')), + ], + decoration: const InputDecoration( + labelText: 'Totale al ritiro (€)', + hintText: '0.00 (lascia vuoto se in garanzia / € 0)', + prefixIcon: Icon(Icons.euro_rounded), + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 14), + + // Note pubbliche per il cliente + TextField( + controller: _notesCtrl, + enabled: !state.isBusy, + maxLines: 2, + decoration: const InputDecoration( + labelText: 'Note pubbliche per il cliente (opzionale)', + hintText: 'Es. Sostituito display in garanzia...', + prefixIcon: Icon(Icons.notes_rounded), + border: OutlineInputBorder(), + ), + ), + const SizedBox(height: 16), + + // Sezione Avviso Cliente + if (state.supportsAutoNotification) + Container( + decoration: BoxDecoration( + color: pref.color.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: pref.color.withValues(alpha: 0.35)), + ), + child: SwitchListTile( + value: state.sendAutoNotification, + onChanged: state.isBusy + ? null + : (val) => context + .read() + .toggleSendAutoNotification(val), + secondary: pref.buildIcon(size: 20), + title: Text( + pref.isEmail + ? 'Invia avviso ritiro via Email' + : 'Invia avviso ritiro su WhatsApp', + style: const TextStyle( + fontWeight: FontWeight.w600, + fontSize: 14, + ), + ), + subtitle: Text( + dest.isNotEmpty + ? 'Destinatario: $dest' + : (pref.isEmail + ? 'Attenzione: indirizzo email mancante' + : 'Attenzione: numero di telefono mancante'), + style: TextStyle( + fontSize: 12, + color: dest.isNotEmpty ? null : theme.colorScheme.error, + ), + ), + ), + ) + else + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: pref.color.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: pref.color.withValues(alpha: 0.35)), + ), + child: Row( + children: [ + pref.buildIcon(size: 18), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Preferenza cliente: ${pref.label}${dest.isNotEmpty ? ' ($dest)' : ''}. L\'avviso andrà effettuato manualmente.', + style: const TextStyle(fontSize: 12.5), + ), + ), + ], + ), + ), + + if (state.errorMessage != null) ...[ + const SizedBox(height: 12), + Container( + padding: const EdgeInsets.all(12), + decoration: BoxDecoration( + color: theme.colorScheme.errorContainer, + borderRadius: BorderRadius.circular(10), + ), + child: Text( + state.errorMessage!, + style: TextStyle( + color: theme.colorScheme.onErrorContainer, + fontSize: 13, + ), + ), + ), + ], + + const SizedBox(height: 20), + + Row( + children: [ + Expanded( + child: OutlinedButton( + onPressed: state.isBusy ? null : () => Navigator.pop(context), + child: const Text('Annulla'), + ), + ), + const SizedBox(width: 12), + Expanded( + flex: 2, + child: FilledButton.icon( + style: FilledButton.styleFrom( + backgroundColor: Colors.green.shade600, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric(vertical: 14), + ), + onPressed: state.isBusy + ? null + : () => context + .read() + .confirmReturn( + finalPrice: _parsePrice(), + publicNotes: _notesCtrl.text, + ), + icon: state.isBusy + ? const SizedBox( + width: 18, + height: 18, + child: CircularProgressIndicator( + strokeWidth: 2, + color: Colors.white, + ), + ) + : const Icon(Icons.check_rounded), + label: Text( + state.isBusy ? 'Salvataggio...' : 'Conferma Rientro', + ), + ), + ), + ], + ), + ], + ); + } + + Widget _buildCompletedView( + BuildContext context, + ThemeData theme, + MarkTicketReturnedState state, + ) { + final ticket = state.ticket; + final result = state.notificationResult; + final isRetrying = state.step == MarkTicketReturnedStep.retryingNotification; + + return Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Row( + children: [ + Container( + padding: const EdgeInsets.all(10), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(12), + ), + child: const Icon( + Icons.check_circle_rounded, + color: Colors.green, + size: 26, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Dispositivo rientrato e Pronto!', + style: theme.textTheme.titleMedium?.copyWith( + fontWeight: FontWeight.bold, + ), + ), + Text( + [ + ticket.ticketResult?.displayValue ?? 'Pronto', + if (ticket.customerPrice > 0) + 'Totale: ${_currencyFmt.format(ticket.customerPrice)}', + ].join(' • '), + style: theme.textTheme.bodySmall?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 16), + + if (result != null && result.success) + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.green.withValues(alpha: 0.12), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.green.withValues(alpha: 0.5)), + ), + child: Row( + children: [ + Icon( + ticket.contactPreference.isEmail + ? Icons.mark_email_read_rounded + : Icons.mark_chat_read_rounded, + color: Colors.green, + size: 24, + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Avviso ${result.channel.label} inviato con successo', + style: const TextStyle( + fontWeight: FontWeight.bold, + color: Colors.green, + ), + ), + const SizedBox(height: 2), + Text( + 'Cliente avvisato su ${result.destination ?? ticket.effectiveContactDestination}.', + style: const TextStyle(fontSize: 12.5), + ), + ], + ), + ), + ], + ), + ) + else if (result != null && !result.success) + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.red.withValues(alpha: 0.08), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.red.withValues(alpha: 0.45)), + ), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Icon( + Icons.error_outline_rounded, + color: Colors.red, + size: 24, + ), + const SizedBox(width: 10), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + 'Avviso ${result.channel.label} non riuscito', + style: const TextStyle( + fontWeight: FontWeight.bold, + color: Colors.red, + ), + ), + const SizedBox(height: 4), + Text( + result.error ?? + 'Impossibile inviare l\'avviso al cliente.', + style: const TextStyle(fontSize: 13), + ), + ], + ), + ), + ], + ), + const SizedBox(height: 10), + Align( + alignment: Alignment.centerRight, + child: OutlinedButton.icon( + onPressed: isRetrying + ? null + : () => context + .read() + .retryNotification(), + icon: isRetrying + ? const SizedBox( + width: 14, + height: 14, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Icon(Icons.refresh_rounded, size: 18), + label: Text( + isRetrying ? 'Invio in corso...' : 'Riprova invio', + ), + ), + ), + ], + ), + ) + else + Container( + padding: const EdgeInsets.all(14), + decoration: BoxDecoration( + color: Colors.amber.withValues(alpha: 0.14), + borderRadius: BorderRadius.circular(12), + border: Border.all(color: Colors.amber.shade700), + ), + child: Row( + children: [ + Icon( + Icons.notifications_active_outlined, + color: Colors.amber.shade900, + ), + const SizedBox(width: 10), + Expanded( + child: Text( + 'Timeline pubblica aggiornata. Ricordati di avvisare il cliente (${ticket.contactPreference.label}${ticket.effectiveContactDestination.isNotEmpty ? ': ${ticket.effectiveContactDestination}' : ''}).', + style: const TextStyle(fontSize: 12.5), + ), + ), + ], + ), + ), + + const SizedBox(height: 20), + + FilledButton( + onPressed: isRetrying ? null : () => Navigator.pop(context, ticket), + child: const Text('Chiudi'), + ), + ], + ); + } +} diff --git a/lib/features/tickets/ui/widgets/ticket_list_card.dart b/lib/features/tickets/ui/widgets/ticket_list_card.dart index e5501a9..92be274 100644 --- a/lib/features/tickets/ui/widgets/ticket_list_card.dart +++ b/lib/features/tickets/ui/widgets/ticket_list_card.dart @@ -7,6 +7,7 @@ import 'package:flux/features/attachments/ui/attachment_viewer_screen.dart'; import 'package:flux/features/tickets/blocs/ticket_list_cubit.dart'; import 'package:flux/features/tickets/models/ticket_model.dart'; import 'package:flux/features/tickets/models/ticket_status_extension.dart'; +import 'package:flux/features/tickets/ui/widgets/mark_ticket_returned_sheet.dart'; import 'package:go_router/go_router.dart'; class TicketListCard extends StatelessWidget { @@ -274,6 +275,46 @@ class TicketListCard extends StatelessWidget { fontSize: 12, ), ), + if (ticket.ticketStatus == TicketStatus.waitingForReturn && + !isSelectionMode && + ticket.id != null) ...[ + const SizedBox(height: 8), + Align( + alignment: Alignment.centerRight, + child: FilledButton.tonalIcon( + style: FilledButton.styleFrom( + backgroundColor: Colors.green.withValues( + alpha: 0.14, + ), + foregroundColor: Colors.green.shade800, + visualDensity: VisualDensity.compact, + padding: const EdgeInsets.symmetric( + horizontal: 12, + vertical: 8, + ), + ), + onPressed: () async { + final updated = await showMarkTicketReturnedSheet( + context, + ticket, + ); + if (updated != null && context.mounted) { + context.read().loadTickets( + refresh: true, + ); + } + }, + icon: const Icon( + Icons.assignment_returned_rounded, + size: 17, + ), + label: const Text( + 'Segna rientrato', + style: TextStyle(fontWeight: FontWeight.w700), + ), + ), + ), + ], ], ),