Files
flux/lib/features/tickets/blocs/ticket_form_cubit.dart
T

730 lines
24 KiB
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/enums_and_consts/contact_preference.dart';
import 'package:flux/core/services/email/email_service.dart';
import 'package:flux/core/services/whatsapp/whatsapp_service.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';
import 'package:flux/features/tickets/models/ticket_notification_result.dart';
import 'package:flux/features/tickets/data/ticket_repository.dart';
import 'package:flux/features/tickets/utils/ticket_notification_helper.dart';
import 'package:flux/features/tickets/utils/ticket_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:intl/intl.dart';
import 'ticket_form_state.dart';
class TicketFormCubit extends Cubit<TicketFormState> {
final TicketRepository _repository = GetIt.I.get<TicketRepository>();
final CustomerRepository _customerRepository =
GetIt.I.get<CustomerRepository>();
final SessionCubit _sessionCubit = GetIt.I.get<SessionCubit>();
final WhatsAppService _whatsAppService = GetIt.I.get<WhatsAppService>();
final EmailService _emailService = GetIt.I.get<EmailService>();
bool _pendingOpeningNotificationForDraft = false;
// Costruttore: prepariamo subito il ticket base con i dati di chi lo crea
TicketFormCubit({StaffMemberModel? createdBy, TicketModel? existingTicket})
: super(
TicketFormState(
// Se c'è un ticket esistente usa quello, ALTRIMENTI ne crea uno vuoto
// e ci stampa subito il nome del creatore!
ticket:
existingTicket ??
TicketModel.empty().copyWith(
createdById: createdBy?.id,
createdByName: createdBy?.name,
),
),
);
/// 1. INIZIALIZZAZIONE
Future<void> initForm({String? id, TicketModel? existingTicket}) async {
if (existingTicket != null) {
// SCENARIO 1: Abbiamo il ticket intero passato via record
emit(
state.copyWith(ticket: existingTicket, status: TicketFormStatus.ready),
);
} else if (id != null) {
// SCENARIO 2: QR CODE o Web Refresh! (Hai solo l'ID)
emit(state.copyWith(status: TicketFormStatus.loading));
try {
// Boom! Lo scarica dal database in tempo reale
final fetchedTicket = await _repository.getTicketById(id);
emit(
state.copyWith(ticket: fetchedTicket, status: TicketFormStatus.ready),
);
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Ticket non trovato',
),
);
}
} else {
// SCENARIO 3: Nuovo Ticket
final currentStore = _sessionCubit.state.currentStore;
final companyId = _sessionCubit.state.company?.id ?? '';
// IL TRUCCO È QUI: Usiamo `state.ticket` invece di `TicketModel.empty()`.
// `state.ticket` HA GIÀ i dati di 'createdBy' settati nel costruttore!
final newTicket = state.ticket.copyWith(
companyId: companyId,
storeId: currentStore?.id,
ticketStatus: TicketStatus.open, // <-- O il tuo status di default
ticketType: TicketType.repair,
);
emit(state.copyWith(ticket: newTicket, status: TicketFormStatus.ready));
}
}
/// 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: resolvedAlt,
),
),
);
}
/// 3. AGGIORNAMENTO MODELLO (Usato dal nostro SharedModelSection!)
void updateTargetModel({required String modelId, required String modelName}) {
emit(
state.copyWith(
ticket: state.ticket.copyWith(
targetModelId: modelId,
targetModelName: modelName,
),
),
);
}
void updateSourceModel({required String modelId, required String modelName}) {
emit(
state.copyWith(
ticket: state.ticket.copyWith(
sourceModelId: modelId,
sourceModelName: modelName,
),
),
);
}
void updateCreator({required String staffId, required String staffName}) {
emit(
state.copyWith(
ticket: state.ticket.copyWith(
createdById: staffId,
createdByName: staffName,
),
),
);
}
/// 4. AGGIORNAMENTO GENERICO DEI CAMPI
void updateFields({
TicketType? ticketType,
TicketStatus? status,
String? request,
String? targetSn,
String? targetPassword,
String? sourceSn,
String? sourcePassword,
String? alternativePhoneNumber,
ContactPreference? contactPreference,
bool? hasCourtesyDevice,
String? includedAccessories,
String? publicNotes,
String? internalNotes,
double? customerPrice,
double? internalCost,
String? assignedToId,
String? assignedToName,
WarrantyType? warrantyType,
DateTime? estimatedDeliveryAt,
bool clearEstimatedDelivery = false,
}) {
emit(
state.copyWith(
ticket: state.ticket.copyWith(
ticketType: ticketType ?? state.ticket.ticketType,
ticketStatus: status ?? state.ticket.ticketStatus,
request: request ?? state.ticket.request,
targetSn: targetSn ?? state.ticket.targetSn,
targetPassword: targetPassword ?? state.ticket.targetPassword,
sourcePassword: sourcePassword ?? state.ticket.sourcePassword,
sourceSn: sourceSn ?? state.ticket.sourceSn,
alternativePhoneNumber:
alternativePhoneNumber ?? state.ticket.alternativePhoneNumber,
contactPreference:
contactPreference ?? state.ticket.contactPreference,
hasCourtesyDevice:
hasCourtesyDevice ?? state.ticket.hasCourtesyDevice,
includedAccessories:
includedAccessories ?? state.ticket.includedAccessories,
publicNotes: publicNotes ?? state.ticket.publicNotes,
internalNotes: internalNotes ?? state.ticket.internalNotes,
customerPrice: customerPrice ?? state.ticket.customerPrice,
internalCost: internalCost ?? state.ticket.internalCost,
assignedToId: assignedToId ?? state.ticket.assignedToId,
assignedToName: assignedToName ?? state.ticket.assignedToName,
warrantyType: warrantyType ?? state.ticket.warrantyType,
estimatedDeliveryAt: estimatedDeliveryAt,
clearEstimatedDelivery: clearEstimatedDelivery,
),
),
);
}
/// 5. SALVATAGGIO
Future<void> saveTicket() async {
emit(
state.copyWith(
status: TicketFormStatus.saving,
clearNotificationResult: true,
),
);
try {
final ticketToSave = state.ticket;
// Validazione base
if (ticketToSave.customerId == null || ticketToSave.customerId!.isEmpty) {
throw Exception("Seleziona un cliente prima di salvare.");
}
final isBrandNew = ticketToSave.id == null || ticketToSave.id!.isEmpty;
final TicketModel savedTicket;
if (isBrandNew) {
savedTicket = await _repository.insertTicket(ticketToSave);
} else {
savedTicket = await _repository.updateTicket(ticketToSave);
}
await _syncCustomerAlternativePhone(ticketToSave);
final enrichedTicket = ticketToSave.copyWith(
id: savedTicket.id,
referenceId: savedTicket.referenceId,
createdAt: savedTicket.createdAt ?? ticketToSave.createdAt ?? DateTime.now(),
);
TicketNotificationResult? notificationResult;
if (isBrandNew || _pendingOpeningNotificationForDraft) {
_pendingOpeningNotificationForDraft = false;
// Log pubblico iniziale nella timeline
if (enrichedTicket.id != null && enrichedTicket.id!.isNotEmpty) {
try {
await GetIt.I.get<TrackingRepository>().logQuickEvent(
companyId: enrichedTicket.companyId,
message: 'Pratica di assistenza aperta e registrata.',
type: TrackingType.statusChange,
parentId: enrichedTicket.id!,
parentType: TrackingParentType.ticket,
staffId: enrichedTicket.createdById ?? '',
isInternal: false,
);
} catch (_) {}
}
// Invio automatico ricevuta PDF su WhatsApp o Email se preferenza automatica
if (enrichedTicket.contactPreference.isWhatsapp ||
enrichedTicket.contactPreference.isEmail) {
notificationResult = await _sendOpeningReceipt(enrichedTicket);
}
}
emit(
state.copyWith(
status: TicketFormStatus.success,
ticket: enrichedTicket,
notificationResult: notificationResult,
),
);
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: e.toString(),
),
);
}
}
/// 5.1 SALVATAGGIO SILENZIOSO (Per generare il QR Code al volo)
Future<String?> saveTicketDraft() async {
// Non mettiamo lo stato 'saving' per non far sfarfallare tutta la UI,
// usiamo un caricamento invisibile.
try {
final ticketToSave = state.ticket;
if (ticketToSave.customerId == null || ticketToSave.customerId!.isEmpty) {
throw Exception("Seleziona un cliente prima di poter usare il QR.");
}
final savedTicket = await _repository.insertTicket(ticketToSave);
_pendingOpeningNotificationForDraft = true;
// Aggiorniamo silenziosamente lo stato con il ticket che ora ha un ID!
emit(state.copyWith(ticket: savedTicket, status: TicketFormStatus.ready));
return savedTicket.id;
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: e.toString(),
),
);
return null;
}
}
Future<void> takeInCharge({
required String staffId,
required String staffName,
}) async {
final currentTicket = state.ticket;
// Sicurezza: non possiamo prendere in carico un ticket fantasma
if (currentTicket.id == null || currentTicket.id!.isEmpty) return;
// 1. Prepariamo il ticket aggiornato
final updatedTicket = currentTicket.copyWith(
ticketStatus: TicketStatus
.inProgress, // Assumendo che tu abbia un enum per gli stati
assignedToId: staffId,
assignedToName: staffName,
);
try {
// 2. Aggiorniamo il ticket sul Database (usa il tuo metodo esistente del repo)
await _repository.updateTicket(updatedTicket);
// 3. Spara il log automatico nella Timeline!
await GetIt.I.get<TrackingRepository>().logQuickEvent(
companyId: currentTicket.companyId,
message: "Ticket preso in carico. Inizio lavorazione.",
type: TrackingType.statusChange,
parentId: currentTicket.id!,
parentType: TrackingParentType.ticket,
staffId: staffId,
// Lo mettiamo pubblico (isInternal: false) così il cliente a casa vede che
// il suo dispositivo è ufficialmente sotto i ferri!
isInternal: false,
);
// 4. Aggiorniamo lo stato locale del Cubit per far scattare la UI
emit(state.copyWith(ticket: updatedTicket));
} catch (e) {
// Gestisci eventuali errori (es. mostrando una snackbar)
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Errore durante la presa in carico: $e',
),
);
}
}
Future<TicketNotificationResult?> pauseTicket({
required TicketStatus newStatus,
required String notes,
bool notifyCustomer = false,
double? quotePrice,
}) async {
final currentTicket = state.ticket;
if (currentTicket.id == null || currentTicket.id!.isEmpty) return null;
final hasQuote = quotePrice != null && quotePrice > 0;
final updatedTicket = currentTicket.copyWith(
ticketStatus: newStatus,
customerPrice: hasQuote ? quotePrice : currentTicket.customerPrice,
);
try {
await _repository.updateTicket(updatedTicket);
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final buffer = StringBuffer();
if (hasQuote) {
buffer.write(
'Preventivo emesso: ${currencyFmt.format(quotePrice)} (${newStatus.displayValue}).',
);
} else {
buffer.write('Stato aggiornato: ${newStatus.displayValue}.');
}
if (notes.trim().isNotEmpty) {
buffer.write(' Note: ${notes.trim()}');
}
await GetIt.I.get<TrackingRepository>().logQuickEvent(
companyId: currentTicket.companyId,
message: buffer.toString(),
type: TrackingType.statusChange,
parentId: currentTicket.id!,
parentType: TrackingParentType.ticket,
staffId: currentTicket.assignedToId ?? '',
isInternal: false,
);
TicketNotificationResult? notificationResult;
if (notifyCustomer &&
(updatedTicket.contactPreference.isWhatsapp ||
updatedTicket.contactPreference.isEmail)) {
notificationResult = hasQuote
? await _sendQuoteNotification(
updatedTicket,
price: quotePrice,
notes: notes,
)
: await _sendStatusNotification(
updatedTicket,
publicNote: notes,
contextLabel: 'Aggiornamento stato',
);
}
emit(
state.copyWith(
ticket: updatedTicket,
notificationResult: notificationResult,
),
);
return notificationResult;
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Errore durante la sospensione: $e',
),
);
return null;
}
}
Future<TicketNotificationResult?> completeTicket({
required TicketResult result,
required double finalPrice,
bool notifyCustomer = false,
}) async {
final currentTicket = state.ticket;
if (currentTicket.id == null || currentTicket.id!.isEmpty) return null;
// 1. Aggiorniamo il ticket con il nuovo status, l'esito e il prezzo!
final updatedTicket = currentTicket.copyWith(
ticketStatus: TicketStatus.ready,
ticketResult: result,
customerPrice: finalPrice,
);
try {
await _repository.updateTicket(updatedTicket);
// 2. Timeline personalizzata in base all'esito
final esitoTesto = result == TicketResult.success
? "Riparato con successo"
: "Non riparabile/Preventivo rifiutato";
await GetIt.I.get<TrackingRepository>().logQuickEvent(
companyId: currentTicket.companyId,
message:
"Lavorazione completata. Esito: $esitoTesto. Il dispositivo è pronto per il ritiro.",
type: TrackingType.statusChange,
parentId: currentTicket.id!,
parentType: TrackingParentType.ticket,
staffId: currentTicket.assignedToId ?? '',
isInternal: false,
);
TicketNotificationResult? notificationResult;
if (notifyCustomer &&
(updatedTicket.contactPreference.isWhatsapp ||
updatedTicket.contactPreference.isEmail)) {
notificationResult = await _sendStatusNotification(
updatedTicket,
contextLabel: 'Avviso ritiro',
);
}
emit(
state.copyWith(
ticket: updatedTicket,
notificationResult: notificationResult,
),
);
return notificationResult;
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Errore durante la chiusura: $e',
),
);
return null;
}
}
/// Emette un preventivo su un ticket esistente, lo mette in Attesa Cliente,
/// scrive in timeline pubblica e (se richiesto) avvisa il cliente su WhatsApp/Email.
Future<TicketNotificationResult?> sendQuote({
required double price,
String notes = '',
bool notifyCustomer = true,
}) async {
final currentTicket = state.ticket;
if (currentTicket.id == null || currentTicket.id!.isEmpty) return null;
final updatedTicket = currentTicket.copyWith(
customerPrice: price,
ticketStatus: TicketStatus.waitingForCustomer,
);
try {
await _repository.updateTicket(updatedTicket);
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final cleanNotes = notes.trim();
final timelineMsg = cleanNotes.isNotEmpty
? 'Preventivo emesso: ${currencyFmt.format(price)}. $cleanNotes'
: 'Preventivo emesso: ${currencyFmt.format(price)}. In attesa di conferma dal cliente.';
await GetIt.I.get<TrackingRepository>().logQuickEvent(
companyId: currentTicket.companyId,
message: timelineMsg,
type: TrackingType.statusChange,
parentId: currentTicket.id!,
parentType: TrackingParentType.ticket,
staffId:
currentTicket.assignedToId ??
_sessionCubit.state.currentStaffMember?.id ??
'',
isInternal: false,
);
TicketNotificationResult? notificationResult;
if (notifyCustomer &&
(updatedTicket.contactPreference.isWhatsapp ||
updatedTicket.contactPreference.isEmail)) {
notificationResult = await _sendQuoteNotification(
updatedTicket,
price: price,
notes: cleanNotes,
);
}
emit(
state.copyWith(
ticket: updatedTicket,
notificationResult: notificationResult,
),
);
return notificationResult;
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Errore durante l\'invio del preventivo: $e',
),
);
return null;
}
}
Future<TicketNotificationResult> _sendOpeningReceipt(
TicketModel ticket,
) async {
final ref = ticket.referenceId?.trim().isNotEmpty == true
? ticket.referenceId!
: (ticket.id?.substring(0, 8) ?? 'ticket');
final filename = 'Ricevuta_Assistenza_$ref.pdf';
Uint8List? pdfBytes;
try {
final doc = await TicketPdfService().generateCustomerReceiptPdf(ticket);
pdfBytes = await doc.save();
} catch (e) {
debugPrint('Errore generazione PDF ricevuta ticket: $e');
}
if (ticket.contactPreference.isWhatsapp) {
final phone = ticket.effectiveContactDestination;
final message = TicketNotificationHelper.buildOpeningWhatsAppMessage(
ticket,
);
final waRes = pdfBytes != null
? await _whatsAppService.sendDocument(
phone: phone,
bytes: pdfBytes,
filename: filename,
caption: message,
)
: await _whatsAppService.sendMessage(
phone: phone,
message: message,
linkPreview: true,
);
return TicketNotificationResult.fromWhatsApp(
waRes,
fallbackDestination: phone,
contextLabel: 'Ricevuta apertura',
);
}
final email = ticket.effectiveContactDestination;
final payload = TicketNotificationHelper.buildOpeningEmail(ticket);
final emailRes = await _emailService.sendEmail(
to: email,
subject: payload.subject,
text: payload.text,
html: payload.html,
account: EmailSenderAccount.assistenza,
attachments: pdfBytes != null
? [EmailAttachment(filename: filename, bytes: pdfBytes)]
: null,
);
return TicketNotificationResult.fromEmail(
emailRes,
fallbackDestination: email,
contextLabel: 'Ricevuta apertura',
);
}
Future<TicketNotificationResult> _sendQuoteNotification(
TicketModel ticket, {
required double price,
String? notes,
}) async {
if (ticket.contactPreference.isWhatsapp) {
final phone = ticket.effectiveContactDestination;
final message = TicketNotificationHelper.buildQuoteWhatsAppMessage(
ticket,
price: price,
notes: notes,
);
final waRes = await _whatsAppService.sendMessage(
phone: phone,
message: message,
linkPreview: true,
);
return TicketNotificationResult.fromWhatsApp(
waRes,
fallbackDestination: phone,
contextLabel: 'Preventivo',
);
}
final email = ticket.effectiveContactDestination;
final payload = TicketNotificationHelper.buildQuoteEmail(
ticket,
price: price,
notes: notes,
);
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: 'Preventivo',
);
}
Future<TicketNotificationResult> _sendStatusNotification(
TicketModel ticket, {
String? publicNote,
required String contextLabel,
}) 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: contextLabel,
);
}
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: contextLabel,
);
}
Future<void> _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<void> deleteTicket() async {
final currentTicket = state.ticket;
if (currentTicket.id == null || currentTicket.id!.isEmpty) return;
try {
await _repository.deleteTicket(currentTicket.id!);
emit(state.copyWith(status: TicketFormStatus.deleted));
} catch (e) {
emit(
state.copyWith(
status: TicketFormStatus.failure,
errorMessage: 'Errore durante l\'eliminazione: $e',
),
);
}
}
}