Files
flux/lib/features/tickets/ui/public_ticket_screen.dart
T

823 lines
34 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tickets/blocs/public_ticket_cubit.dart';
import 'package:flux/features/tickets/models/public_ticket_model.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/tickets/models/ticket_status_extension.dart';
import 'package:flux/features/tracking/models/tracking_model.dart';
import 'package:intl/intl.dart';
import 'package:url_launcher/url_launcher.dart';
class PublicTicketScreen extends StatefulWidget {
final String ticketId;
const PublicTicketScreen({super.key, required this.ticketId});
@override
State<PublicTicketScreen> createState() => _PublicTicketScreenState();
}
class _PublicTicketScreenState extends State<PublicTicketScreen> {
@override
void initState() {
super.initState();
context.read<PublicTicketCubit>().loadTicket(widget.ticketId);
}
int _progressStep(TicketStatus status) {
switch (status) {
case TicketStatus.open:
return 0;
case TicketStatus.inProgress:
case TicketStatus.waitingForParts:
case TicketStatus.waitingForQuote:
case TicketStatus.waitingForCustomer:
case TicketStatus.waitingForShipping:
case TicketStatus.waitingForReturn:
return 1;
case TicketStatus.ready:
return 2;
case TicketStatus.closed:
return 3;
}
}
String _statusSubtitle(PublicTicketModel ticket) {
switch (ticket.ticketStatus) {
case TicketStatus.open:
return 'Abbiamo ricevuto la tua richiesta. Un tecnico la prenderà in carico al più presto.';
case TicketStatus.inProgress:
return 'Il tuo dispositivo è attualmente in lavorazione presso il nostro laboratorio.';
case TicketStatus.waitingForParts:
return 'Siamo in attesa dell\'arrivo dei ricambi necessari per completare l\'intervento.';
case TicketStatus.waitingForQuote:
return 'Stiamo elaborando il preventivo per la riparazione. Ti aggiorneremo appena pronto.';
case TicketStatus.waitingForCustomer:
return 'Siamo in attesa di un tuo riscontro o della conferma del preventivo per procedere.';
case TicketStatus.waitingForShipping:
return 'Il dispositivo è in preparazione per la spedizione al centro assistenza.';
case TicketStatus.waitingForReturn:
return 'Il dispositivo è presso il centro assistenza. Ti avviseremo appena rientra.';
case TicketStatus.ready:
return 'Ottime notizie! Il dispositivo è pronto per il ritiro in negozio.';
case TicketStatus.closed:
return 'Pratica conclusa e dispositivo riconsegnato. Grazie per averci scelto!';
}
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
return Scaffold(
backgroundColor: theme.colorScheme.surface,
body: SafeArea(
child: BlocBuilder<PublicTicketCubit, PublicTicketState>(
builder: (context, state) {
if (state.status == PublicTicketStatus.initial ||
state.status == PublicTicketStatus.loading) {
return const Center(child: CircularProgressIndicator());
}
if (state.status == PublicTicketStatus.notFound) {
return _buildEmptyState(
context,
icon: Icons.search_off_rounded,
title: 'Scheda non trovata',
subtitle:
'Il link potrebbe non essere valido oppure la pratica non è più disponibile.',
);
}
if (state.status == PublicTicketStatus.failure ||
state.ticket == null) {
return _buildEmptyState(
context,
icon: Icons.cloud_off_rounded,
title: 'Connessione non riuscita',
subtitle:
state.errorMessage ?? 'Impossibile caricare i dati ora.',
onRetry: () => context
.read<PublicTicketCubit>()
.loadTicket(widget.ticketId),
);
}
return _buildTicketContent(context, theme, state.ticket!);
},
),
),
);
}
Widget _buildEmptyState(
BuildContext context, {
required IconData icon,
required String title,
required String subtitle,
VoidCallback? onRetry,
}) {
final theme = Theme.of(context);
return Center(
child: Padding(
padding: const EdgeInsets.all(24.0),
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 420),
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(icon, size: 64, color: theme.colorScheme.primary),
const SizedBox(height: 16),
Text(
title,
style: theme.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
textAlign: TextAlign.center,
),
const SizedBox(height: 8),
Text(
subtitle,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
),
if (onRetry != null) ...[
const SizedBox(height: 20),
FilledButton.icon(
onPressed: onRetry,
icon: const Icon(Icons.refresh_rounded),
label: const Text('Riprova'),
),
],
],
),
),
),
);
}
Widget _buildTicketContent(
BuildContext context,
ThemeData theme,
PublicTicketModel ticket,
) {
final dateFmt = DateFormat('dd/MM/yyyy');
final dateTimeFmt = DateFormat('dd/MM/yyyy HH:mm');
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final statusColor = ticket.ticketStatus.color;
final step = _progressStep(ticket.ticketStatus);
return RefreshIndicator(
onRefresh: () =>
context.read<PublicTicketCubit>().loadTicket(widget.ticketId),
child: SingleChildScrollView(
physics: const AlwaysScrollableScrollPhysics(),
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 20),
child: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 680),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// --- HEADER AZIENDA / NEGOZIO ---
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: theme.colorScheme.primary.withValues(alpha: 0.12),
borderRadius: BorderRadius.circular(12),
),
child: Icon(
Icons.build_circle_rounded,
color: theme.colorScheme.primary,
size: 28,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
ticket.companyName?.isNotEmpty == true
? ticket.companyName!
: 'Centro Assistenza',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w800,
),
),
if (ticket.storeName?.isNotEmpty == true)
Text(
'Punto vendita: ${ticket.storeName}',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
IconButton(
tooltip: 'Aggiorna stato',
onPressed: () => context
.read<PublicTicketCubit>()
.loadTicket(widget.ticketId),
icon: const Icon(Icons.refresh_rounded),
),
],
),
const SizedBox(height: 16),
// --- HERO CARD STATO ATTUALE ---
Container(
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: [
statusColor.withValues(alpha: 0.16),
statusColor.withValues(alpha: 0.05),
],
begin: Alignment.topLeft,
end: Alignment.bottomRight,
),
borderRadius: BorderRadius.circular(18),
border: Border.all(
color: statusColor.withValues(alpha: 0.45),
width: 1.5,
),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Wrap(
spacing: 8,
runSpacing: 8,
alignment: WrapAlignment.spaceBetween,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Container(
padding: const EdgeInsets.symmetric(
horizontal: 10,
vertical: 5,
),
decoration: BoxDecoration(
color: statusColor,
borderRadius: BorderRadius.circular(20),
),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon(
ticket.ticketStatus.icon,
size: 16,
color: Colors.white,
),
const SizedBox(width: 6),
Text(
ticket.ticketStatus.displayValue,
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 13,
),
),
],
),
),
if (ticket.referenceId?.isNotEmpty == true)
Text(
'Rif. ${ticket.referenceId}',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.w800,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
const SizedBox(height: 14),
if (ticket.customerName?.isNotEmpty == true)
Text(
'Ciao ${ticket.customerName},',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Text(
_statusSubtitle(ticket),
style: theme.textTheme.bodyMedium?.copyWith(
height: 1.45,
),
),
const SizedBox(height: 18),
_buildProgressBar(theme, step, statusColor),
],
),
),
const SizedBox(height: 16),
// --- PREVENTIVO / IMPORTO (se presente) ---
if (ticket.customerPrice > 0) ...[
Container(
padding: const EdgeInsets.all(16),
decoration: BoxDecoration(
color: theme.colorScheme.primaryContainer.withValues(
alpha: 0.45,
),
borderRadius: BorderRadius.circular(14),
border: Border.all(
color: theme.colorScheme.primary.withValues(alpha: 0.3),
),
),
child: Row(
children: [
Icon(
Icons.receipt_long_rounded,
color: theme.colorScheme.primary,
size: 28,
),
const SizedBox(width: 14),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
ticket.ticketStatus == TicketStatus.ready ||
ticket.ticketStatus ==
TicketStatus.closed
? 'IMPORTO INTERVENTO'
: 'PREVENTIVO / IMPORTO STIMATO',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.w800,
letterSpacing: 0.5,
color: theme.colorScheme.primary,
),
),
const SizedBox(height: 2),
Text(
currencyFmt.format(ticket.customerPrice),
style: theme.textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.w900,
color: theme.colorScheme.primary,
),
),
],
),
),
],
),
),
const SizedBox(height: 16),
],
// --- DETTAGLI SCHEDA ---
Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(
color: theme.dividerColor.withValues(alpha: 0.35),
),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Dettagli Assistenza',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const Divider(height: 22),
if (ticket.targetModelName?.isNotEmpty == true)
_infoRow(
Icons.smartphone_rounded,
'Dispositivo',
ticket.targetModelName!,
),
_infoRow(
Icons.category_outlined,
'Tipo intervento',
ticket.ticketType.displayValue,
),
if (ticket.createdAt != null)
_infoRow(
Icons.calendar_today_outlined,
'Data apertura',
dateFmt.format(ticket.createdAt!),
),
if (ticket.estimatedDeliveryAt != null &&
ticket.ticketStatus != TicketStatus.closed)
_infoRow(
Icons.event_available_outlined,
'Consegna stimata',
dateFmt.format(ticket.estimatedDeliveryAt!),
),
if (ticket.warrantyType != null)
_infoRow(
Icons.verified_user_outlined,
'Garanzia',
ticket.warrantyType!.displayValue,
),
if (ticket.includedAccessories?.trim().isNotEmpty ==
true)
_infoRow(
Icons.cable_rounded,
'Accessori lasciati',
ticket.includedAccessories!.trim(),
),
if (ticket.hasCourtesyDevice)
_infoRow(
Icons.phone_android_rounded,
'Muletto di cortesia',
'Assegnato (da riconsegnare al ritiro)',
),
if (ticket.request.trim().isNotEmpty) ...[
const SizedBox(height: 8),
Text(
'Problema segnalato',
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.45),
borderRadius: BorderRadius.circular(10),
),
child: Text(
ticket.request.trim(),
style: theme.textTheme.bodyMedium,
),
),
],
if (ticket.publicNotes?.trim().isNotEmpty == true) ...[
const SizedBox(height: 12),
Text(
'Note per il cliente',
style: theme.textTheme.labelMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.blue.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(10),
),
child: Text(
ticket.publicNotes!.trim(),
style: theme.textTheme.bodyMedium,
),
),
],
if (ticket.resolutionNotes?.trim().isNotEmpty ==
true) ...[
const SizedBox(height: 12),
Text(
'Esito lavorazione',
style: theme.textTheme.labelMedium?.copyWith(
color: Colors.green.shade700,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 4),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.green.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(10),
),
child: Text(
ticket.resolutionNotes!.trim(),
style: theme.textTheme.bodyMedium,
),
),
],
],
),
),
),
const SizedBox(height: 16),
// --- TIMELINE PUBBLICA ---
Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(
color: theme.dividerColor.withValues(alpha: 0.35),
),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Icon(
Icons.timeline_rounded,
size: 20,
color: theme.colorScheme.primary,
),
const SizedBox(width: 8),
Text(
'Cronologia Aggiornamenti',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
],
),
const Divider(height: 22),
if (ticket.timeline.isEmpty)
Padding(
padding: const EdgeInsets.symmetric(vertical: 12),
child: Text(
'La pratica è stata registrata. Qui compariranno tutti gli aggiornamenti.',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
)
else
...ticket.timeline.asMap().entries.map((entry) {
final idx = entry.key;
final item = entry.value;
final isLast = idx == ticket.timeline.length - 1;
final isStatus =
item.eventType == TrackingType.statusChange;
return IntrinsicHeight(
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(
width: 24,
child: Column(
children: [
Container(
width: 12,
height: 12,
margin: const EdgeInsets.only(top: 4),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isStatus
? theme.colorScheme.primary
: Colors.teal,
),
),
if (!isLast)
Expanded(
child: Container(
width: 2,
margin:
const EdgeInsets.symmetric(
vertical: 4,
),
color: theme.dividerColor
.withValues(alpha: 0.5),
),
),
],
),
),
const SizedBox(width: 10),
Expanded(
child: Padding(
padding: EdgeInsets.only(
bottom: isLast ? 4 : 16,
),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: [
Text(
dateTimeFmt.format(item.createdAt),
style: theme.textTheme.labelSmall
?.copyWith(
color: theme
.colorScheme
.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
const SizedBox(height: 2),
Text(
item.message,
style: theme.textTheme.bodyMedium,
),
],
),
),
),
],
),
);
}),
],
),
),
),
const SizedBox(height: 16),
// --- CONTATTI NEGOZIO ---
if ((ticket.companyPhone?.trim().isNotEmpty ?? false) ||
(ticket.companyEmail?.trim().isNotEmpty ?? false))
Card(
elevation: 0,
margin: EdgeInsets.zero,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(16),
side: BorderSide(
color: theme.dividerColor.withValues(alpha: 0.35),
),
),
child: Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Hai bisogno di informazioni?',
style: theme.textTheme.titleSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
if (ticket.companyAddress?.isNotEmpty == true) ...[
const SizedBox(height: 4),
Text(
[
ticket.companyAddress,
ticket.companyCity,
].where((e) => e != null && e.isNotEmpty).join(', '),
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
const SizedBox(height: 12),
Wrap(
spacing: 10,
runSpacing: 10,
children: [
if (ticket.companyPhone?.trim().isNotEmpty ??
false)
FilledButton.tonalIcon(
onPressed: () => launchUrl(
Uri.parse(
'tel:${ticket.companyPhone!.trim()}',
),
),
icon: const Icon(Icons.phone_outlined, size: 18),
label: Text(ticket.companyPhone!.trim()),
),
if (ticket.companyEmail?.trim().isNotEmpty ??
false)
OutlinedButton.icon(
onPressed: () => launchUrl(
Uri.parse(
'mailto:${ticket.companyEmail!.trim()}?subject=${Uri.encodeComponent('Info Ticket ${ticket.referenceId ?? ''}')}',
),
),
icon: const Icon(Icons.email_outlined, size: 18),
label: Text(ticket.companyEmail!.trim()),
),
],
),
],
),
),
),
const SizedBox(height: 24),
],
),
),
),
),
);
}
Widget _buildProgressBar(ThemeData theme, int currentStep, Color activeColor) {
const labels = ['Aperto', 'In lavorazione', 'Pronto', 'Consegnato'];
return Row(
children: List.generate(labels.length, (index) {
final isDone = index <= currentStep;
return Expanded(
child: Column(
children: [
Row(
children: [
Expanded(
child: Container(
height: 3,
color: index == 0
? Colors.transparent
: (isDone
? activeColor
: theme.dividerColor.withValues(alpha: 0.4)),
),
),
Container(
width: 22,
height: 22,
decoration: BoxDecoration(
shape: BoxShape.circle,
color: isDone
? activeColor
: theme.colorScheme.surfaceContainerHighest,
),
child: Icon(
isDone ? Icons.check_rounded : Icons.circle_outlined,
size: 13,
color: isDone
? Colors.white
: theme.colorScheme.onSurfaceVariant,
),
),
Expanded(
child: Container(
height: 3,
color: index == labels.length - 1
? Colors.transparent
: (index < currentStep
? activeColor
: theme.dividerColor.withValues(alpha: 0.4)),
),
),
],
),
const SizedBox(height: 6),
Text(
labels[index],
style: TextStyle(
fontSize: 10.5,
fontWeight: isDone ? FontWeight.bold : FontWeight.normal,
color: isDone
? activeColor
: theme.colorScheme.onSurfaceVariant,
),
textAlign: TextAlign.center,
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
),
);
}),
);
}
Widget _infoRow(IconData icon, String label, String value) {
return Padding(
padding: const EdgeInsets.only(bottom: 10),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: Colors.grey.shade600),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
label,
style: TextStyle(
fontSize: 11.5,
color: Colors.grey.shade600,
fontWeight: FontWeight.w600,
),
),
Text(
value,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
],
),
),
],
),
);
}
}