410 lines
14 KiB
Dart
410 lines
14 KiB
Dart
import 'package:flux/features/tickets/models/ticket_model.dart';
|
||
import 'package:intl/intl.dart';
|
||
|
||
typedef TicketEmailPayload = ({String subject, String text, String html});
|
||
|
||
/// Costruisce i messaggi WhatsApp e le Email HTML per i Ticket di Assistenza.
|
||
class TicketNotificationHelper {
|
||
TicketNotificationHelper._();
|
||
|
||
static final NumberFormat _currencyFmt = NumberFormat.currency(
|
||
locale: 'it_IT',
|
||
symbol: '€',
|
||
);
|
||
static final DateFormat _dateFmt = DateFormat('dd/MM/yyyy');
|
||
|
||
static String _escapeHtml(String input) {
|
||
return input
|
||
.replaceAll('&', '&')
|
||
.replaceAll('<', '<')
|
||
.replaceAll('>', '>')
|
||
.replaceAll('"', '"')
|
||
.replaceAll("'", ''');
|
||
}
|
||
|
||
static String _ticketRef(TicketModel ticket) {
|
||
final ref = ticket.referenceId?.trim() ?? '';
|
||
return ref.isNotEmpty ? ref : (ticket.id?.substring(0, 8) ?? '');
|
||
}
|
||
|
||
static String _deviceLabel(TicketModel ticket) {
|
||
final model = ticket.targetModelName?.trim() ?? '';
|
||
if (model.isNotEmpty) return model;
|
||
return ticket.ticketType.displayValue;
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 1. APERTURA TICKET (con ricevuta PDF allegata + link pagina pubblica)
|
||
// ===========================================================================
|
||
|
||
static String buildOpeningWhatsAppMessage(TicketModel ticket) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
|
||
final buffer = StringBuffer()
|
||
..writeln(
|
||
'Ciao${name.isNotEmpty ? ' $name' : ''}, abbiamo preso in carico la tua pratica di assistenza *#$ref*!',
|
||
)
|
||
..writeln()
|
||
..writeln('• *Dispositivo:* $device')
|
||
..writeln('• *Intervento:* ${ticket.ticketType.displayValue}');
|
||
|
||
if (ticket.customerPrice > 0) {
|
||
buffer.writeln(
|
||
'• *Preventivo iniziale:* ${_currencyFmt.format(ticket.customerPrice)}',
|
||
);
|
||
}
|
||
if (ticket.estimatedDeliveryAt != null) {
|
||
buffer.writeln(
|
||
'• *Consegna stimata:* ${_dateFmt.format(ticket.estimatedDeliveryAt!)}',
|
||
);
|
||
}
|
||
|
||
buffer
|
||
..writeln()
|
||
..writeln('In allegato trovi la ricevuta in formato PDF.');
|
||
|
||
if (link.isNotEmpty) {
|
||
buffer
|
||
..writeln()
|
||
..writeln('Puoi seguire lo stato di avanzamento in tempo reale qui:')
|
||
..write(link);
|
||
}
|
||
|
||
return buffer.toString();
|
||
}
|
||
|
||
static TicketEmailPayload buildOpeningEmail(TicketModel ticket) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
|
||
final subject = 'Conferma apertura pratica #$ref – $device';
|
||
final rows = <({String label, String value, bool highlight})>[
|
||
(label: 'Riferimento pratica', value: '#$ref', highlight: true),
|
||
(label: 'Dispositivo', value: device, highlight: false),
|
||
(
|
||
label: 'Tipo intervento',
|
||
value: ticket.ticketType.displayValue,
|
||
highlight: false,
|
||
),
|
||
if (ticket.customerPrice > 0)
|
||
(
|
||
label: 'Preventivo iniziale',
|
||
value: _currencyFmt.format(ticket.customerPrice),
|
||
highlight: true,
|
||
),
|
||
if (ticket.estimatedDeliveryAt != null)
|
||
(
|
||
label: 'Consegna stimata',
|
||
value: _dateFmt.format(ticket.estimatedDeliveryAt!),
|
||
highlight: false,
|
||
),
|
||
];
|
||
|
||
final text = buildOpeningWhatsAppMessage(ticket).replaceAll('*', '');
|
||
final html = _wrapHtmlEmail(
|
||
title: 'Pratica di assistenza aperta',
|
||
accentColor: '#1d4ed8',
|
||
greetingHtml:
|
||
'Ciao${name.isNotEmpty ? ' <strong>${_escapeHtml(name)}</strong>' : ''},',
|
||
introHtml:
|
||
'Abbiamo preso in carico la tua richiesta di assistenza. In allegato trovi la ricevuta PDF della pratica.',
|
||
rows: rows,
|
||
ctaLabel: link.isNotEmpty ? 'Segui lo stato della pratica' : null,
|
||
ctaUrl: link.isNotEmpty ? link : null,
|
||
footerHtml:
|
||
'Ti aggiorneremo automaticamente in caso di novità, preventivi o appena il dispositivo sarà pronto per il ritiro.',
|
||
);
|
||
|
||
return (subject: subject, text: text, html: html);
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 2. PREVENTIVO EMESSO
|
||
// ===========================================================================
|
||
|
||
static String buildQuoteWhatsAppMessage(
|
||
TicketModel ticket, {
|
||
required double price,
|
||
String? notes,
|
||
}) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
final cleanNotes = notes?.trim() ?? '';
|
||
|
||
final buffer = StringBuffer()
|
||
..writeln(
|
||
'Ciao${name.isNotEmpty ? ' $name' : ''}, abbiamo preparato il preventivo per la tua pratica *#$ref* ($device):',
|
||
)
|
||
..writeln()
|
||
..writeln('• *Importo preventivo:* ${_currencyFmt.format(price)}');
|
||
|
||
if (cleanNotes.isNotEmpty) {
|
||
buffer.writeln('• *Dettagli:* $cleanNotes');
|
||
}
|
||
|
||
buffer
|
||
..writeln()
|
||
..writeln(
|
||
'Rispondici a questo messaggio o contattaci per confermare se desideri procedere con la riparazione.',
|
||
);
|
||
|
||
if (link.isNotEmpty) {
|
||
buffer
|
||
..writeln()
|
||
..writeln('Dettagli e cronologia pratica:')
|
||
..write(link);
|
||
}
|
||
|
||
return buffer.toString();
|
||
}
|
||
|
||
static TicketEmailPayload buildQuoteEmail(
|
||
TicketModel ticket, {
|
||
required double price,
|
||
String? notes,
|
||
}) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
final cleanNotes = notes?.trim() ?? '';
|
||
|
||
final subject = 'Preventivo pronto – Pratica #$ref ($device)';
|
||
final rows = <({String label, String value, bool highlight})>[
|
||
(label: 'Pratica', value: '#$ref', highlight: false),
|
||
(label: 'Dispositivo', value: device, highlight: false),
|
||
(
|
||
label: 'Importo preventivo',
|
||
value: _currencyFmt.format(price),
|
||
highlight: true,
|
||
),
|
||
if (cleanNotes.isNotEmpty)
|
||
(label: 'Dettagli', value: cleanNotes, highlight: false),
|
||
];
|
||
|
||
final text = buildQuoteWhatsAppMessage(
|
||
ticket,
|
||
price: price,
|
||
notes: notes,
|
||
).replaceAll('*', '');
|
||
final html = _wrapHtmlEmail(
|
||
title: 'Preventivo disponibile',
|
||
accentColor: '#d97706',
|
||
greetingHtml:
|
||
'Ciao${name.isNotEmpty ? ' <strong>${_escapeHtml(name)}</strong>' : ''},',
|
||
introHtml:
|
||
'Il preventivo per la tua pratica di assistenza è pronto. Ti preghiamo di darci conferma per poter procedere.',
|
||
rows: rows,
|
||
ctaLabel: link.isNotEmpty ? 'Visualizza pratica online' : null,
|
||
ctaUrl: link.isNotEmpty ? link : null,
|
||
footerHtml:
|
||
'Rispondi a questa email oppure contattaci in negozio per confermare o rifiutare il preventivo.',
|
||
);
|
||
|
||
return (subject: subject, text: text, html: html);
|
||
}
|
||
|
||
// ===========================================================================
|
||
// 3. CAMBIO DI STATO (es. Attesa ricambi, Spedito, Attesa cliente, Pronto)
|
||
// ===========================================================================
|
||
|
||
static String buildStatusUpdateWhatsAppMessage(
|
||
TicketModel ticket, {
|
||
String? publicNote,
|
||
}) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
final cleanNote = publicNote?.trim() ?? '';
|
||
|
||
final buffer = StringBuffer();
|
||
|
||
if (ticket.ticketStatus == TicketStatus.ready) {
|
||
final isSuccess = ticket.ticketResult != TicketResult.failure;
|
||
buffer
|
||
..writeln(
|
||
'Ciao${name.isNotEmpty ? ' $name' : ''}, il tuo dispositivo ($device – pratica *#$ref*) è *pronto per il ritiro*!',
|
||
)
|
||
..writeln()
|
||
..writeln(
|
||
'• *Esito:* ${isSuccess ? 'Intervento completato con successo' : 'Non riparabile / Intervento non eseguito'}',
|
||
);
|
||
if (ticket.customerPrice > 0) {
|
||
buffer.writeln(
|
||
'• *Totale al ritiro:* ${_currencyFmt.format(ticket.customerPrice)}',
|
||
);
|
||
}
|
||
if (ticket.hasCourtesyDevice) {
|
||
buffer.writeln(
|
||
'• *Promemoria:* ricordati di riportare il dispositivo di cortesia.',
|
||
);
|
||
}
|
||
if (cleanNote.isNotEmpty) {
|
||
buffer.writeln('• *Note:* $cleanNote');
|
||
}
|
||
buffer
|
||
..writeln()
|
||
..writeln('Ti aspettiamo in negozio!');
|
||
} else {
|
||
buffer
|
||
..writeln(
|
||
'Ciao${name.isNotEmpty ? ' $name' : ''}, c\'è un aggiornamento sulla tua pratica *#$ref* ($device):',
|
||
)
|
||
..writeln()
|
||
..writeln('• *Nuovo stato:* ${ticket.ticketStatus.displayValue}');
|
||
if (cleanNote.isNotEmpty) {
|
||
buffer.writeln('• *Note:* $cleanNote');
|
||
}
|
||
if (ticket.customerPrice > 0 &&
|
||
ticket.ticketStatus == TicketStatus.waitingForCustomer) {
|
||
buffer.writeln(
|
||
'• *Importo indicato:* ${_currencyFmt.format(ticket.customerPrice)}',
|
||
);
|
||
}
|
||
}
|
||
|
||
if (link.isNotEmpty) {
|
||
buffer
|
||
..writeln()
|
||
..writeln('Segui tutti gli aggiornamenti qui:')
|
||
..write(link);
|
||
}
|
||
|
||
return buffer.toString();
|
||
}
|
||
|
||
static TicketEmailPayload buildStatusUpdateEmail(
|
||
TicketModel ticket, {
|
||
String? publicNote,
|
||
}) {
|
||
final name = ticket.customer?.name.trim() ?? '';
|
||
final ref = _ticketRef(ticket);
|
||
final device = _deviceLabel(ticket);
|
||
final link = ticket.publicTrackingUrl;
|
||
final cleanNote = publicNote?.trim() ?? '';
|
||
final isReady = ticket.ticketStatus == TicketStatus.ready;
|
||
|
||
final subject = isReady
|
||
? 'Dispositivo pronto per il ritiro – Pratica #$ref'
|
||
: 'Aggiornamento pratica #$ref: ${ticket.ticketStatus.displayValue}';
|
||
|
||
final rows = <({String label, String value, bool highlight})>[
|
||
(label: 'Pratica', value: '#$ref', highlight: false),
|
||
(label: 'Dispositivo', value: device, highlight: false),
|
||
(
|
||
label: 'Stato attuale',
|
||
value: ticket.ticketStatus.displayValue,
|
||
highlight: true,
|
||
),
|
||
if (isReady && ticket.ticketResult != null)
|
||
(
|
||
label: 'Esito',
|
||
value: ticket.ticketResult == TicketResult.success
|
||
? 'Intervento completato con successo'
|
||
: 'Non riparabile / Intervento non eseguito',
|
||
highlight: false,
|
||
),
|
||
if (ticket.customerPrice > 0 &&
|
||
(isReady || ticket.ticketStatus == TicketStatus.waitingForCustomer))
|
||
(
|
||
label: isReady ? 'Totale al ritiro' : 'Importo preventivo',
|
||
value: _currencyFmt.format(ticket.customerPrice),
|
||
highlight: true,
|
||
),
|
||
if (cleanNote.isNotEmpty)
|
||
(label: 'Dettagli', value: cleanNote, highlight: false),
|
||
];
|
||
|
||
final text = buildStatusUpdateWhatsAppMessage(
|
||
ticket,
|
||
publicNote: publicNote,
|
||
).replaceAll('*', '');
|
||
|
||
final html = _wrapHtmlEmail(
|
||
title: isReady
|
||
? 'Il tuo dispositivo è pronto!'
|
||
: 'Aggiornamento sulla tua pratica',
|
||
accentColor: isReady ? '#16a34a' : '#0f766e',
|
||
greetingHtml:
|
||
'Ciao${name.isNotEmpty ? ' <strong>${_escapeHtml(name)}</strong>' : ''},',
|
||
introHtml: isReady
|
||
? 'La lavorazione sul tuo dispositivo è terminata ed è pronto per il ritiro in negozio.'
|
||
: 'Ti informiamo che lo stato della tua pratica di assistenza è stato aggiornato.',
|
||
rows: rows,
|
||
ctaLabel: link.isNotEmpty ? 'Apri stato pratica online' : null,
|
||
ctaUrl: link.isNotEmpty ? link : null,
|
||
footerHtml: isReady
|
||
? (ticket.hasCourtesyDevice
|
||
? 'Ti aspettiamo in negozio! Ricordati di riportare il dispositivo di cortesia.'
|
||
: 'Ti aspettiamo in negozio per il ritiro!')
|
||
: 'Puoi consultare in qualsiasi momento la cronologia aggiornata dal link qui sopra.',
|
||
);
|
||
|
||
return (subject: subject, text: text, html: html);
|
||
}
|
||
|
||
static String _wrapHtmlEmail({
|
||
required String title,
|
||
required String accentColor,
|
||
required String greetingHtml,
|
||
required String introHtml,
|
||
required List<({String label, String value, bool highlight})> rows,
|
||
String? ctaLabel,
|
||
String? ctaUrl,
|
||
required String footerHtml,
|
||
}) {
|
||
final rowsHtml = rows.map((row) {
|
||
final valueStyle = row.highlight
|
||
? 'color: $accentColor; font-weight: 700; font-size: 15px;'
|
||
: 'color: #0f172a; font-weight: 600; font-size: 14px;';
|
||
return '''
|
||
<tr>
|
||
<td style="padding: 8px 0; color: #64748b; font-size: 14px; border-bottom: 1px solid #f1f5f9;">${_escapeHtml(row.label)}</td>
|
||
<td style="padding: 8px 0; text-align: right; $valueStyle border-bottom: 1px solid #f1f5f9;">${_escapeHtml(row.value)}</td>
|
||
</tr>
|
||
''';
|
||
}).join();
|
||
|
||
final ctaHtml = (ctaLabel != null && ctaUrl != null)
|
||
? '''
|
||
<div style="margin: 26px 0; text-align: center;">
|
||
<a href="${_escapeHtml(ctaUrl)}" style="background-color: $accentColor; color: #ffffff; padding: 13px 26px; text-decoration: none; border-radius: 10px; font-size: 15px; font-weight: 600; display: inline-block;">
|
||
${_escapeHtml(ctaLabel)}
|
||
</a>
|
||
</div>
|
||
'''
|
||
: '';
|
||
|
||
return '''
|
||
<div style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif; max-width: 560px; margin: 24px auto; padding: 28px; border: 1px solid #e2e8f0; border-radius: 16px; background-color: #ffffff;">
|
||
<h2 style="color: $accentColor; font-size: 21px; font-weight: 700; margin: 0 0 16px 0;">
|
||
${_escapeHtml(title)}
|
||
</h2>
|
||
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0 0 12px 0;">
|
||
$greetingHtml
|
||
</p>
|
||
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0 0 20px 0;">
|
||
$introHtml
|
||
</p>
|
||
<table style="width: 100%; border-collapse: collapse; margin-bottom: 16px; background-color: #f8fafc; border-radius: 10px; padding: 12px;">
|
||
<tbody>
|
||
$rowsHtml
|
||
</tbody>
|
||
</table>
|
||
$ctaHtml
|
||
<p style="color: #475569; font-size: 14px; line-height: 1.6; margin: 0;">
|
||
$footerHtml
|
||
</p>
|
||
</div>
|
||
''';
|
||
}
|
||
}
|