Compare commits

..
8 Commits
Author SHA1 Message Date
brontomark 52c1cce878 feat: add internal deep link URL and update bag label and customer receipt in ticket form 2026-12-04 19:30:24 +01:00
brontomark f6d5a4f0ce feat: add mark ticket returned cubit and shipping notifications 2026-12-04 19:24:11 +01:00
brontomark a570918a60 feat: implement public ticket tracking and automated notification system 2026-12-04 18:58:46 +01:00
brontomark a568486b4f feat: handle delivery state transition and UI feedback in customer order form 2026-12-03 19:37:53 +01:00
brontomark 56f0d1ee53 refactor: redesign customer order label PDF for vertical layout with prominent QR code 2026-12-03 17:13:05 +01:00
brontomark 6296f49737 feat: add sender account support to email service and bump version to 2.7.1+96
Build and Release FLUX (Multi-Platform) / build-web (push) Successful in 2m7s
Build and Release FLUX (Multi-Platform) / build-macos (push) Successful in 2m30s
Build and Release FLUX (Multi-Platform) / build-linux (push) Successful in 1m56s
Build and Release FLUX (Multi-Platform) / build-windows (push) Successful in 8m26s
2026-12-03 12:10:52 +01:00
brontomark 1fbd2bf8db feat: add email service and automated customer order notifications 2026-12-03 11:55:37 +01:00
brontomark 0bc8ae92b9 feat: add WhatsApp service and response model with dependency injection 2026-12-03 10:42:56 +01:00
42 changed files with 6666 additions and 608 deletions

No files matched your search

+16 -1
View File
@@ -66,8 +66,10 @@ import 'package:flux/features/tasks/blocs/task_list_cubit.dart';
import 'package:flux/features/tasks/models/task_model.dart';
import 'package:flux/features/tasks/ui/task_form_screen.dart';
import 'package:flux/features/tasks/ui/task_list_screen.dart';
import 'package:flux/features/tickets/blocs/public_ticket_cubit.dart';
import 'package:flux/features/tickets/blocs/ticket_form_cubit.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/tickets/ui/public_ticket_screen.dart';
import 'package:flux/features/tickets/ui/ticket_form_screen.dart';
import 'package:flux/features/tickets/ui/ticket_list_screen.dart';
import 'package:flux/features/tickets/ui/ticket_workspace/ticket_workspace_screen.dart';
@@ -109,8 +111,10 @@ class AppRouter {
final matched = state.matchedLocation;
final isPublicRoute = path.startsWith('/upload') ||
path.startsWith('/financing') ||
path.startsWith('/ticket/') ||
matched.startsWith('/upload') ||
matched.startsWith('/financing');
matched.startsWith('/financing') ||
matched.startsWith('/ticket/');
if (isPublicRoute) {
// Ritorna null esplicitamente per dire al router "Rimani qui e non fare altri controlli"
@@ -177,6 +181,17 @@ class AppRouter {
return FinancingFormScreen(sessionId: sessionId);
},
),
GoRoute(
path: '/ticket/:id',
name: Routes.publicTicket,
builder: (context, state) {
final ticketId = state.pathParameters['id'] ?? '';
return BlocProvider(
create: (_) => PublicTicketCubit(),
child: PublicTicketScreen(ticketId: ticketId),
);
},
),
// --- CORE APP (DENTRO LA SHELL CON NAVIGATION BAR/RAIL) ---
ShellRoute(
+1
View File
@@ -33,4 +33,5 @@ class Routes {
static const String financing = 'financing';
static const String customerOrders = 'customer-orders';
static const String customerOrderForm = 'customer-order-form';
static const String publicTicket = 'public-ticket';
}
@@ -0,0 +1,52 @@
import 'package:equatable/equatable.dart';
class EmailResponse extends Equatable {
final bool success;
final String? to;
final String? messageId;
final String? error;
const EmailResponse({
required this.success,
this.to,
this.messageId,
this.error,
});
static const empty = EmailResponse(success: false);
EmailResponse copyWith({
bool? success,
String? to,
String? messageId,
String? error,
}) {
return EmailResponse(
success: success ?? this.success,
to: to ?? this.to,
messageId: messageId ?? this.messageId,
error: error ?? this.error,
);
}
factory EmailResponse.fromMap(Map<String, dynamic> map) {
return EmailResponse(
success: map['success'] as bool? ?? false,
to: map['to'] as String?,
messageId: map['messageId'] as String?,
error: map['error'] as String?,
);
}
Map<String, dynamic> toMap() {
return {
'success': success,
if (to != null) 'to': to,
if (messageId != null) 'messageId': messageId,
if (error != null) 'error': error,
};
}
@override
List<Object?> get props => [success, to, messageId, error];
}
+158
View File
@@ -0,0 +1,158 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flux/core/services/email/email_response_model.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
/// Allegato binario codificato in base64 per la Edge Function `send-email`.
class EmailAttachment {
final String filename;
final Uint8List bytes;
final String contentType;
const EmailAttachment({
required this.filename,
required this.bytes,
this.contentType = 'application/pdf',
});
Map<String, dynamic> toMap() => {
'filename': filename,
'contentBase64': base64Encode(bytes),
'contentType': contentType,
};
}
/// Account mittente configurato sulla Edge Function `send-email`.
enum EmailSenderAccount {
ordini('ordini'),
assistenza('assistenza');
final String value;
const EmailSenderAccount(this.value);
}
class EmailService {
static const String _functionName = 'send-email';
static final RegExp _emailRegex = RegExp(r'^[^@\s]+@[^@\s]+\.[^@\s]+$');
final SupabaseClient _supabase;
EmailService(this._supabase);
/// Invia un'email tramite la Edge Function `send-email` (SMTP Stalwart).
Future<EmailResponse> sendEmail({
required String to,
required String subject,
required String text,
String? html,
String? replyTo,
EmailSenderAccount account = EmailSenderAccount.ordini,
List<EmailAttachment>? attachments,
}) async {
final cleanedTo = to.trim();
final cleanedSubject = subject.trim();
final cleanedText = text.trim();
if (cleanedTo.isEmpty) {
return const EmailResponse(
success: false,
error: 'Indirizzo email del cliente mancante.',
);
}
if (!_emailRegex.hasMatch(cleanedTo)) {
return EmailResponse(
success: false,
to: cleanedTo,
error: 'Indirizzo email non valido: $cleanedTo',
);
}
if (cleanedSubject.isEmpty || (cleanedText.isEmpty && (html?.trim().isEmpty ?? true))) {
return EmailResponse(
success: false,
to: cleanedTo,
error: 'Oggetto o contenuto email mancanti.',
);
}
try {
final response = await _supabase.functions.invoke(
_functionName,
body: {
'to': cleanedTo,
'subject': cleanedSubject,
'text': cleanedText,
'account': account.value,
if (html != null && html.trim().isNotEmpty) 'html': html.trim(),
if (replyTo != null && replyTo.trim().isNotEmpty)
'replyTo': replyTo.trim(),
if (attachments != null && attachments.isNotEmpty)
'attachments': attachments.map((a) => a.toMap()).toList(),
},
);
final data = _decodeData(response.data);
if (data != null) {
return EmailResponse.fromMap(data);
}
return EmailResponse(
success: response.status >= 200 && response.status < 300,
to: cleanedTo,
error: response.status >= 200 && response.status < 300
? null
: 'Risposta non valida dal server email (HTTP ${response.status}).',
);
} on FunctionException catch (e) {
debugPrint('EmailService FunctionException (${e.status}): ${e.details}');
final details = _decodeData(e.details);
if (details != null) {
final parsed = EmailResponse.fromMap(details);
return parsed.copyWith(
success: false,
to: parsed.to ?? cleanedTo,
error: parsed.error ?? e.reasonPhrase ?? 'Errore invio email.',
);
}
return EmailResponse(
success: false,
to: cleanedTo,
error:
e.reasonPhrase ??
'Errore di comunicazione con il server email (${e.status}).',
);
} catch (e) {
debugPrint('EmailService error: $e');
return EmailResponse(
success: false,
to: cleanedTo,
error: 'Impossibile contattare il servizio email: $e',
);
}
}
Map<String, dynamic>? _decodeData(dynamic raw) {
if (raw is Map<String, dynamic>) {
return raw;
}
if (raw is Map) {
return Map<String, dynamic>.from(raw);
}
if (raw is String && raw.trim().isNotEmpty) {
try {
final decoded = jsonDecode(raw);
if (decoded is Map<String, dynamic>) {
return decoded;
}
if (decoded is Map) {
return Map<String, dynamic>.from(decoded);
}
} catch (_) {
return null;
}
}
return null;
}
}
@@ -0,0 +1,81 @@
import 'package:equatable/equatable.dart';
class WhatsAppResponse extends Equatable {
final bool success;
final bool exists;
final String? phone;
final String? chatId;
final String? session;
final String? messageId;
final String? error;
const WhatsAppResponse({
required this.success,
required this.exists,
this.phone,
this.chatId,
this.session,
this.messageId,
this.error,
});
static const empty = WhatsAppResponse(
success: false,
exists: false,
);
WhatsAppResponse copyWith({
bool? success,
bool? exists,
String? phone,
String? chatId,
String? session,
String? messageId,
String? error,
}) {
return WhatsAppResponse(
success: success ?? this.success,
exists: exists ?? this.exists,
phone: phone ?? this.phone,
chatId: chatId ?? this.chatId,
session: session ?? this.session,
messageId: messageId ?? this.messageId,
error: error ?? this.error,
);
}
factory WhatsAppResponse.fromMap(Map<String, dynamic> map) {
return WhatsAppResponse(
success: map['success'] as bool? ?? false,
exists: map['exists'] as bool? ?? false,
phone: map['phone'] as String?,
chatId: map['chatId'] as String?,
session: map['session'] as String?,
messageId: map['messageId'] as String?,
error: map['error'] as String?,
);
}
Map<String, dynamic> toMap() {
return {
'success': success,
'exists': exists,
if (phone != null) 'phone': phone,
if (chatId != null) 'chatId': chatId,
if (session != null) 'session': session,
if (messageId != null) 'messageId': messageId,
if (error != null) 'error': error,
};
}
@override
List<Object?> get props => [
success,
exists,
phone,
chatId,
session,
messageId,
error,
];
}
@@ -0,0 +1,166 @@
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flux/core/services/whatsapp/whatsapp_response_model.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
class WhatsAppService {
static const String _functionName = 'send-whatsapp';
final SupabaseClient _supabase;
WhatsAppService(this._supabase);
/// Invia un messaggio WhatsApp tramite la Edge Function `send-whatsapp`.
Future<WhatsAppResponse> sendMessage({
required String phone,
required String message,
bool linkPreview = true,
}) async {
final cleanedPhone = phone.trim();
final cleanedMessage = message.trim();
if (cleanedPhone.isEmpty) {
return const WhatsAppResponse(
success: false,
exists: false,
error: 'Numero di telefono mancante.',
);
}
if (cleanedMessage.isEmpty) {
return const WhatsAppResponse(
success: false,
exists: false,
error: 'Il messaggio non può essere vuoto.',
);
}
return _invoke({
'phone': cleanedPhone,
'message': cleanedMessage,
'linkPreview': linkPreview,
});
}
/// Invia un documento (es. PDF ricevuta) su WhatsApp con eventuale didascalia.
Future<WhatsAppResponse> sendDocument({
required String phone,
required Uint8List bytes,
required String filename,
String? caption,
String mimetype = 'application/pdf',
}) async {
final cleanedPhone = phone.trim();
if (cleanedPhone.isEmpty) {
return const WhatsAppResponse(
success: false,
exists: false,
error: 'Numero di telefono mancante.',
);
}
final cleanedCaption = caption?.trim() ?? '';
return _invoke({
'phone': cleanedPhone,
if (cleanedCaption.isNotEmpty) 'message': cleanedCaption,
if (cleanedCaption.isNotEmpty) 'caption': cleanedCaption,
'file': {
'mimetype': mimetype,
'filename': filename,
'data': base64Encode(bytes),
},
});
}
/// Verifica se il numero è registrato su WhatsApp senza inviare alcun messaggio.
Future<WhatsAppResponse> checkNumber(String phone) async {
final cleanedPhone = phone.trim();
if (cleanedPhone.isEmpty) {
return const WhatsAppResponse(
success: false,
exists: false,
error: 'Numero di telefono mancante.',
);
}
return _invoke({
'phone': cleanedPhone,
'checkOnly': true,
});
}
/// Scorciatoia booleana per verificare se un numero ha WhatsApp attivo.
Future<bool> hasWhatsApp(String phone) async {
final result = await checkNumber(phone);
return result.exists;
}
Future<WhatsAppResponse> _invoke(Map<String, dynamic> body) async {
try {
final response = await _supabase.functions.invoke(
_functionName,
body: body,
);
final data = _decodeData(response.data);
if (data != null) {
return WhatsAppResponse.fromMap(data);
}
return WhatsAppResponse(
success: response.status >= 200 && response.status < 300,
exists: false,
error: response.status >= 200 && response.status < 300
? null
: 'Risposta non valida dal server (HTTP ${response.status}).',
);
} on FunctionException catch (e) {
debugPrint('WhatsAppService FunctionException (${e.status}): ${e.details}');
final details = _decodeData(e.details);
if (details != null) {
final parsed = WhatsAppResponse.fromMap(details);
return parsed.copyWith(
success: false,
error: parsed.error ?? e.reasonPhrase ?? 'Errore invio WhatsApp.',
);
}
return WhatsAppResponse(
success: false,
exists: false,
error: e.reasonPhrase ?? 'Errore di comunicazione con il server (${e.status}).',
);
} catch (e) {
debugPrint('WhatsAppService error: $e');
return WhatsAppResponse(
success: false,
exists: false,
error: 'Impossibile contattare il servizio WhatsApp: $e',
);
}
}
Map<String, dynamic>? _decodeData(dynamic raw) {
if (raw is Map<String, dynamic>) {
return raw;
}
if (raw is Map) {
return Map<String, dynamic>.from(raw);
}
if (raw is String && raw.trim().isNotEmpty) {
try {
final decoded = jsonDecode(raw);
if (decoded is Map<String, dynamic>) {
return decoded;
}
if (decoded is Map) {
return Map<String, dynamic>.from(decoded);
}
} catch (_) {
return null;
}
}
return null;
}
}
@@ -2,9 +2,14 @@ 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/core/services/email/email_service.dart';
import 'package:flux/core/services/whatsapp/whatsapp_service.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/customer_orders/models/order_notification_result.dart';
import 'package:flux/features/customer_orders/utils/customer_order_email_helper.dart';
import 'package:flux/features/customer_orders/utils/customer_order_whatsapp_helper.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';
@@ -16,6 +21,10 @@ class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final CustomerRepository _customerRepository = sl<CustomerRepository>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
final WhatsAppService _whatsAppService = sl<WhatsAppService>();
final EmailService _emailService = sl<EmailService>();
bool _pendingReceiptForDraft = false;
CustomerOrderFormCubit({
StaffMemberModel? createdBy,
@@ -236,18 +245,62 @@ class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
}
try {
final isBrandNew = orderToSave.id == null || orderToSave.id!.isEmpty;
final CustomerOrderModel saved;
if (orderToSave.id == null || orderToSave.id!.isEmpty) {
if (isBrandNew) {
saved = await _repository.insertOrder(orderToSave);
if (silentForAttachment) {
_pendingReceiptForDraft = true;
}
} else {
saved = await _repository.updateOrder(orderToSave);
}
await _syncCustomerAlternativePhone(orderToSave);
OrderNotificationResult? receiptNotificationResult;
final shouldSendReceipt =
!silentForAttachment && (isBrandNew || _pendingReceiptForDraft);
if (shouldSendReceipt) {
_pendingReceiptForDraft = false;
if (saved.contactPreference.isWhatsapp) {
final phone = saved.effectiveContactDestination;
final message = CustomerOrderWhatsAppHelper.buildOrderReceiptMessage(
saved,
);
final waRes = await _whatsAppService.sendMessage(
phone: phone,
message: message,
linkPreview: false,
);
receiptNotificationResult = OrderNotificationResult.fromWhatsApp(
waRes,
fallbackDestination: phone,
);
} else if (saved.contactPreference.isEmail) {
final email = saved.effectiveContactDestination;
final payload = CustomerOrderEmailHelper.buildOrderReceiptEmail(
saved,
);
final emailRes = await _emailService.sendEmail(
to: email,
subject: payload.subject,
text: payload.text,
html: payload.html,
);
receiptNotificationResult = OrderNotificationResult.fromEmail(
emailRes,
fallbackDestination: email,
);
}
}
final transitionedToArrived =
saved.status == CustomerOrderStatus.arrived &&
previousStatus != CustomerOrderStatus.arrived;
final transitionedToDelivered =
saved.status == CustomerOrderStatus.delivered &&
previousStatus != CustomerOrderStatus.delivered;
emit(
state.copyWith(
@@ -256,6 +309,8 @@ class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
: CustomerOrderFormStatus.saved,
order: saved,
justMarkedArrived: transitionedToArrived,
justMarkedDelivered: transitionedToDelivered,
receiptNotificationResult: receiptNotificationResult,
errorMessage: null,
),
);
@@ -16,6 +16,8 @@ class CustomerOrderFormState extends Equatable {
final List<String> availableTags;
final String? errorMessage;
final bool justMarkedArrived;
final bool justMarkedDelivered;
final OrderNotificationResult? receiptNotificationResult;
const CustomerOrderFormState({
this.status = CustomerOrderFormStatus.initial,
@@ -23,6 +25,8 @@ class CustomerOrderFormState extends Equatable {
this.availableTags = const [],
this.errorMessage,
this.justMarkedArrived = false,
this.justMarkedDelivered = false,
this.receiptNotificationResult,
});
CustomerOrderFormState copyWith({
@@ -31,6 +35,8 @@ class CustomerOrderFormState extends Equatable {
List<String>? availableTags,
String? errorMessage,
bool? justMarkedArrived,
bool? justMarkedDelivered,
OrderNotificationResult? receiptNotificationResult,
}) {
return CustomerOrderFormState(
status: status ?? this.status,
@@ -38,6 +44,8 @@ class CustomerOrderFormState extends Equatable {
availableTags: availableTags ?? this.availableTags,
errorMessage: errorMessage,
justMarkedArrived: justMarkedArrived ?? false,
justMarkedDelivered: justMarkedDelivered ?? false,
receiptNotificationResult: receiptNotificationResult,
);
}
@@ -48,5 +56,7 @@ class CustomerOrderFormState extends Equatable {
availableTags,
errorMessage,
justMarkedArrived,
justMarkedDelivered,
receiptNotificationResult,
];
}
@@ -0,0 +1,160 @@
import 'package:equatable/equatable.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/core/services/email/email_service.dart';
import 'package:flux/core/services/whatsapp/whatsapp_service.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/customer_orders/models/order_notification_result.dart';
import 'package:flux/features/customer_orders/utils/customer_order_email_helper.dart';
import 'package:flux/features/customer_orders/utils/customer_order_whatsapp_helper.dart';
import 'package:flux/service_locator.dart';
part 'mark_order_arrived_state.dart';
class MarkOrderArrivedCubit extends Cubit<MarkOrderArrivedState> {
final CustomerOrdersRepository _repository = sl<CustomerOrdersRepository>();
final WhatsAppService _whatsAppService = sl<WhatsAppService>();
final EmailService _emailService = sl<EmailService>();
MarkOrderArrivedCubit(CustomerOrderModel order)
: super(
MarkOrderArrivedState(
order: order,
sendAutoNotification:
order.contactPreference.isWhatsapp ||
order.contactPreference.isEmail,
),
);
void toggleSendAutoNotification(bool enabled) {
emit(state.copyWith(sendAutoNotification: enabled));
}
Future<void> confirmArrival({
required String externalCode,
required double price,
}) async {
emit(
state.copyWith(
step: MarkOrderArrivedStep.submitting,
clearErrorMessage: true,
clearNotificationResult: true,
),
);
try {
final updatedOrder = state.order.copyWith(
status: CustomerOrderStatus.arrived,
externalCode: externalCode.trim(),
price: price,
);
var saved = await _repository.updateOrder(updatedOrder);
OrderNotificationResult? notificationResult;
if (state.sendAutoNotification && state.supportsAutoNotification) {
notificationResult = await _sendArrivalNotification(saved);
if (notificationResult != null && notificationResult.success) {
saved = await _markNotifiedSafely(saved);
}
}
if (!isClosed) {
emit(
state.copyWith(
step: MarkOrderArrivedStep.completed,
order: saved,
notificationResult: notificationResult,
clearErrorMessage: true,
),
);
}
} catch (e) {
if (!isClosed) {
emit(
state.copyWith(
step: MarkOrderArrivedStep.editing,
errorMessage: e.toString(),
),
);
}
}
}
Future<void> retryNotification() async {
if (state.isBusy || !state.supportsAutoNotification) return;
emit(state.copyWith(step: MarkOrderArrivedStep.retryingNotification));
var currentOrder = state.order;
final notificationResult = await _sendArrivalNotification(currentOrder);
if (notificationResult != null && notificationResult.success) {
currentOrder = await _markNotifiedSafely(currentOrder);
}
if (!isClosed) {
emit(
state.copyWith(
step: MarkOrderArrivedStep.completed,
order: currentOrder,
notificationResult: notificationResult,
),
);
}
}
Future<OrderNotificationResult?> _sendArrivalNotification(
CustomerOrderModel order,
) async {
if (order.contactPreference.isWhatsapp) {
final phone = order.effectiveContactDestination;
final message = CustomerOrderWhatsAppHelper.buildOrderArrivedMessage(
order,
);
final waRes = await _whatsAppService.sendMessage(
phone: phone,
message: message,
linkPreview: false,
);
return OrderNotificationResult.fromWhatsApp(
waRes,
fallbackDestination: phone,
);
}
if (order.contactPreference.isEmail) {
final email = order.effectiveContactDestination;
final payload = CustomerOrderEmailHelper.buildOrderArrivedEmail(order);
final emailRes = await _emailService.sendEmail(
to: email,
subject: payload.subject,
text: payload.text,
html: payload.html,
);
return OrderNotificationResult.fromEmail(
emailRes,
fallbackDestination: email,
);
}
return null;
}
Future<CustomerOrderModel> _markNotifiedSafely(
CustomerOrderModel order,
) async {
try {
return await _repository.updateOrder(
order.copyWith(
customerNotified: true,
customerNotifiedAt: DateTime.now(),
),
);
} catch (_) {
return order.copyWith(
customerNotified: true,
customerNotifiedAt: DateTime.now(),
);
}
}
}
@@ -0,0 +1,62 @@
part of 'mark_order_arrived_cubit.dart';
enum MarkOrderArrivedStep {
editing,
submitting,
retryingNotification,
completed,
}
class MarkOrderArrivedState extends Equatable {
final MarkOrderArrivedStep step;
final CustomerOrderModel order;
final bool sendAutoNotification;
final OrderNotificationResult? notificationResult;
final String? errorMessage;
const MarkOrderArrivedState({
this.step = MarkOrderArrivedStep.editing,
required this.order,
required this.sendAutoNotification,
this.notificationResult,
this.errorMessage,
});
bool get supportsAutoNotification =>
order.contactPreference.isWhatsapp || order.contactPreference.isEmail;
bool get isBusy =>
step == MarkOrderArrivedStep.submitting ||
step == MarkOrderArrivedStep.retryingNotification;
MarkOrderArrivedState copyWith({
MarkOrderArrivedStep? step,
CustomerOrderModel? order,
bool? sendAutoNotification,
OrderNotificationResult? notificationResult,
bool clearNotificationResult = false,
String? errorMessage,
bool clearErrorMessage = false,
}) {
return MarkOrderArrivedState(
step: step ?? this.step,
order: order ?? this.order,
sendAutoNotification: sendAutoNotification ?? this.sendAutoNotification,
notificationResult: clearNotificationResult
? null
: (notificationResult ?? this.notificationResult),
errorMessage: clearErrorMessage
? null
: (errorMessage ?? this.errorMessage),
);
}
@override
List<Object?> get props => [
step,
order,
sendAutoNotification,
notificationResult,
errorMessage,
];
}
@@ -0,0 +1,87 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/services/email/email_response_model.dart';
import 'package:flux/core/services/whatsapp/whatsapp_response_model.dart';
enum OrderNotificationChannel {
whatsapp('WhatsApp'),
email('Email');
final String label;
const OrderNotificationChannel(this.label);
}
class OrderNotificationResult extends Equatable {
final OrderNotificationChannel channel;
final bool success;
final bool? whatsappExists;
final String? destination;
final String? error;
const OrderNotificationResult({
required this.channel,
required this.success,
this.whatsappExists,
this.destination,
this.error,
});
static const empty = OrderNotificationResult(
channel: OrderNotificationChannel.whatsapp,
success: false,
);
bool get isNumberNotOnWhatsApp =>
channel == OrderNotificationChannel.whatsapp &&
whatsappExists == false &&
(error?.toLowerCase().contains('whatsapp') ?? false);
factory OrderNotificationResult.fromWhatsApp(
WhatsAppResponse response, {
String? fallbackDestination,
}) {
return OrderNotificationResult(
channel: OrderNotificationChannel.whatsapp,
success: response.success,
whatsappExists: response.exists,
destination: response.phone ?? fallbackDestination,
error: response.error,
);
}
factory OrderNotificationResult.fromEmail(
EmailResponse response, {
String? fallbackDestination,
}) {
return OrderNotificationResult(
channel: OrderNotificationChannel.email,
success: response.success,
destination: response.to ?? fallbackDestination,
error: response.error,
);
}
OrderNotificationResult copyWith({
OrderNotificationChannel? channel,
bool? success,
bool? whatsappExists,
String? destination,
String? error,
}) {
return OrderNotificationResult(
channel: channel ?? this.channel,
success: success ?? this.success,
whatsappExists: whatsappExists ?? this.whatsappExists,
destination: destination ?? this.destination,
error: error ?? this.error,
);
}
@override
List<Object?> get props => [
channel,
success,
whatsappExists,
destination,
error,
];
}
@@ -1,6 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.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';
@@ -10,6 +11,7 @@ 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';
import 'package:url_launcher/url_launcher.dart';
@@ -202,6 +204,51 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
);
}
void _closeScreen() {
if (!mounted) return;
if (context.canPop()) {
context.pop();
} else {
context.goNamed(Routes.customerOrders);
}
}
Future<void> _showDeliveredSuccessDialog(CustomerOrderModel order) async {
final goToOrders = await showDialog<bool>(
context: context,
builder: (dialogCtx) {
return AlertDialog(
title: Row(
children: [
Icon(Icons.check_circle_rounded, color: Colors.green.shade600),
const SizedBox(width: 8),
const Expanded(child: Text('Consegna registrata!')),
],
),
content: Text(
'L\'ordine di ${order.customer?.name ?? 'Cliente'} (${order.productDescription}) è stato segnato come consegnato.',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogCtx, false),
child: const Text('Rimani qui'),
),
FilledButton(
style: FilledButton.styleFrom(
backgroundColor: Colors.green.shade600,
),
onPressed: () => Navigator.pop(dialogCtx, true),
child: const Text('Vai agli Ordini'),
),
],
);
},
);
if (goToOrders == true && mounted) {
_closeScreen();
}
}
Future<void> _confirmDelete(BuildContext context) async {
final cubit = context.read<CustomerOrderFormCubit>();
final ok = await showDialog<bool>(
@@ -248,7 +295,7 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
}
if (state.status == CustomerOrderFormStatus.deleted) {
Navigator.of(context).pop();
_closeScreen();
return;
}
@@ -264,12 +311,51 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
}
if (state.status == CustomerOrderFormStatus.saved) {
final receiptResult = state.receiptNotificationResult;
if (receiptResult != null && context.mounted) {
final channelLabel = receiptResult.channel.label;
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
receiptResult.success
? 'Ordine creato! Ricevuta $channelLabel inviata al cliente.'
: 'Ordine creato, ma ricevuta $channelLabel non inviata: ${receiptResult.error ?? 'errore sconosciuto'}',
),
backgroundColor: receiptResult.success
? Colors.green.shade700
: Colors.orange.shade800,
duration: Duration(seconds: receiptResult.success ? 3 : 5),
),
);
}
if (state.justMarkedArrived) {
await _showArrivedLabelPrompt(state.order);
}
if (state.justMarkedDelivered && context.mounted) {
if (!context.canPop()) {
await _showDeliveredSuccessDialog(state.order);
return;
}
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
'Ordine di ${state.order.customer?.name ?? 'Cliente'} segnato come consegnato!',
),
backgroundColor: Colors.green.shade700,
duration: const Duration(seconds: 3),
),
);
if (_closeAfterSave) {
_closeScreen();
}
return;
}
if (_closeAfterSave && context.mounted) {
Navigator.of(context).pop();
} else if (context.mounted) {
_closeScreen();
} else if (receiptResult == null && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ordine aggiornato con successo!'),
@@ -322,9 +408,10 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
child: LayoutBuilder(
builder: (context, constraints) {
final isDesktop = constraints.maxWidth > 920;
final isMobile = constraints.maxWidth < 650;
return SingleChildScrollView(
padding: const EdgeInsets.all(16.0),
padding: EdgeInsets.all(isMobile ? 12.0 : 16.0),
child: Center(
child: ConstrainedBox(
constraints: BoxConstraints(
@@ -339,10 +426,10 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
padding: const EdgeInsets.only(
left: 4,
right: 4,
bottom: 12,
bottom: 10,
),
child: Wrap(
spacing: 20,
spacing: 16,
runSpacing: 4,
children: [
Text(
@@ -382,7 +469,12 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
(order.status == CustomerOrderStatus.arrived ||
order.status ==
CustomerOrderStatus.delivered))
_buildCassaCheckoutBanner(context, theme, order),
_buildCassaCheckoutBanner(
context,
theme,
order,
isMobile: isMobile,
),
if (isDesktop)
Row(
@@ -395,6 +487,7 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
context,
theme,
order,
isMobile: false,
),
_buildAttachmentsCard(context, order),
],
@@ -406,14 +499,26 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
context,
theme,
state,
isMobile: false,
),
),
],
)
else ...[
_buildOrderRequestCard(context, theme, order),
_buildManagementCard(context, theme, state),
_buildAttachmentsCard(context, order),
_buildOrderRequestCard(
context,
theme,
order,
isMobile: isMobile,
),
_buildManagementCard(
context,
theme,
state,
isMobile: isMobile,
),
if (!isMobile)
_buildAttachmentsCard(context, order),
],
],
),
@@ -425,7 +530,10 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
),
bottomNavigationBar: SafeArea(
child: Container(
padding: const EdgeInsets.all(16.0),
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
vertical: 12.0,
),
decoration: BoxDecoration(
color: theme.scaffoldBackgroundColor,
boxShadow: [
@@ -455,8 +563,8 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
flex: 2,
child: FilledButton.icon(
style: FilledButton.styleFrom(
backgroundColor: order.status.color,
foregroundColor: Colors.white,
backgroundColor: theme.colorScheme.primary,
foregroundColor: theme.colorScheme.onPrimary,
padding: const EdgeInsets.symmetric(vertical: 14),
),
icon: state.status == CustomerOrderFormStatus.saving
@@ -492,8 +600,9 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
Widget _buildCassaCheckoutBanner(
BuildContext context,
ThemeData theme,
CustomerOrderModel order,
) {
CustomerOrderModel order, {
bool isMobile = false,
}) {
final currencyFmt = NumberFormat.currency(locale: 'it_IT', symbol: '€');
final livePrice = _parseAmount(_priceCtrl.text) > 0
? _parseAmount(_priceCtrl.text)
@@ -507,9 +616,105 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
: order.externalCode;
final isDelivered = order.status == CustomerOrderStatus.delivered;
final codeBox = Container(
width: isMobile ? double.infinity : null,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
decoration: BoxDecoration(
color: theme.colorScheme.surface,
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: theme.dividerColor.withValues(alpha: 0.5),
),
),
child: Row(
mainAxisSize: isMobile ? MainAxisSize.max : MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Expanded(
flex: isMobile ? 1 : 0,
child: 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),
),
);
},
),
],
],
),
);
final priceBox = Container(
width: isMobile ? double.infinity : null,
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
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,
),
),
],
),
);
return Container(
margin: const EdgeInsets.only(bottom: 20),
padding: const EdgeInsets.all(20),
margin: EdgeInsets.only(bottom: isMobile ? 14 : 20),
padding: EdgeInsets.all(isMobile ? 14 : 20),
decoration: BoxDecoration(
gradient: LinearGradient(
colors: isDelivered
@@ -540,211 +745,198 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
? Icons.check_circle_rounded
: Icons.point_of_sale_rounded,
color: isDelivered ? Colors.green.shade700 : Colors.teal.shade700,
size: 26,
size: isMobile ? 22 : 26,
),
const SizedBox(width: 10),
Expanded(
child: Text(
isDelivered
? 'ORDINE GIÀ CONSEGNATO AL CLIENTE'
: 'RIEPILOGO CASSA & CONSEGNA AL CLIENTE',
: 'RIEPILOGO CASSA & CONSEGNA',
style: TextStyle(
fontWeight: FontWeight.w900,
fontSize: 14,
letterSpacing: 0.5,
fontSize: isMobile ? 13 : 14,
letterSpacing: 0.4,
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,
if (!isMobile)
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<CustomerOrderFormCubit>().state.order,
);
},
),
onPressed: () {
_flushControllersToCubit();
_printQrLabel(
context.read<CustomerOrderFormCubit>().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,
),
),
],
Divider(height: isMobile ? 18 : 24),
if (isMobile) ...[
Text(
'CLIENTE',
style: TextStyle(
fontSize: 11,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
// 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),
),
);
},
),
],
],
),
Text(
order.customer?.name ?? 'Cliente sconosciuto',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
),
),
if (order.productDescription.isNotEmpty) ...[
const SizedBox(height: 2),
Text(
order.quantity > 1
? '${order.productDescription} ×${order.quantity}'
: order.productDescription,
style: theme.textTheme.bodyMedium?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
fontWeight: FontWeight.w600,
),
),
// 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(
],
const SizedBox(height: 12),
codeBox,
const SizedBox(height: 10),
priceBox,
] else
Wrap(
spacing: 24,
runSpacing: 14,
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
liveDeposit > 0
? 'DA INCASSARE (Prezzo ${currencyFmt.format(livePrice)} - Acconto ${currencyFmt.format(liveDeposit)})'
: 'PREZZO DA INCASSARE',
'CLIENTE',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w800,
fontSize: 11,
fontWeight: FontWeight.bold,
color: theme.colorScheme.onSurfaceVariant,
),
),
Text(
livePrice > 0
? currencyFmt.format(toPay)
: 'Prezzo non impostato',
style: TextStyle(
fontSize: 20,
order.customer?.name ?? 'Cliente sconosciuto',
style: theme.textTheme.titleLarge?.copyWith(
fontWeight: FontWeight.w900,
color: Colors.teal.shade700,
),
),
],
),
),
],
),
codeBox,
priceBox,
],
),
if (!isDelivered) ...[
const SizedBox(height: 16),
Wrap(
spacing: 10,
runSpacing: 10,
children: [
FilledButton.icon(
const SizedBox(height: 14),
if (isMobile) ...[
SizedBox(
width: double.infinity,
child: FilledButton.icon(
style: FilledButton.styleFrom(
backgroundColor: Colors.green.shade600,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
),
icon: const Icon(Icons.check_circle_outline_rounded),
label: const Text('Consegna al Cliente'),
label: const Text(
'Consegna al Cliente',
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 15),
),
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})',
),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: OutlinedButton.icon(
icon: order.contactPreference.buildIcon(size: 16),
label: Text(
order.customerNotified
? 'Ricontatta'
: 'Avvisa Cliente',
overflow: TextOverflow.ellipsis,
),
onPressed: () {
_flushControllersToCubit();
_launchCustomerContact(
context.read<CustomerOrderFormCubit>().state.order,
);
},
),
),
onPressed: () {
_flushControllersToCubit();
_launchCustomerContact(
context.read<CustomerOrderFormCubit>().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,
const SizedBox(width: 8),
TextButton.icon(
style: TextButton.styleFrom(foregroundColor: Colors.red),
icon: const Icon(Icons.cancel_outlined, size: 18),
label: const Text('Annulla'),
onPressed: () => _submitSave(
overrideStatus: CustomerOrderStatus.cancelled,
closeAfter: true,
),
),
),
],
),
],
),
] else
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<CustomerOrderFormCubit>().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,
),
),
],
),
],
],
),
@@ -757,14 +949,65 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
Widget _buildOrderRequestCard(
BuildContext context,
ThemeData theme,
CustomerOrderModel order,
) {
CustomerOrderModel order, {
bool isMobile = false,
}) {
final dateFmt = DateFormat('dd/MM/yyyy');
final productField = 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,
);
final quantityStepper = 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<CustomerOrderFormCubit>()
.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<CustomerOrderFormCubit>()
.updateFields(quantity: order.quantity + 1),
),
],
),
);
return _buildCard(
title: 'Richiesta Cliente',
icon: Icons.shopping_bag_outlined,
themeColor: Colors.indigo,
isMobile: isMobile,
headerTrailing: InkWell(
borderRadius: BorderRadius.circular(8),
onTap: () async {
@@ -863,61 +1106,30 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
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),
if (isMobile) ...[
productField,
const SizedBox(height: 12),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(
'Quantità',
style: theme.textTheme.bodyMedium?.copyWith(
fontWeight: FontWeight.w600,
),
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<CustomerOrderFormCubit>()
.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<CustomerOrderFormCubit>()
.updateFields(quantity: order.quantity + 1),
),
],
),
),
],
),
quantityStepper,
],
),
] else
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(child: productField),
const SizedBox(width: 12),
quantityStepper,
],
),
const SizedBox(height: 18),
// Modalità di Avviso Cliente
@@ -964,8 +1176,9 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
Widget _buildManagementCard(
BuildContext context,
ThemeData theme,
CustomerOrderFormState state,
) {
CustomerOrderFormState state, {
bool isMobile = false,
}) {
final order = state.order;
final dateTimeFmt = DateFormat('dd/MM/yyyy HH:mm');
@@ -973,6 +1186,7 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
title: 'Gestione Ordine, Etichette & Cassa',
icon: Icons.sell_outlined,
themeColor: Colors.teal,
isMobile: isMobile,
children: [
// Stato Ordine
Text(
@@ -1091,35 +1305,56 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
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(() {}),
),
if (isMobile) ...[
TextFormField(
controller: _externalCodeCtrl,
decoration: const InputDecoration(
labelText: 'Codice Esterno (Cassa)',
hintText: 'Codice articolo...',
prefixIcon: Icon(Icons.qr_code_scanner_rounded),
),
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(() {}),
),
onChanged: (_) => setState(() {}),
),
const SizedBox(height: 14),
TextFormField(
controller: _priceCtrl,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
decoration: const InputDecoration(
labelText: 'Prezzo Vendita (€)',
prefixIcon: Icon(Icons.euro_rounded),
),
],
),
onChanged: (_) => setState(() {}),
),
] else
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
@@ -1214,16 +1449,17 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
required Color themeColor,
required List<Widget> children,
Widget? headerTrailing,
bool isMobile = false,
}) {
return Card(
margin: const EdgeInsets.only(bottom: 20),
margin: EdgeInsets.only(bottom: isMobile ? 14 : 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),
padding: EdgeInsets.all(isMobile ? 14.0 : 20.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
@@ -1250,7 +1486,7 @@ class _CustomerOrderFormScreenState extends State<CustomerOrderFormScreen> {
?headerTrailing,
],
),
const Divider(height: 28),
Divider(height: isMobile ? 20 : 28),
...children,
],
),
@@ -6,6 +6,7 @@ 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/ui/mark_order_arrived_sheet.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';
@@ -564,6 +565,11 @@ class _CustomerOrderListScreenState extends State<CustomerOrderListScreen> {
PopupMenuButton<CustomerOrderStatus>(
tooltip: 'Cambia stato rapidamente',
onSelected: (newStatus) {
if (newStatus == CustomerOrderStatus.arrived &&
order.status != CustomerOrderStatus.arrived) {
showMarkOrderArrivedSheet(context, order);
return;
}
context
.read<CustomerOrderListCubit>()
.quickUpdateStatus(order, newStatus);
@@ -761,6 +767,32 @@ class _CustomerOrderListScreenState extends State<CustomerOrderListScreen> {
.toList(),
),
],
// Riga 5: Azione rapida "Segna arrivato" per ordini da ordinare / ordinati
if (status == CustomerOrderStatus.toOrder ||
status == CustomerOrderStatus.ordered) ...[
const SizedBox(height: 10),
Align(
alignment: Alignment.centerRight,
child: FilledButton.tonalIcon(
style: FilledButton.styleFrom(
backgroundColor: Colors.teal.withValues(alpha: 0.14),
foregroundColor: Colors.teal.shade800,
visualDensity: VisualDensity.compact,
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 8,
),
),
onPressed: () => showMarkOrderArrivedSheet(context, order),
icon: const Icon(Icons.inventory_2_rounded, size: 17),
label: const Text(
'Segna arrivato',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
),
],
],
),
),
@@ -0,0 +1,592 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/customer_orders/blocs/mark_order_arrived_cubit.dart';
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:flux/features/customer_orders/utils/customer_order_label_pdf_service.dart';
import 'package:intl/intl.dart';
import 'package:printing/printing.dart';
/// Apre la BottomSheet per confermare l'arrivo di un ordine cliente,
/// aggiornare codice cassa e prezzo, inviare l'avviso WhatsApp e stampare l'etichetta QR.
Future<void> showMarkOrderArrivedSheet(
BuildContext context,
CustomerOrderModel order,
) {
return showModalBottomSheet<void>(
context: context,
isScrollControlled: true,
useSafeArea: true,
showDragHandle: true,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(20)),
),
builder: (_) => BlocProvider(
create: (_) => MarkOrderArrivedCubit(order),
child: _MarkOrderArrivedSheetBody(initialOrder: order),
),
);
}
class _MarkOrderArrivedSheetBody extends StatefulWidget {
final CustomerOrderModel initialOrder;
const _MarkOrderArrivedSheetBody({required this.initialOrder});
@override
State<_MarkOrderArrivedSheetBody> createState() =>
_MarkOrderArrivedSheetBodyState();
}
class _MarkOrderArrivedSheetBodyState
extends State<_MarkOrderArrivedSheetBody> {
late final TextEditingController _externalCodeCtrl;
late final TextEditingController _priceCtrl;
final NumberFormat _currencyFmt = NumberFormat.currency(
locale: 'it_IT',
symbol: '€',
);
@override
void initState() {
super.initState();
_externalCodeCtrl = TextEditingController(
text: widget.initialOrder.externalCode,
);
_priceCtrl = TextEditingController(
text: widget.initialOrder.price > 0
? widget.initialOrder.price.toStringAsFixed(2)
: '',
);
}
@override
void dispose() {
_externalCodeCtrl.dispose();
_priceCtrl.dispose();
super.dispose();
}
double _parsePrice() {
final normalized = _priceCtrl.text.trim().replaceAll(',', '.');
return double.tryParse(normalized) ?? 0.0;
}
Future<void> _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(),
);
}
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final bottomInset = MediaQuery.of(context).viewInsets.bottom;
return BlocBuilder<MarkOrderArrivedCubit, MarkOrderArrivedState>(
builder: (context, state) {
final isCompleted =
state.step == MarkOrderArrivedStep.completed ||
state.step == MarkOrderArrivedStep.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,
MarkOrderArrivedState state,
) {
final order = state.order;
final pref = order.contactPreference;
final dest = order.effectiveContactDestination;
final currentPrice = _parsePrice();
final remaining = (currentPrice - order.deposit) > 0
? (currentPrice - order.deposit)
: 0.0;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.teal.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.inventory_2_rounded,
color: Colors.teal,
size: 24,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Segna ordine come Arrivato',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 2),
Text(
'${order.customer?.name ?? 'Cliente'} • ${order.productDescription}${order.quantity > 1 ? ' ×${order.quantity}' : ''}',
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
maxLines: 2,
overflow: TextOverflow.ellipsis,
),
],
),
),
],
),
const SizedBox(height: 18),
// Codice Cassa
TextField(
controller: _externalCodeCtrl,
enabled: !state.isBusy,
textCapitalization: TextCapitalization.characters,
decoration: const InputDecoration(
labelText: 'Codice Cassa / Articolo',
hintText: 'Es. COD-12345',
prefixIcon: Icon(Icons.qr_code_scanner_rounded),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 14),
// Prezzo di vendita
TextField(
controller: _priceCtrl,
enabled: !state.isBusy,
keyboardType: const TextInputType.numberWithOptions(decimal: true),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
],
onChanged: (_) => setState(() {}),
decoration: const InputDecoration(
labelText: 'Prezzo di vendita (€)',
hintText: '0.00',
prefixIcon: Icon(Icons.euro_rounded),
border: OutlineInputBorder(),
),
),
// Riepilogo acconto / residuo live
if (order.deposit > 0 || currentPrice > 0) ...[
const SizedBox(height: 10),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
decoration: BoxDecoration(
color: theme.colorScheme.surfaceContainerHighest.withValues(
alpha: 0.55,
),
borderRadius: BorderRadius.circular(10),
),
child: Wrap(
spacing: 16,
runSpacing: 4,
children: [
if (order.deposit > 0)
Text(
'Acconto: ${_currencyFmt.format(order.deposit)}',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: Colors.teal.shade700,
),
),
if (currentPrice > 0)
Text(
remaining > 0
? 'Residuo al ritiro: ${_currencyFmt.format(remaining)}'
: 'Già saldato',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w700,
color: remaining > 0
? theme.colorScheme.primary
: Colors.green.shade700,
),
),
],
),
),
],
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<MarkOrderArrivedCubit>()
.toggleSendAutoNotification(val),
secondary: pref.buildIcon(size: 20),
title: Text(
pref.isEmail
? 'Invia avviso Email al cliente'
: 'Invia avviso WhatsApp al cliente',
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),
// Pulsanti Azione
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.teal,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: state.isBusy
? null
: () => context
.read<MarkOrderArrivedCubit>()
.confirmArrival(
externalCode: _externalCodeCtrl.text,
price: _parsePrice(),
),
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 Arrivo',
),
),
),
],
),
],
);
}
Widget _buildCompletedView(
BuildContext context,
ThemeData theme,
MarkOrderArrivedState state,
) {
final order = state.order;
final result = state.notificationResult;
final isRetrying = state.step == MarkOrderArrivedStep.retryingNotification;
return Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// Header Conferma
Row(
children: [
Container(
padding: const EdgeInsets.all(10),
decoration: BoxDecoration(
color: Colors.teal.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.check_circle_rounded,
color: Colors.teal,
size: 26,
),
),
const SizedBox(width: 12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
'Ordine segnato come Arrivato!',
style: theme.textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
),
),
Text(
[
if (order.externalCode.isNotEmpty)
'Cod. Cassa: ${order.externalCode}',
if (order.price > 0)
'Prezzo: ${_currencyFmt.format(order.price)}',
].join(' • '),
style: theme.textTheme.bodySmall?.copyWith(
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
],
),
const SizedBox(height: 16),
// Esito Avviso Automatico (WhatsApp o Email)
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(
order.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 ?? order.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(
result.isNumberNotOnWhatsApp
? 'Numero non registrato su WhatsApp'
: '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: 4),
Text(
'L\'ordine rimane segnato "Da avvisare" così puoi contattare il cliente manualmente.',
style: TextStyle(
fontSize: 12,
color: theme.colorScheme.onSurfaceVariant,
),
),
],
),
),
],
),
const SizedBox(height: 10),
Align(
alignment: Alignment.centerRight,
child: OutlinedButton.icon(
onPressed: isRetrying
? null
: () => context
.read<MarkOrderArrivedCubit>()
.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(
'Ricordati di avvisare il cliente (${order.contactPreference.label}${order.effectiveContactDestination.isNotEmpty ? ': ${order.effectiveContactDestination}' : ''}).',
style: const TextStyle(fontSize: 12.5),
),
),
],
),
),
const SizedBox(height: 20),
// Proposta stampa etichetta QR
FilledButton.icon(
style: FilledButton.styleFrom(
padding: const EdgeInsets.symmetric(vertical: 14),
),
onPressed: isRetrying ? null : () => _printQrLabel(order),
icon: const Icon(Icons.print_rounded),
label: const Text('Stampa Etichetta QR'),
),
const SizedBox(height: 10),
OutlinedButton(
onPressed: isRetrying ? null : () => Navigator.pop(context),
child: const Text('Chiudi'),
),
],
);
}
}
@@ -0,0 +1,234 @@
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:intl/intl.dart';
typedef OrderEmailPayload = ({String subject, String text, String html});
/// Costruisce oggetto, testo semplice e HTML per le email degli Ordini Clienti.
class CustomerOrderEmailHelper {
CustomerOrderEmailHelper._();
static final NumberFormat _currencyFmt = NumberFormat.currency(
locale: 'it_IT',
symbol: '€',
);
static String _escapeHtml(String input) {
return input
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
static String _formatProduct(CustomerOrderModel order) {
final desc = order.productDescription.trim();
if (order.quantity > 1) {
return '$desc (x${order.quantity})';
}
return desc;
}
static List<({String label, String value, bool highlight})> _buildPriceRows(
CustomerOrderModel order, {
required bool isArrived,
}) {
final rows = <({String label, String value, bool highlight})>[];
if (order.price > 0) {
rows.add((
label: 'Prezzo di vendita',
value: _currencyFmt.format(order.price),
highlight: false,
));
if (order.deposit > 0) {
rows.add((
label: isArrived ? 'Acconto già versato' : 'Acconto versato',
value: _currencyFmt.format(order.deposit),
highlight: false,
));
if (order.remainingAmount > 0) {
rows.add((
label: isArrived
? 'Importo residuo al ritiro'
: 'Importo residuo da pagare',
value: _currencyFmt.format(order.remainingAmount),
highlight: true,
));
} else {
rows.add((
label: 'Stato pagamento',
value: 'Già saldato',
highlight: true,
));
}
} else {
rows.add((
label: isArrived ? 'Importo al ritiro' : 'Importo da pagare al ritiro',
value: _currencyFmt.format(order.price),
highlight: true,
));
}
} else if (order.deposit > 0) {
rows.add((
label: isArrived ? 'Acconto già versato' : 'Acconto versato',
value: _currencyFmt.format(order.deposit),
highlight: false,
));
if (!isArrived) {
rows.add((
label: 'Prezzo di vendita',
value: 'Da definire',
highlight: false,
));
}
} else if (!isArrived) {
rows.add((
label: 'Prezzo di vendita',
value: 'Da definire',
highlight: false,
));
}
return rows;
}
/// Email di ricevuta inviata alla creazione di un nuovo ordine cliente.
static OrderEmailPayload buildOrderReceiptEmail(CustomerOrderModel order) {
final customerName = order.customer?.name.trim() ?? '';
final greetingText = customerName.isNotEmpty
? 'Ciao $customerName,'
: 'Ciao,';
final greetingHtml = customerName.isNotEmpty
? 'Ciao <strong>${_escapeHtml(customerName)}</strong>,'
: 'Ciao,';
final product = _formatProduct(order);
final store = order.storeDisplayName?.trim() ?? '';
final storeSuffix = store.isNotEmpty
? ' presso il punto vendita $store'
: '';
final priceRows = _buildPriceRows(order, isArrived: false);
final subject = 'Conferma ordine: $product';
final textBuffer = StringBuffer()
..writeln(greetingText)
..writeln()
..writeln('Grazie per il tuo ordine di $product!')
..writeln();
for (final row in priceRows) {
textBuffer.writeln('- ${row.label}: ${row.value}');
}
textBuffer
..writeln()
..write(
'Ti avviseremo non appena sarà arrivato$storeSuffix e pronto per il ritiro.',
);
final html = _wrapHtmlEmail(
title: 'Conferma del tuo ordine',
accentColor: '#0f766e',
greetingHtml: greetingHtml,
introHtml:
'Grazie per il tuo ordine di <strong>${_escapeHtml(product)}</strong>!',
rows: [
(label: 'Prodotto', value: product, highlight: false),
...priceRows,
],
footerHtml:
'Ti avviseremo non appena il prodotto sarà arrivato${store.isNotEmpty ? ' presso il punto vendita <strong>${_escapeHtml(store)}</strong>' : ''} e pronto per il ritiro.',
);
return (subject: subject, text: textBuffer.toString(), html: html);
}
/// Email di avviso ritiro inviata quando il prodotto viene segnato come Arrivato.
static OrderEmailPayload buildOrderArrivedEmail(CustomerOrderModel order) {
final customerName = order.customer?.name.trim() ?? '';
final greetingText = customerName.isNotEmpty
? 'Ciao $customerName,'
: 'Ciao,';
final greetingHtml = customerName.isNotEmpty
? 'Ciao <strong>${_escapeHtml(customerName)}</strong>,'
: 'Ciao,';
final product = _formatProduct(order);
final store = order.storeDisplayName?.trim() ?? '';
final storeSuffix = store.isNotEmpty
? ' presso il punto vendita $store'
: '';
final priceRows = _buildPriceRows(order, isArrived: true);
final subject = 'Il tuo ordine è arrivato: $product';
final textBuffer = StringBuffer()
..writeln(greetingText)
..writeln()
..writeln('Il prodotto che hai ordinato ($product) è arrivato ed è pronto per il ritiro!')
..writeln();
for (final row in priceRows) {
textBuffer.writeln('- ${row.label}: ${row.value}');
}
textBuffer
..writeln()
..write('Ti aspettiamo$storeSuffix per il ritiro!');
final html = _wrapHtmlEmail(
title: 'Il tuo ordine è arrivato!',
accentColor: '#0d9488',
greetingHtml: greetingHtml,
introHtml:
'Ottime notizie: il prodotto che hai ordinato (<strong>${_escapeHtml(product)}</strong>) è arrivato ed è pronto per il ritiro.',
rows: [
(label: 'Prodotto', value: product, highlight: false),
...priceRows,
],
footerHtml:
'Ti aspettiamo${store.isNotEmpty ? ' presso il punto vendita <strong>${_escapeHtml(store)}</strong>' : ' in negozio'} per il ritiro!',
);
return (subject: subject, text: textBuffer.toString(), 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,
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();
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: 20px; background-color: #f8fafc; border-radius: 10px; padding: 12px;">
<tbody>
$rowsHtml
</tbody>
</table>
<p style="color: #334155; font-size: 15px; line-height: 1.6; margin: 0;">
$footerHtml
</p>
</div>
''';
}
}
@@ -1,42 +1,44 @@
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).
/// Genera il PDF dell'etichetta prodotto in orientamento verticale:
/// QR code grande in alto, nome cliente e descrizione prodotto in basso
/// (senza prezzo/codice cassa così l'operatore scansiona il QR alla consegna).
Future<pw.Document> generateOrderLabelPdf(CustomerOrderModel order) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
final company = GetIt.I.get<SessionCubit>().state.company;
final widthMm = company?.labelWidth ?? 40.0;
final heightMm = company?.labelHeight ?? 30.0;
final isVertical = company?.isLabelVertical ?? false;
final rawW = company?.labelWidth ?? 38.0;
final rawH = company?.labelHeight ?? 25.0;
final pageFormat = isVertical
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
: PdfPageFormat(widthMm * PdfPageFormat.mm, heightMm * PdfPageFormat.mm);
// Orientamento sempre verticale: lato corto come larghezza, lato lungo come altezza (es. 25x38mm)
final shortSideMm = rawW < rawH ? rawW : rawH;
final longSideMm = rawW > rawH ? rawW : rawH;
final effectiveW = pageFormat.width;
final effectiveH = pageFormat.height;
final minSide = effectiveW < effectiveH ? effectiveW : effectiveH;
final qrSize = (minSide - 6 * PdfPageFormat.mm).clamp(
final pageFormat = PdfPageFormat(
shortSideMm * PdfPageFormat.mm,
longSideMm * PdfPageFormat.mm,
);
const margin = 1.5 * PdfPageFormat.mm;
final contentWidth = pageFormat.width - (margin * 2);
// QR grande quasi quanto tutta la larghezza disponibile per lettura immediata su 25x38mm
final qrSize = (contentWidth - 1 * PdfPageFormat.mm).clamp(
14 * PdfPageFormat.mm,
26 * PdfPageFormat.mm,
24 * 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 ?? '');
@@ -44,67 +46,38 @@ class CustomerOrderLabelPdfService {
pdf.addPage(
pw.Page(
pageFormat: pageFormat,
margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm),
margin: const pw.EdgeInsets.all(margin),
build: (context) {
final infoBlock = pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
mainAxisAlignment: pw.MainAxisAlignment.center,
mainAxisSize: pw.MainAxisSize.min,
return pw.Column(
mainAxisAlignment: pw.MainAxisAlignment.start,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(
errorCorrectLevel: pw.BarcodeQRCorrectionLevel.low,
),
data: qrData,
width: qrSize,
height: qrSize,
),
pw.SizedBox(height: 1.5 * PdfPageFormat.mm),
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),
style: pw.TextStyle(font: boldFont, fontSize: 9.5),
textAlign: pw.TextAlign.center,
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,
pw.SizedBox(height: 0.8 * PdfPageFormat.mm),
pw.Expanded(
child: pw.Text(
productLine,
style: pw.TextStyle(font: font, fontSize: 7.2),
textAlign: pw.TextAlign.center,
maxLines: 2,
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,
),
],
);
},
@@ -0,0 +1,120 @@
import 'package:flux/features/customer_orders/models/customer_order_model.dart';
import 'package:intl/intl.dart';
/// Costruisce i messaggi WhatsApp formattati per gli Ordini Clienti.
class CustomerOrderWhatsAppHelper {
CustomerOrderWhatsAppHelper._();
static final NumberFormat _currencyFmt = NumberFormat.currency(
locale: 'it_IT',
symbol: '€',
);
static String _formatCustomerName(CustomerOrderModel order) {
final fullName = order.customer?.name.trim() ?? '';
if (fullName.isEmpty) return '';
return ' $fullName';
}
static String _formatProduct(CustomerOrderModel order) {
final desc = order.productDescription.trim();
if (order.quantity > 1) {
return '$desc (x${order.quantity})';
}
return desc;
}
static String _formatStoreSuffix(CustomerOrderModel order) {
final store = order.storeDisplayName?.trim() ?? '';
if (store.isEmpty) return '';
return ' presso il punto vendita *$store*';
}
/// Messaggio di ricevuta inviato alla creazione di un nuovo ordine cliente.
static String buildOrderReceiptMessage(CustomerOrderModel order) {
final namePart = _formatCustomerName(order);
final product = _formatProduct(order);
final storeSuffix = _formatStoreSuffix(order);
final buffer = StringBuffer()
..writeln('Ciao$namePart, grazie per il tuo ordine di *$product*!')
..writeln();
if (order.price > 0) {
buffer.writeln('• *Prezzo:* ${_currencyFmt.format(order.price)}');
if (order.deposit > 0) {
buffer.writeln(
'• *Acconto versato:* ${_currencyFmt.format(order.deposit)}',
);
if (order.remainingAmount > 0) {
buffer.writeln(
'• *Importo residuo da pagare:* ${_currencyFmt.format(order.remainingAmount)}',
);
} else {
buffer.writeln('• *Stato pagamento:* Già saldato');
}
} else {
buffer.writeln(
'• *Importo da pagare al ritiro:* ${_currencyFmt.format(order.price)}',
);
}
} else if (order.deposit > 0) {
buffer.writeln(
'• *Acconto versato:* ${_currencyFmt.format(order.deposit)}',
);
buffer.writeln('• *Prezzo di vendita:* da definire');
} else {
buffer.writeln('• *Prezzo di vendita:* da definire');
}
buffer
..writeln()
..write(
'Ti avviseremo non appena sarà arrivato$storeSuffix e pronto per il ritiro.',
);
return buffer.toString();
}
/// Messaggio di avviso ritiro inviato quando il prodotto viene segnato come Arrivato.
static String buildOrderArrivedMessage(CustomerOrderModel order) {
final namePart = _formatCustomerName(order);
final product = _formatProduct(order);
final storeSuffix = _formatStoreSuffix(order);
final buffer = StringBuffer()
..writeln('Ciao$namePart, il prodotto che hai ordinato è arrivato!')
..writeln()
..writeln('• *Prodotto:* $product');
if (order.price > 0) {
buffer.writeln('• *Prezzo:* ${_currencyFmt.format(order.price)}');
if (order.deposit > 0) {
buffer.writeln(
'• *Acconto già versato:* ${_currencyFmt.format(order.deposit)}',
);
if (order.remainingAmount > 0) {
buffer.writeln(
'• *Importo residuo al ritiro:* ${_currencyFmt.format(order.remainingAmount)}',
);
} else {
buffer.writeln('• *Stato pagamento:* Già saldato');
}
} else {
buffer.writeln(
'• *Importo al ritiro:* ${_currencyFmt.format(order.price)}',
);
}
} else if (order.deposit > 0) {
buffer.writeln(
'• *Acconto già versato:* ${_currencyFmt.format(order.deposit)}',
);
}
buffer
..writeln()
..write('Ti aspettiamo$storeSuffix per il ritiro!');
return buffer.toString();
}
}
@@ -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<MarkTicketReturnedState> {
final TicketRepository _ticketRepository = sl<TicketRepository>();
final TrackingRepository _trackingRepository = sl<TrackingRepository>();
final WhatsAppService _whatsAppService = sl<WhatsAppService>();
final EmailService _emailService = sl<EmailService>();
final SessionCubit _sessionCubit = sl<SessionCubit>();
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<void> 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<void> 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<TicketNotificationResult> _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',
);
}
}
@@ -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<Object?> get props => [
step,
ticket,
selectedResult,
sendAutoNotification,
notificationResult,
errorMessage,
];
}
@@ -0,0 +1,56 @@
import 'package:equatable/equatable.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tickets/models/public_ticket_model.dart';
import 'package:flux/service_locator.dart';
import 'package:supabase_flutter/supabase_flutter.dart';
part 'public_ticket_state.dart';
class PublicTicketCubit extends Cubit<PublicTicketState> {
final SupabaseClient _supabase = sl<SupabaseClient>();
PublicTicketCubit() : super(const PublicTicketState());
Future<void> loadTicket(String ticketId) async {
final cleanedId = ticketId.trim();
if (cleanedId.isEmpty) {
emit(const PublicTicketState(status: PublicTicketStatus.notFound));
return;
}
emit(state.copyWith(status: PublicTicketStatus.loading));
try {
final response = await _supabase.rpc(
'get_public_ticket',
params: {'p_ticket_id': cleanedId},
);
if (response == null) {
emit(const PublicTicketState(status: PublicTicketStatus.notFound));
return;
}
final map = response is Map<String, dynamic>
? response
: Map<String, dynamic>.from(response as Map);
emit(
PublicTicketState(
status: PublicTicketStatus.loaded,
ticket: PublicTicketModel.fromMap(map),
),
);
} catch (e) {
debugPrint('PublicTicketCubit.loadTicket error: $e');
emit(
PublicTicketState(
status: PublicTicketStatus.failure,
errorMessage:
'Impossibile caricare lo stato della pratica. Riprova tra poco.',
),
);
}
}
}
@@ -0,0 +1,30 @@
part of 'public_ticket_cubit.dart';
enum PublicTicketStatus { initial, loading, loaded, notFound, failure }
class PublicTicketState extends Equatable {
final PublicTicketStatus status;
final PublicTicketModel? ticket;
final String? errorMessage;
const PublicTicketState({
this.status = PublicTicketStatus.initial,
this.ticket,
this.errorMessage,
});
PublicTicketState copyWith({
PublicTicketStatus? status,
PublicTicketModel? ticket,
String? errorMessage,
}) {
return PublicTicketState(
status: status ?? this.status,
ticket: ticket ?? this.ticket,
errorMessage: errorMessage,
);
}
@override
List<Object?> get props => [status, ticket, errorMessage];
}
+335 -21
View File
@@ -1,14 +1,21 @@
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> {
@@ -16,6 +23,10 @@ class TicketFormCubit extends Cubit<TicketFormState> {
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})
@@ -185,7 +196,12 @@ class TicketFormCubit extends Cubit<TicketFormState> {
/// 5. SALVATAGGIO
Future<void> saveTicket() async {
emit(state.copyWith(status: TicketFormStatus.saving));
emit(
state.copyWith(
status: TicketFormStatus.saving,
clearNotificationResult: true,
),
);
try {
final ticketToSave = state.ticket;
@@ -194,20 +210,53 @@ class TicketFormCubit extends Cubit<TicketFormState> {
if (ticketToSave.customerId == null || ticketToSave.customerId!.isEmpty) {
throw Exception("Seleziona un cliente prima di salvare.");
}
TicketModel? savedTicket;
if (ticketToSave.id == null) {
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: ticketToSave.copyWith(
id: savedTicket.id,
referenceId: savedTicket.referenceId,
),
ticket: enrichedTicket,
notificationResult: notificationResult,
),
);
} catch (e) {
@@ -232,6 +281,7 @@ class TicketFormCubit extends Cubit<TicketFormState> {
}
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));
@@ -295,29 +345,40 @@ class TicketFormCubit extends Cubit<TicketFormState> {
}
}
Future<void> pauseTicket({
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;
if (currentTicket.id == null || currentTicket.id!.isEmpty) return null;
// 1. Usiamo lo stato esatto scelto dal tecnico
final updatedTicket = currentTicket.copyWith(ticketStatus: newStatus);
final hasQuote = quotePrice != null && quotePrice > 0;
final updatedTicket = currentTicket.copyWith(
ticketStatus: newStatus,
customerPrice: hasQuote ? quotePrice : currentTicket.customerPrice,
);
try {
await _repository.updateTicket(updatedTicket);
// 2. Componiamo un bel messaggio per la Timeline
// Es: "Sospeso per: waitingForQuote. Note: Cliente in ferie"
String timelineMessage = "Lavorazione sospesa (${newStatus.name}).";
if (notes.isNotEmpty) {
timelineMessage += " Note: $notes";
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: timelineMessage,
message: buffer.toString(),
type: TrackingType.statusChange,
parentId: currentTicket.id!,
parentType: TrackingParentType.ticket,
@@ -325,7 +386,30 @@ class TicketFormCubit extends Cubit<TicketFormState> {
isInternal: false,
);
emit(state.copyWith(ticket: updatedTicket));
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(
@@ -333,16 +417,18 @@ class TicketFormCubit extends Cubit<TicketFormState> {
errorMessage: 'Errore durante la sospensione: $e',
),
);
return null;
}
}
Future<void> completeTicket({
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;
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(
@@ -370,7 +456,23 @@ class TicketFormCubit extends Cubit<TicketFormState> {
isInternal: false,
);
emit(state.copyWith(ticket: updatedTicket));
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(
@@ -378,9 +480,221 @@ class TicketFormCubit extends Cubit<TicketFormState> {
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() ?? '';
@@ -1,6 +1,6 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
// Adatta gli import al tuo progetto!
import 'package:flux/features/tickets/models/ticket_notification_result.dart';
enum TicketFormStatus {
initial,
@@ -17,25 +17,37 @@ class TicketFormState extends Equatable {
final TicketModel ticket;
final TicketFormStatus status;
final String? errorMessage;
final TicketNotificationResult? notificationResult;
const TicketFormState({
required this.ticket,
this.status = TicketFormStatus.initial,
this.errorMessage,
this.notificationResult,
});
@override
List<Object?> get props => [ticket, status, errorMessage];
List<Object?> get props => [
ticket,
status,
errorMessage,
notificationResult,
];
TicketFormState copyWith({
TicketModel? ticket,
TicketFormStatus? status,
String? errorMessage,
TicketNotificationResult? notificationResult,
bool clearNotificationResult = false,
}) {
return TicketFormState(
ticket: ticket ?? this.ticket,
status: status ?? this.status,
errorMessage: errorMessage,
notificationResult: clearNotificationResult
? null
: (notificationResult ?? this.notificationResult),
);
}
}
@@ -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<TicketShippingState> {
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<TicketShippingState> {
}
}
}
Future<void> _notifyShippedTickets({
required List<TicketModel> tickets,
required TicketStatus newTicketStatus,
required String providerName,
}) async {
final trackingRepo = GetIt.I<TrackingRepository>();
final whatsApp = GetIt.I<WhatsAppService>();
final emailService = GetIt.I<EmailService>();
final staffId = GetIt.I<SessionCubit>().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');
}
}
}
}
@@ -0,0 +1,243 @@
import 'package:equatable/equatable.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
import 'package:flux/features/tracking/models/tracking_model.dart';
class PublicTicketTimelineItem extends Equatable {
final String id;
final DateTime createdAt;
final TrackingType eventType;
final String message;
const PublicTicketTimelineItem({
required this.id,
required this.createdAt,
required this.eventType,
required this.message,
});
static final empty = PublicTicketTimelineItem(
id: '',
createdAt: DateTime.fromMillisecondsSinceEpoch(0),
eventType: TrackingType.manualNote,
message: '',
);
PublicTicketTimelineItem copyWith({
String? id,
DateTime? createdAt,
TrackingType? eventType,
String? message,
}) {
return PublicTicketTimelineItem(
id: id ?? this.id,
createdAt: createdAt ?? this.createdAt,
eventType: eventType ?? this.eventType,
message: message ?? this.message,
);
}
factory PublicTicketTimelineItem.fromMap(Map<String, dynamic> map) {
return PublicTicketTimelineItem(
id: map['id']?.toString() ?? '',
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'].toString()).toLocal()
: DateTime.now(),
eventType: TrackingType.fromString(map['event_type']?.toString() ?? ''),
message: map['message']?.toString() ?? '',
);
}
@override
List<Object?> get props => [id, createdAt, eventType, message];
}
class PublicTicketModel extends Equatable {
final String id;
final String? referenceId;
final DateTime? createdAt;
final DateTime? closedAt;
final DateTime? returnedAt;
final DateTime? estimatedDeliveryAt;
final TicketType ticketType;
final TicketStatus ticketStatus;
final TicketResult? ticketResult;
final WarrantyType? warrantyType;
final String request;
final String? includedAccessories;
final bool hasCourtesyDevice;
final double customerPrice;
final String? publicNotes;
final String? resolutionNotes;
final String? targetModelName;
final String? customerName;
final String? companyName;
final String? companyPhone;
final String? companyEmail;
final String? companyAddress;
final String? companyCity;
final String? storeName;
final List<PublicTicketTimelineItem> timeline;
const PublicTicketModel({
required this.id,
this.referenceId,
this.createdAt,
this.closedAt,
this.returnedAt,
this.estimatedDeliveryAt,
this.ticketType = TicketType.repair,
this.ticketStatus = TicketStatus.open,
this.ticketResult,
this.warrantyType,
this.request = '',
this.includedAccessories,
this.hasCourtesyDevice = false,
this.customerPrice = 0.0,
this.publicNotes,
this.resolutionNotes,
this.targetModelName,
this.customerName,
this.companyName,
this.companyPhone,
this.companyEmail,
this.companyAddress,
this.companyCity,
this.storeName,
this.timeline = const [],
});
static const empty = PublicTicketModel(id: '');
PublicTicketModel copyWith({
String? id,
String? referenceId,
DateTime? createdAt,
DateTime? closedAt,
DateTime? returnedAt,
DateTime? estimatedDeliveryAt,
TicketType? ticketType,
TicketStatus? ticketStatus,
TicketResult? ticketResult,
WarrantyType? warrantyType,
String? request,
String? includedAccessories,
bool? hasCourtesyDevice,
double? customerPrice,
String? publicNotes,
String? resolutionNotes,
String? targetModelName,
String? customerName,
String? companyName,
String? companyPhone,
String? companyEmail,
String? companyAddress,
String? companyCity,
String? storeName,
List<PublicTicketTimelineItem>? timeline,
}) {
return PublicTicketModel(
id: id ?? this.id,
referenceId: referenceId ?? this.referenceId,
createdAt: createdAt ?? this.createdAt,
closedAt: closedAt ?? this.closedAt,
returnedAt: returnedAt ?? this.returnedAt,
estimatedDeliveryAt: estimatedDeliveryAt ?? this.estimatedDeliveryAt,
ticketType: ticketType ?? this.ticketType,
ticketStatus: ticketStatus ?? this.ticketStatus,
ticketResult: ticketResult ?? this.ticketResult,
warrantyType: warrantyType ?? this.warrantyType,
request: request ?? this.request,
includedAccessories: includedAccessories ?? this.includedAccessories,
hasCourtesyDevice: hasCourtesyDevice ?? this.hasCourtesyDevice,
customerPrice: customerPrice ?? this.customerPrice,
publicNotes: publicNotes ?? this.publicNotes,
resolutionNotes: resolutionNotes ?? this.resolutionNotes,
targetModelName: targetModelName ?? this.targetModelName,
customerName: customerName ?? this.customerName,
companyName: companyName ?? this.companyName,
companyPhone: companyPhone ?? this.companyPhone,
companyEmail: companyEmail ?? this.companyEmail,
companyAddress: companyAddress ?? this.companyAddress,
companyCity: companyCity ?? this.companyCity,
storeName: storeName ?? this.storeName,
timeline: timeline ?? this.timeline,
);
}
factory PublicTicketModel.fromMap(Map<String, dynamic> map) {
final rawTimeline = map['timeline'] as List? ?? const [];
return PublicTicketModel(
id: map['id']?.toString() ?? '',
referenceId: map['reference_id'] as String?,
createdAt: map['created_at'] != null
? DateTime.parse(map['created_at'].toString()).toLocal()
: null,
closedAt: map['closed_at'] != null
? DateTime.parse(map['closed_at'].toString()).toLocal()
: null,
returnedAt: map['returned_at'] != null
? DateTime.parse(map['returned_at'].toString()).toLocal()
: null,
estimatedDeliveryAt: map['estimated_delivery_at'] != null
? DateTime.parse(map['estimated_delivery_at'].toString()).toLocal()
: null,
ticketType: TicketType.fromString(map['ticket_type']?.toString() ?? ''),
ticketStatus: TicketStatus.fromString(map['ticket_status']?.toString()),
ticketResult: TicketResult.fromString(map['ticket_result']?.toString()),
warrantyType: map['warranty_type'] != null
? WarrantyType.fromString(map['warranty_type'].toString())
: null,
request: map['request']?.toString() ?? '',
includedAccessories: map['included_accessories'] as String?,
hasCourtesyDevice: map['has_courtesy_device'] as bool? ?? false,
customerPrice: (map['customer_price'] as num?)?.toDouble() ?? 0.0,
publicNotes: map['public_notes'] as String?,
resolutionNotes: map['resolution_notes'] as String?,
targetModelName: map['target_model_name'] as String?,
customerName: map['customer_name'] as String?,
companyName: map['company_name'] as String?,
companyPhone: map['company_phone'] as String?,
companyEmail: map['company_email'] as String?,
companyAddress: map['company_address'] as String?,
companyCity: map['company_city'] as String?,
storeName: map['store_name'] as String?,
timeline: rawTimeline
.whereType<Map>()
.map(
(e) => PublicTicketTimelineItem.fromMap(
Map<String, dynamic>.from(e),
),
)
.toList(),
);
}
@override
List<Object?> get props => [
id,
referenceId,
createdAt,
closedAt,
returnedAt,
estimatedDeliveryAt,
ticketType,
ticketStatus,
ticketResult,
warrantyType,
request,
includedAccessories,
hasCourtesyDevice,
customerPrice,
publicNotes,
resolutionNotes,
targetModelName,
customerName,
companyName,
companyPhone,
companyEmail,
companyAddress,
companyCity,
storeName,
timeline,
];
}
@@ -166,6 +166,28 @@ class TicketModel extends Equatable {
this.shippingDocument,
});
/// URL pubblico (senza login) per far seguire al cliente lo stato del ticket
String get publicTrackingUrl =>
id != null && id!.isNotEmpty ? 'https://flux.catelli.it/ticket/$id' : '';
/// URL interno (per QR etichetta sacchetto) che apre direttamente la scheda ticket in FLUX
String get internalDeepLinkUrl => id != null && id!.isNotEmpty
? 'https://flux.catelli.it/tickets/form/$id'
: '';
/// Recapito effettivo da usare in base alla preferenza di contatto scelta
String get effectiveContactDestination {
if (contactPreference.isEmail) {
return customer?.email.trim() ?? '';
}
if (contactPreference.usesAlternativePhone) {
final ticketAlt = alternativePhoneNumber?.trim() ?? '';
if (ticketAlt.isNotEmpty) return ticketAlt;
return customer?.alternativePhoneNumber.trim() ?? '';
}
return customer?.phoneNumber.trim() ?? '';
}
/// Factory per creare un ticket vuoto (utile per i form di creazione)
factory TicketModel.empty({String? companyId, String? storeId}) {
return TicketModel(
@@ -0,0 +1,91 @@
import 'package:equatable/equatable.dart';
import 'package:flux/core/services/email/email_response_model.dart';
import 'package:flux/core/services/whatsapp/whatsapp_response_model.dart';
enum TicketNotificationChannel {
whatsapp('WhatsApp'),
email('Email');
final String label;
const TicketNotificationChannel(this.label);
}
class TicketNotificationResult extends Equatable {
final TicketNotificationChannel channel;
final bool success;
final bool? whatsappExists;
final String? destination;
final String? error;
final String contextLabel;
const TicketNotificationResult({
required this.channel,
required this.success,
this.whatsappExists,
this.destination,
this.error,
this.contextLabel = 'Avviso',
});
static const empty = TicketNotificationResult(
channel: TicketNotificationChannel.whatsapp,
success: false,
);
factory TicketNotificationResult.fromWhatsApp(
WhatsAppResponse response, {
String? fallbackDestination,
String contextLabel = 'Avviso',
}) {
return TicketNotificationResult(
channel: TicketNotificationChannel.whatsapp,
success: response.success,
whatsappExists: response.exists,
destination: response.phone ?? fallbackDestination,
error: response.error,
contextLabel: contextLabel,
);
}
factory TicketNotificationResult.fromEmail(
EmailResponse response, {
String? fallbackDestination,
String contextLabel = 'Avviso',
}) {
return TicketNotificationResult(
channel: TicketNotificationChannel.email,
success: response.success,
destination: response.to ?? fallbackDestination,
error: response.error,
contextLabel: contextLabel,
);
}
TicketNotificationResult copyWith({
TicketNotificationChannel? channel,
bool? success,
bool? whatsappExists,
String? destination,
String? error,
String? contextLabel,
}) {
return TicketNotificationResult(
channel: channel ?? this.channel,
success: success ?? this.success,
whatsappExists: whatsappExists ?? this.whatsappExists,
destination: destination ?? this.destination,
error: error ?? this.error,
contextLabel: contextLabel ?? this.contextLabel,
);
}
@override
List<Object?> get props => [
channel,
success,
whatsappExists,
destination,
error,
contextLabel,
];
}
@@ -0,0 +1,822 @@
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,
),
),
],
),
),
],
),
);
}
}
+319 -40
View File
@@ -1,7 +1,9 @@
import 'package:flutter/foundation.dart'; // Per kIsWeb
import 'dart:io' show Platform;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flux/features/tickets/models/ticket_notification_result.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';
@@ -19,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';
@@ -215,8 +218,9 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
void _showSuccessActions(
BuildContext context,
TicketModel ticket,
CompanyModel company,
) {
CompanyModel company, {
TicketNotificationResult? notificationResult,
}) {
showModalBottomSheet(
context: context,
isDismissible: false, // Costringiamo l'operatore a una scelta conscia
@@ -224,7 +228,7 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
),
builder: (context) => SafeArea(
builder: (sheetCtx) => SafeArea(
child: SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
@@ -243,7 +247,7 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
const SizedBox(height: 16),
Text(
"Ticket Salvato!",
style: Theme.of(context).textTheme.headlineSmall?.copyWith(
style: Theme.of(sheetCtx).textTheme.headlineSmall?.copyWith(
fontWeight: FontWeight.bold,
),
),
@@ -251,7 +255,52 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
"Rif: ${ticket.referenceId}",
style: TextStyle(color: Colors.grey[600], fontSize: 18),
),
const SizedBox(height: 32),
if (notificationResult != null) ...[
const SizedBox(height: 16),
Container(
width: double.infinity,
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: notificationResult.success
? Colors.green.withValues(alpha: 0.12)
: Colors.orange.withValues(alpha: 0.14),
borderRadius: BorderRadius.circular(12),
border: Border.all(
color: notificationResult.success
? Colors.green.withValues(alpha: 0.5)
: Colors.orange.shade700,
),
),
child: Row(
children: [
Icon(
notificationResult.success
? Icons.check_circle_outline_rounded
: Icons.warning_amber_rounded,
color: notificationResult.success
? Colors.green.shade700
: Colors.orange.shade900,
),
const SizedBox(width: 10),
Expanded(
child: Text(
notificationResult.success
? '${notificationResult.contextLabel} PDF inviata via ${notificationResult.channel.label} (${notificationResult.destination ?? ''}).'
: '${notificationResult.contextLabel} via ${notificationResult.channel.label} non inviata: ${notificationResult.error ?? 'errore sconosciuto'}',
style: TextStyle(
fontSize: 12.5,
fontWeight: FontWeight.w600,
color: notificationResult.success
? Colors.green.shade800
: Colors.orange.shade900,
),
),
),
],
),
),
],
const SizedBox(height: 24),
// Griglia delle Azioni
GridView.count(
@@ -261,50 +310,25 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
crossAxisSpacing: 16,
childAspectRatio: 1.5,
children: [
_ActionButton(
icon: Icons.print,
label: "Ricevuta A4",
onTap: () async {
final doc = await TicketPdfService()
.generateTicketReceipt(ticket);
final bytes = await doc.save();
final fileName = 'Ricevuta_${ticket.referenceId}.pdf';
await Printing.layoutPdf(
onLayout: (format) async => bytes,
name: fileName,
);
/* if (kIsWeb || Platform.isMacOS) {
// Forza il download/salvataggio senza passare per il print spooler
await Printing.sharePdf(
bytes: bytes,
filename: fileName,
);
} else {
// Su Android/iOS continuiamo a usare la stampa diretta che funziona
} */
},
),
if (company.labelFormat != LabelFormat.none)
_ActionButton(
icon: Icons.label,
label: "Etichetta",
icon: Icons.qr_code_2_rounded,
label: "Etichetta Sacchetto",
color: Colors.teal.shade700,
textColor: Colors.white,
onTap: () async {
final doc = await TicketPdfService().generateLabelPdf(
ticket,
);
final bytes = await doc.save();
final fileName = 'Ricevuta_${ticket.referenceId}.pdf';
final fileName = 'Etichetta_${ticket.referenceId}.pdf';
if (kIsWeb || Platform.isMacOS) {
// Forza il download/salvataggio senza passare per il print spooler
await Printing.sharePdf(
bytes: bytes,
filename: fileName,
);
} else {
// Su Android/iOS continuiamo a usare la stampa diretta che funziona
await Printing.layoutPdf(
onLayout: (format) async => bytes,
name: fileName,
@@ -313,9 +337,46 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
},
),
_ActionButton(
icon: Icons.email,
label: "Invia Email",
onTap: ticket.customer!.email.isNotEmpty ? () {} : null,
icon: Icons.print,
label: "Ricevuta Cliente",
color: (notificationResult == null ||
!notificationResult.success)
? Colors.indigo.shade600
: null,
textColor: (notificationResult == null ||
!notificationResult.success)
? Colors.white
: null,
onTap: () async {
final doc = await TicketPdfService()
.generateCustomerReceiptPdf(ticket);
final bytes = await doc.save();
final fileName =
'Ricevuta_Cliente_${ticket.referenceId}.pdf';
await Printing.layoutPdf(
onLayout: (format) async => bytes,
name: fileName,
);
},
),
_ActionButton(
icon: Icons.link_rounded,
label: "Copia Link Stato",
onTap: ticket.publicTrackingUrl.isNotEmpty
? () {
Clipboard.setData(
ClipboardData(text: ticket.publicTrackingUrl),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Link pagina stato copiato negli appunti!',
),
duration: Duration(seconds: 2),
),
);
}
: null,
),
_ActionButton(
icon: Icons.close,
@@ -323,8 +384,12 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
color: Colors.blue[900],
textColor: Colors.white,
onTap: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
Navigator.of(sheetCtx).pop();
if (context.canPop()) {
context.pop();
} else {
context.goNamed(Routes.tickets);
}
},
),
],
@@ -336,6 +401,156 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
);
}
Future<void> _showSendQuoteDialog(
BuildContext context,
TicketModel ticket,
) async {
final priceCtrl = TextEditingController(
text: ticket.customerPrice > 0
? ticket.customerPrice.toStringAsFixed(2)
: '',
);
final notesCtrl = TextEditingController();
final canAutoNotify =
ticket.contactPreference.isWhatsapp || ticket.contactPreference.isEmail;
var notifyCustomer = canAutoNotify;
final result = await showDialog<({double price, String notes, bool notify})>(
context: context,
builder: (dialogCtx) {
return StatefulBuilder(
builder: (dialogCtx, setDialogState) {
return AlertDialog(
title: const Row(
children: [
Icon(Icons.request_quote_outlined, color: Colors.amber),
SizedBox(width: 8),
Expanded(child: Text('Emetti Preventivo')),
],
),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
TextField(
controller: priceCtrl,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
],
decoration: const InputDecoration(
labelText: 'Importo preventivo (€) *',
hintText: 'Es. 89.00',
prefixIcon: Icon(Icons.euro_rounded),
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
TextField(
controller: notesCtrl,
maxLines: 3,
decoration: const InputDecoration(
labelText: 'Dettagli per il cliente (opzionale)',
hintText: 'Es. Sostituzione display originale...',
border: OutlineInputBorder(),
),
),
if (canAutoNotify) ...[
const SizedBox(height: 12),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: notifyCustomer,
onChanged: (val) =>
setDialogState(() => notifyCustomer = val),
title: Text(
ticket.contactPreference.isEmail
? 'Invia preventivo via Email'
: 'Invia preventivo su WhatsApp',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
),
),
subtitle: Text(
ticket.effectiveContactDestination,
style: const TextStyle(fontSize: 12),
),
),
],
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(dialogCtx),
child: const Text('Annulla'),
),
FilledButton.icon(
onPressed: () {
final parsed = double.tryParse(
priceCtrl.text.trim().replaceAll(',', '.'),
);
if (parsed == null || parsed <= 0) return;
Navigator.pop(dialogCtx, (
price: parsed,
notes: notesCtrl.text.trim(),
notify: notifyCustomer,
));
},
icon: const Icon(Icons.send_rounded, size: 18),
label: const Text('Conferma Preventivo'),
),
],
);
},
);
},
);
priceCtrl.dispose();
notesCtrl.dispose();
if (result == null || !context.mounted) return;
final notifResult = await context.read<TicketFormCubit>().sendQuote(
price: result.price,
notes: result.notes,
notifyCustomer: result.notify,
);
if (!context.mounted) return;
_priceCtrl.text = result.price.toStringAsFixed(2);
if (ticket.id != null) {
context.read<TrackingCubit>().loadTrackings(
ticket.id!,
TrackingParentType.ticket,
);
}
context.read<TicketListCubit>().loadTickets(refresh: true);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
notifResult == null
? 'Preventivo salvato e visibile sulla pagina stato.'
: notifResult.success
? 'Preventivo inviato al cliente via ${notifResult.channel.label}!'
: 'Preventivo salvato, ma invio ${notifResult.channel.label} non riuscito: ${notifResult.error ?? 'errore'}',
),
backgroundColor: notifResult == null || notifResult.success
? Colors.green.shade700
: Colors.orange.shade800,
duration: Duration(
seconds: notifResult == null || notifResult.success ? 3 : 5,
),
),
);
}
void _navigateToWorkspace(String ticketId) async {
final formCubit = context.read<TicketFormCubit>();
final trackingCubit = context.read<TrackingCubit>();
@@ -409,6 +624,7 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
context,
state.ticket,
GetIt.I.get<SessionCubit>().state.company!,
notificationResult: state.notificationResult,
);
} else if (state.status == TicketFormStatus.pop) {
Navigator.of(context).pop();
@@ -433,6 +649,30 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
),
actions: [
if (ticket.id != null) ...[
if (ticket.ticketStatus != TicketStatus.closed)
IconButton(
tooltip: 'Emetti / Invia Preventivo al cliente',
onPressed: () => _showSendQuoteDialog(context, ticket),
icon: const Icon(Icons.request_quote_outlined),
),
if (ticket.publicTrackingUrl.isNotEmpty)
IconButton(
tooltip: 'Copia link stato pratica per il cliente',
onPressed: () {
Clipboard.setData(
ClipboardData(text: ticket.publicTrackingUrl),
);
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Link pagina stato copiato negli appunti!',
),
duration: Duration(seconds: 2),
),
);
},
icon: const Icon(Icons.link_rounded),
),
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16.0,
@@ -474,6 +714,45 @@ class _TicketFormScreenState extends State<TicketFormScreen> {
),
),
],
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<TicketFormCubit>().initForm(
existingTicket: updated,
);
if (!context.mounted) return;
_priceCtrl.text = updated.customerPrice > 0
? updated.customerPrice.toStringAsFixed(2)
: '';
context.read<TrackingCubit>().loadTrackings(
ticket.id!,
TrackingParentType.ticket,
);
context.read<TicketListCubit>().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(
@@ -1,22 +1,42 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
Future<({TicketResult result, double finalPrice})?> showCompletionTicketDialog(
typedef CompletionTicketDialogResult = ({
TicketResult result,
double finalPrice,
bool notifyCustomer,
});
Future<CompletionTicketDialogResult?> showCompletionTicketDialog(
BuildContext context, {
required double calculatedTotal,
ContactPreference contactPreference = ContactPreference.whatsappPrimary,
String contactDestination = '',
}) async {
return showDialog<({TicketResult result, double finalPrice})>(
return showDialog<CompletionTicketDialogResult>(
context: context,
barrierDismissible: false, // Obbliga l'utente a premere un bottone
builder: (context) => CompletionTicketDialog(initialTotal: calculatedTotal),
barrierDismissible: false,
builder: (context) => CompletionTicketDialog(
initialTotal: calculatedTotal,
contactPreference: contactPreference,
contactDestination: contactDestination,
),
);
}
class CompletionTicketDialog extends StatefulWidget {
final double initialTotal;
final ContactPreference contactPreference;
final String contactDestination;
const CompletionTicketDialog({super.key, required this.initialTotal});
const CompletionTicketDialog({
super.key,
required this.initialTotal,
required this.contactPreference,
required this.contactDestination,
});
@override
State<CompletionTicketDialog> createState() => _CompletionTicketDialogState();
@@ -24,15 +44,19 @@ class CompletionTicketDialog extends StatefulWidget {
class _CompletionTicketDialogState extends State<CompletionTicketDialog> {
late final TextEditingController _priceCtrl;
TicketResult _selectedResult = TicketResult.success; // Default: Riparato!
TicketResult _selectedResult = TicketResult.success;
late bool _notifyCustomer;
bool get _canAutoNotify =>
widget.contactPreference.isWhatsapp || widget.contactPreference.isEmail;
@override
void initState() {
super.initState();
// Inizializziamo il campo testuale con il totale calcolato
_priceCtrl = TextEditingController(
text: widget.initialTotal.toStringAsFixed(2),
);
_notifyCustomer = _canAutoNotify;
}
@override
@@ -44,6 +68,8 @@ class _CompletionTicketDialogState extends State<CompletionTicketDialog> {
@override
Widget build(BuildContext context) {
final theme = Theme.of(context);
final pref = widget.contactPreference;
final dest = widget.contactDestination.trim();
return AlertDialog(
title: const Row(
@@ -54,79 +80,113 @@ class _CompletionTicketDialogState extends State<CompletionTicketDialog> {
],
),
content: SizedBox(
width: double.maxFinite, // Per allargare bene la modale
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Specifica l\'esito della lavorazione e il totale da incassare.',
),
const SizedBox(height: 24),
width: double.maxFinite,
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Specifica l\'esito della lavorazione e il totale da incassare.',
),
const SizedBox(height: 20),
// --- ESITO LAVORAZIONE (Choice Chips) ---
const Text('Esito:', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: ChoiceChip(
label: const Center(child: Text('Riparato')),
selectedColor: Colors.green.withValues(alpha: 0.2),
selected: _selectedResult == TicketResult.success,
onSelected: (selected) {
if (selected) {
setState(() => _selectedResult = TicketResult.success);
}
},
const Text('Esito:', style: TextStyle(fontWeight: FontWeight.bold)),
const SizedBox(height: 8),
Row(
children: [
Expanded(
child: ChoiceChip(
label: const Center(child: Text('Riparato')),
selectedColor: Colors.green.withValues(alpha: 0.2),
selected: _selectedResult == TicketResult.success,
onSelected: (selected) {
if (selected) {
setState(() => _selectedResult = TicketResult.success);
}
},
),
),
const SizedBox(width: 8),
Expanded(
child: ChoiceChip(
label: const Center(child: Text('Non Riparato')),
selectedColor: Colors.red.withValues(alpha: 0.2),
selected: _selectedResult == TicketResult.failure,
onSelected: (selected) {
if (selected) {
setState(() => _selectedResult = TicketResult.failure);
}
},
),
),
],
),
const SizedBox(height: 20),
const Text(
'Totale da pagare al ritiro:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
TextFormField(
controller: _priceCtrl,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
const SizedBox(width: 8),
Expanded(
child: ChoiceChip(
label: const Center(child: Text('Non Riparato')),
selectedColor: Colors.red.withValues(alpha: 0.2),
selected: _selectedResult == TicketResult.failure,
onSelected: (selected) {
if (selected) {
setState(() => _selectedResult = TicketResult.failure);
}
},
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
],
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.bold,
),
decoration: InputDecoration(
prefixIcon: const Icon(Icons.euro),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
filled: true,
fillColor: theme.colorScheme.surfaceContainerHighest
.withValues(alpha: 0.3),
),
),
if (_canAutoNotify) ...[
const SizedBox(height: 18),
Container(
decoration: BoxDecoration(
color: pref.color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: pref.color.withValues(alpha: 0.35),
),
),
child: SwitchListTile(
dense: true,
value: _notifyCustomer,
onChanged: (val) => setState(() => _notifyCustomer = val),
secondary: pref.buildIcon(size: 18),
title: Text(
pref.isEmail
? 'Invia avviso ritiro via Email'
: 'Invia avviso ritiro su WhatsApp',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13.5,
),
),
subtitle: Text(
dest.isNotEmpty
? dest
: 'Recapito mancante in anagrafica',
style: const TextStyle(fontSize: 12),
),
),
),
],
),
const SizedBox(height: 24),
// --- PREZZO FINALE ---
const Text(
'Totale da pagare al ritiro:',
style: TextStyle(fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
TextFormField(
controller: _priceCtrl,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
inputFormatters: [
FilteringTextInputFormatter.allow(
RegExp(r'[0-9.,]'),
), // Solo numeri, punti e virgole
],
style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
decoration: InputDecoration(
prefixIcon: const Icon(Icons.euro),
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(12),
),
filled: true,
fillColor: theme.colorScheme.surfaceContainerHighest.withValues(
alpha: 0.3,
),
),
),
],
],
),
),
),
actions: [
@@ -137,13 +197,14 @@ class _CompletionTicketDialogState extends State<CompletionTicketDialog> {
FilledButton.icon(
style: FilledButton.styleFrom(backgroundColor: Colors.green.shade600),
onPressed: () {
// Conversione sicura: cambiamo un'eventuale virgola italiana in punto
final safePriceText = _priceCtrl.text.replaceAll(',', '.');
final finalPrice = double.tryParse(safePriceText) ?? 0.0;
Navigator.of(
context,
).pop((result: _selectedResult, finalPrice: finalPrice));
Navigator.of(context).pop((
result: _selectedResult,
finalPrice: finalPrice,
notifyCustomer: _notifyCustomer,
));
},
icon: const Icon(Icons.save),
label: const Text('Conferma Completamento'),
@@ -1,17 +1,42 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flux/core/enums_and_consts/contact_preference.dart';
import 'package:flux/features/tickets/models/ticket_model.dart';
Future<({TicketStatus status, String reason})?> showPauseTicketDialog(
BuildContext context,
) async {
return showDialog<({TicketStatus status, String reason})>(
typedef PauseTicketDialogResult = ({
TicketStatus status,
String reason,
bool notifyCustomer,
double? quotePrice,
});
Future<PauseTicketDialogResult?> showPauseTicketDialog(
BuildContext context, {
ContactPreference contactPreference = ContactPreference.whatsappPrimary,
String contactDestination = '',
double initialPrice = 0.0,
}) async {
return showDialog<PauseTicketDialogResult>(
context: context,
builder: (context) => const PauseTicketDialog(),
builder: (context) => PauseTicketDialog(
contactPreference: contactPreference,
contactDestination: contactDestination,
initialPrice: initialPrice,
),
);
}
class PauseTicketDialog extends StatefulWidget {
const PauseTicketDialog({super.key});
final ContactPreference contactPreference;
final String contactDestination;
final double initialPrice;
const PauseTicketDialog({
super.key,
required this.contactPreference,
required this.contactDestination,
required this.initialPrice,
});
@override
State<PauseTicketDialog> createState() => _PauseTicketDialogState();
@@ -19,17 +44,49 @@ class PauseTicketDialog extends StatefulWidget {
class _PauseTicketDialogState extends State<PauseTicketDialog> {
final _reasonCtrl = TextEditingController();
// Partiamo con un default sensato
late final TextEditingController _quoteCtrl;
TicketStatus _selectedStatus = TicketStatus.waitingForParts;
late bool _notifyCustomer;
bool get _canAutoNotify =>
widget.contactPreference.isWhatsapp || widget.contactPreference.isEmail;
bool _defaultNotifyForStatus(TicketStatus status) {
if (!_canAutoNotify) return false;
return status == TicketStatus.waitingForParts ||
status == TicketStatus.waitingForCustomer;
}
@override
void initState() {
super.initState();
_quoteCtrl = TextEditingController(
text: widget.initialPrice > 0
? widget.initialPrice.toStringAsFixed(2)
: '',
);
_notifyCustomer = _defaultNotifyForStatus(_selectedStatus);
}
@override
void dispose() {
_reasonCtrl.dispose();
_quoteCtrl.dispose();
super.dispose();
}
void _selectStatus(TicketStatus status) {
setState(() {
_selectedStatus = status;
_notifyCustomer = _defaultNotifyForStatus(status);
});
}
@override
Widget build(BuildContext context) {
final pref = widget.contactPreference;
final dest = widget.contactDestination.trim();
return AlertDialog(
title: const Row(
children: [
@@ -39,79 +96,123 @@ class _PauseTicketDialogState extends State<PauseTicketDialog> {
],
),
content: SizedBox(
// Un po' di larghezza per i chips
width: double.maxFinite,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Seleziona il motivo della sospensione:'),
const SizedBox(height: 16),
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text('Seleziona il motivo della sospensione:'),
const SizedBox(height: 12),
// --- SCELTA DELLO STATO (CHIPS) ---
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
ChoiceChip(
label: const Text('Attesa Ricambi'),
selected: _selectedStatus == TicketStatus.waitingForParts,
onSelected: (bool selected) {
if (selected) {
setState(
() => _selectedStatus = TicketStatus.waitingForParts,
);
}
},
),
ChoiceChip(
label: const Text('Attesa Preventivo'),
selected: _selectedStatus == TicketStatus.waitingForQuote,
onSelected: (bool selected) {
if (selected) {
setState(
() => _selectedStatus = TicketStatus.waitingForQuote,
);
}
},
),
ChoiceChip(
label: const Text('Attesa Cliente'),
selected: _selectedStatus == TicketStatus.waitingForCustomer,
onSelected: (bool selected) {
if (selected) {
setState(
() => _selectedStatus = TicketStatus.waitingForCustomer,
);
}
},
// --- SCELTA DELLO STATO (CHIPS) ---
Wrap(
spacing: 8.0,
runSpacing: 8.0,
children: [
ChoiceChip(
label: const Text('Attesa Ricambi'),
selected: _selectedStatus == TicketStatus.waitingForParts,
onSelected: (selected) {
if (selected) _selectStatus(TicketStatus.waitingForParts);
},
),
ChoiceChip(
label: const Text('Attesa Preventivo'),
selected: _selectedStatus == TicketStatus.waitingForQuote,
onSelected: (selected) {
if (selected) _selectStatus(TicketStatus.waitingForQuote);
},
),
ChoiceChip(
label: const Text('Attesa Cliente / Preventivo'),
selected:
_selectedStatus == TicketStatus.waitingForCustomer,
onSelected: (selected) {
if (selected) {
_selectStatus(TicketStatus.waitingForCustomer);
}
},
),
],
),
if (_selectedStatus == TicketStatus.waitingForCustomer) ...[
const SizedBox(height: 16),
TextField(
controller: _quoteCtrl,
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
inputFormatters: [
FilteringTextInputFormatter.allow(RegExp(r'[0-9.,]')),
],
decoration: const InputDecoration(
labelText: 'Importo preventivo (€) - opzionale',
hintText: 'Es. 89.00',
prefixIcon: Icon(Icons.euro_rounded),
border: OutlineInputBorder(),
isDense: true,
),
),
],
),
const SizedBox(height: 24),
const Text(
'Note aggiuntive (opzionali):',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
const SizedBox(height: 8),
// --- NOTE AGGIUNTIVE ---
TextField(
controller: _reasonCtrl,
maxLines: 2,
decoration: const InputDecoration(
hintText: 'Es: Il fornitore consegna martedì...',
border: OutlineInputBorder(),
const SizedBox(height: 16),
const Text(
'Note pubbliche per il cliente (opzionali):',
style: TextStyle(fontSize: 12, color: Colors.grey),
),
),
],
const SizedBox(height: 8),
TextField(
controller: _reasonCtrl,
maxLines: 2,
decoration: const InputDecoration(
hintText: 'Es: Il ricambio arriva martedì...',
border: OutlineInputBorder(),
),
),
if (_canAutoNotify) ...[
const SizedBox(height: 16),
Container(
decoration: BoxDecoration(
color: pref.color.withValues(alpha: 0.08),
borderRadius: BorderRadius.circular(10),
border: Border.all(
color: pref.color.withValues(alpha: 0.35),
),
),
child: SwitchListTile(
dense: true,
value: _notifyCustomer,
onChanged: (val) => setState(() => _notifyCustomer = val),
secondary: pref.buildIcon(size: 18),
title: Text(
pref.isEmail
? 'Avvisa il cliente via Email'
: 'Avvisa il cliente su WhatsApp',
style: const TextStyle(
fontWeight: FontWeight.w600,
fontSize: 13.5,
),
),
subtitle: Text(
dest.isNotEmpty
? dest
: 'Recapito mancante in anagrafica',
style: const TextStyle(fontSize: 12),
),
),
),
],
],
),
),
),
actions: [
TextButton(
onPressed: () =>
Navigator.of(context).pop(), // Ritorna null (Annulla)
onPressed: () => Navigator.of(context).pop(),
child: const Text('Annulla'),
),
FilledButton(
@@ -119,10 +220,15 @@ class _PauseTicketDialogState extends State<PauseTicketDialog> {
backgroundColor: Colors.orange.shade700,
),
onPressed: () {
// RITORNIAMO IL RECORD CON STATO E NOTE!
Navigator.of(
context,
).pop((status: _selectedStatus, reason: _reasonCtrl.text.trim()));
final parsedQuote = _selectedStatus == TicketStatus.waitingForCustomer
? double.tryParse(_quoteCtrl.text.trim().replaceAll(',', '.'))
: null;
Navigator.of(context).pop((
status: _selectedStatus,
reason: _reasonCtrl.text.trim(),
notifyCustomer: _notifyCustomer,
quotePrice: parsedQuote,
));
},
child: const Text('Conferma Pausa'),
),
@@ -262,18 +262,42 @@ class TicketWorkspaceScreen extends StatelessWidget {
child: OutlinedButton.icon(
// ... stile del bottone ...
onPressed: () async {
// 1. Apriamo la modale e riceviamo il RECORD
final result = await showPauseTicketDialog(context);
final ticket = context.read<TicketFormCubit>().state.ticket;
final result = await showPauseTicketDialog(
context,
contactPreference: ticket.contactPreference,
contactDestination: ticket.effectiveContactDestination,
initialPrice: ticket.customerPrice,
);
// 2. Se l'utente ha confermato...
if (result != null && context.mounted) {
// 3. Lanciamo l'azione passando lo stato esatto e le note
await context.read<TicketFormCubit>().pauseTicket(
newStatus: result.status,
notes: result.reason,
);
final notifResult = await context
.read<TicketFormCubit>()
.pauseTicket(
newStatus: result.status,
notes: result.reason,
notifyCustomer: result.notifyCustomer,
quotePrice: result.quotePrice,
);
if (notifResult != null && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
notifResult.success
? '${notifResult.contextLabel} inviato via ${notifResult.channel.label}!'
: '${notifResult.contextLabel} via ${notifResult.channel.label} non riuscito: ${notifResult.error ?? 'errore sconosciuto'}',
),
backgroundColor: notifResult.success
? Colors.green.shade700
: Colors.orange.shade800,
duration: Duration(
seconds: notifResult.success ? 3 : 5,
),
),
);
}
// 4. Riportiamo l'utente alla dashboard
if (context.mounted) Navigator.of(context).pop();
}
},
@@ -290,26 +314,43 @@ class TicketWorkspaceScreen extends StatelessWidget {
backgroundColor: Colors.green.shade600,
),
onPressed: () async {
// 1. Apriamo la nuova modale avanzata e aspettiamo il Record.
// (Per ora passiamo 0.0, poi lo sostituiremo con la somma dei costi)
final ticket = context.read<TicketFormCubit>().state.ticket;
final completionData = await showCompletionTicketDialog(
context,
calculatedTotal: 0.0,
calculatedTotal: ticket.customerPrice,
contactPreference: ticket.contactPreference,
contactDestination: ticket.effectiveContactDestination,
);
// 2. Se l'utente ha premuto "Conferma" e non "Annulla"...
if (completionData != null && context.mounted) {
// 3. Lanciamo l'azione nel Cubit
await context.read<TicketFormCubit>().completeTicket(
result: completionData.result,
finalPrice: completionData.finalPrice,
);
final notifResult = await context
.read<TicketFormCubit>()
.completeTicket(
result: completionData.result,
finalPrice: completionData.finalPrice,
notifyCustomer: completionData.notifyCustomer,
);
if (notifResult != null && context.mounted) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(
content: Text(
notifResult.success
? 'Avviso ritiro inviato via ${notifResult.channel.label}!'
: 'Ticket completato, ma avviso ${notifResult.channel.label} non riuscito: ${notifResult.error ?? 'errore sconosciuto'}',
),
backgroundColor: notifResult.success
? Colors.green.shade700
: Colors.orange.shade800,
duration: Duration(
seconds: notifResult.success ? 3 : 5,
),
),
);
}
if (context.mounted) {
// 4. Avvisiamo il "Vigile Urbano" di ricaricare la lista
context.read<TicketListCubit>().loadTickets(refresh: true);
// 5. Teletrasporto alla Base
context.goNamed(Routes.home);
}
}
@@ -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<TicketModel?> showMarkTicketReturnedSheet(
BuildContext context,
TicketModel ticket,
) {
return showModalBottomSheet<TicketModel?>(
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<MarkTicketReturnedCubit, MarkTicketReturnedState>(
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<MarkTicketReturnedCubit>().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<MarkTicketReturnedCubit>().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<MarkTicketReturnedCubit>()
.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<MarkTicketReturnedCubit>()
.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<MarkTicketReturnedCubit>()
.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'),
),
],
);
}
}
@@ -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<TicketListCubit>().loadTickets(
refresh: true,
);
}
},
icon: const Icon(
Icons.assignment_returned_rounded,
size: 17,
),
label: const Text(
'Segna rientrato',
style: TextStyle(fontWeight: FontWeight.w700),
),
),
),
],
],
),
@@ -0,0 +1,409 @@
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('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;')
.replaceAll("'", '&#39;');
}
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>
''';
}
}
@@ -292,57 +292,432 @@ class TicketPdfService {
);
}
/// Genera una ricevuta digitale A4 (1 sola copia cliente, senza note interne né password)
/// con QR Code collegato alla pagina pubblica di tracciamento.
Future<pw.Document> generateCustomerReceiptPdf(TicketModel ticket) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
final ref = ticket.referenceId?.trim().isNotEmpty == true
? ticket.referenceId!
: (ticket.id?.substring(0, 8) ?? '');
final createdDate = ticket.createdAt != null
? '${ticket.createdAt!.day.toString().padLeft(2, '0')}/${ticket.createdAt!.month.toString().padLeft(2, '0')}/${ticket.createdAt!.year}'
: '';
final estimatedDate = ticket.estimatedDeliveryAt != null
? '${ticket.estimatedDeliveryAt!.day.toString().padLeft(2, '0')}/${ticket.estimatedDeliveryAt!.month.toString().padLeft(2, '0')}/${ticket.estimatedDeliveryAt!.year}'
: '';
final trackingUrl = ticket.publicTrackingUrl;
pdf.addPage(
pw.Page(
pageFormat: PdfPageFormat.a4,
margin: const pw.EdgeInsets.all(28),
build: (pw.Context context) {
return pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
// HEADER AZIENDA + RIF TICKET
pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
company.name,
style: pw.TextStyle(font: boldFont, fontSize: 18),
),
pw.SizedBox(height: 3),
pw.Text(
[
company.address,
company.city,
].where((e) => e.trim().isNotEmpty).join(', '),
style: pw.TextStyle(font: font, fontSize: 9.5),
),
pw.Text(
[
if ((company.phone ?? '').trim().isNotEmpty)
'Tel: ${company.phone}',
if ((company.email ?? '').trim().isNotEmpty)
company.email!,
].join(' • '),
style: pw.TextStyle(font: font, fontSize: 9.5),
),
if (company.vatId.trim().isNotEmpty)
pw.Text(
'P.IVA: ${company.vatId}',
style: pw.TextStyle(font: font, fontSize: 9),
),
],
),
),
pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.end,
children: [
pw.Text(
'RICEVUTA DI ASSISTENZA',
style: pw.TextStyle(
font: boldFont,
fontSize: 11,
color: PdfColors.blueGrey700,
),
),
pw.SizedBox(height: 2),
pw.Text(
'Pratica #$ref',
style: pw.TextStyle(font: boldFont, fontSize: 15),
),
if (createdDate.isNotEmpty)
pw.Text(
'Data apertura: $createdDate',
style: pw.TextStyle(font: font, fontSize: 9.5),
),
],
),
],
),
pw.SizedBox(height: 12),
pw.Divider(thickness: 1, color: PdfColors.grey400),
pw.SizedBox(height: 14),
// DATI CLIENTE & DISPOSITIVO
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'CLIENTE',
ticket.customer?.name ?? 'Cliente',
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'RECAPITO',
ticket.effectiveContactDestination.isNotEmpty
? ticket.effectiveContactDestination
: (ticket.customer?.phoneNumber ?? '-'),
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'DISPOSITIVO',
ticket.targetModelName?.isNotEmpty == true
? ticket.targetModelName!
: ticket.ticketType.displayValue,
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'SERIALE / IMEI',
ticket.targetSn?.trim().isNotEmpty == true
? ticket.targetSn!.trim()
: '-',
font,
boldFont,
),
),
],
),
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Expanded(
child: _infoBlock(
'TIPO INTERVENTO',
ticket.ticketType.displayValue,
font,
boldFont,
),
),
pw.Expanded(
child: _infoBlock(
'GARANZIA',
ticket.warrantyType?.displayValue ?? 'Fuori garanzia',
font,
boldFont,
),
),
],
),
if (ticket.includedAccessories?.trim().isNotEmpty == true ||
ticket.hasCourtesyDevice ||
estimatedDate.isNotEmpty ||
ticket.customerPrice > 0) ...[
pw.SizedBox(height: 14),
pw.Row(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
if (ticket.includedAccessories?.trim().isNotEmpty == true)
pw.Expanded(
child: _infoBlock(
'ACCESSORI LASCIATI',
ticket.includedAccessories!.trim(),
font,
boldFont,
),
),
if (ticket.hasCourtesyDevice)
pw.Expanded(
child: _infoBlock(
'MULETTO DI CORTESIA',
'Consegnato al cliente',
font,
boldFont,
),
),
if (estimatedDate.isNotEmpty)
pw.Expanded(
child: _infoBlock(
'CONSEGNA STIMATA',
estimatedDate,
font,
boldFont,
),
),
if (ticket.customerPrice > 0)
pw.Expanded(
child: _infoBlock(
'PREVENTIVO INIZIALE',
'EUR ${ticket.customerPrice.toStringAsFixed(2)}',
font,
boldFont,
),
),
],
),
],
pw.SizedBox(height: 16),
// PROBLEMA SEGNALATO
pw.Container(
width: double.infinity,
padding: const pw.EdgeInsets.all(12),
decoration: pw.BoxDecoration(
color: PdfColors.grey100,
borderRadius: pw.BorderRadius.circular(6),
),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'DIFETTO / RICHIESTA SEGNALATA',
style: pw.TextStyle(
font: boldFont,
fontSize: 8.5,
color: PdfColors.grey700,
),
),
pw.SizedBox(height: 4),
pw.Text(
ticket.request.trim().isNotEmpty
? ticket.request.trim()
: '-',
style: pw.TextStyle(font: font, fontSize: 11),
),
],
),
),
// NOTE PUBBLICHE (MAI internalNotes!)
if (ticket.publicNotes?.trim().isNotEmpty == true) ...[
pw.SizedBox(height: 12),
pw.Container(
width: double.infinity,
padding: const pw.EdgeInsets.all(12),
decoration: pw.BoxDecoration(
border: pw.Border.all(color: PdfColors.grey300),
borderRadius: pw.BorderRadius.circular(6),
),
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'NOTE',
style: pw.TextStyle(
font: boldFont,
fontSize: 8.5,
color: PdfColors.grey700,
),
),
pw.SizedBox(height: 4),
pw.Text(
ticket.publicNotes!.trim(),
style: pw.TextStyle(font: font, fontSize: 10.5),
),
],
),
),
],
pw.Spacer(),
// BOX TRACCIAMENTO ONLINE CON QR CODE
if (trackingUrl.isNotEmpty)
pw.Container(
padding: const pw.EdgeInsets.all(14),
decoration: pw.BoxDecoration(
color: PdfColors.blue50,
border: pw.Border.all(color: PdfColors.blue200),
borderRadius: pw.BorderRadius.circular(8),
),
child: pw.Row(
children: [
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(
errorCorrectLevel: pw.BarcodeQRCorrectionLevel.low,
),
data: trackingUrl,
width: 68,
height: 68,
),
pw.SizedBox(width: 14),
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
children: [
pw.Text(
'SEGUI LO STATO DELLA TUA PRATICA ONLINE',
style: pw.TextStyle(
font: boldFont,
fontSize: 10.5,
color: PdfColors.blue900,
),
),
pw.SizedBox(height: 4),
pw.Text(
'Inquadra il QR Code con il telefono per verificare in tempo reale gli aggiornamenti, eventuali preventivi e quando il dispositivo sarà pronto per il ritiro.',
style: pw.TextStyle(font: font, fontSize: 9),
),
pw.SizedBox(height: 4),
pw.Text(
trackingUrl,
style: pw.TextStyle(
font: font,
fontSize: 8,
color: PdfColors.blue700,
),
),
],
),
),
],
),
),
pw.SizedBox(height: 14),
pw.Align(
alignment: pw.Alignment.centerRight,
child: pw.Text(
'Grazie per aver scelto ${company.name}!',
style: pw.TextStyle(
font: font,
fontSize: 9.5,
color: PdfColors.grey700,
),
),
),
],
);
},
),
);
return pdf;
}
/// Genera l'etichetta adesiva verticale per il sacchetto del prodotto:
/// QR Code grande in alto (link alla scheda lavorazione), nome cliente e difetto sotto.
Future<pw.Document> generateLabelPdf(TicketModel ticket) async {
final pdf = pw.Document();
final font = await PdfGoogleFonts.robotoRegular();
final boldFont = await PdfGoogleFonts.robotoBold();
// Prendiamo le misure salvate (se custom) o usiamo default
final widthMm = company.labelWidth ?? 62.0;
final heightMm = company.labelHeight ?? 29.0;
final rawW = company.labelWidth ?? 38.0;
final rawH = company.labelHeight ?? 25.0;
// Creiamo il formato fisico esatto!
final format = company.isLabelVertical
? PdfPageFormat(heightMm * PdfPageFormat.mm, widthMm * PdfPageFormat.mm)
: PdfPageFormat(
widthMm * PdfPageFormat.mm,
heightMm * PdfPageFormat.mm,
);
// Orientamento sempre verticale: lato corto come larghezza, lato lungo come altezza (es. 25x38mm)
final shortSideMm = rawW < rawH ? rawW : rawH;
final longSideMm = rawW > rawH ? rawW : rawH;
final format = PdfPageFormat(
shortSideMm * PdfPageFormat.mm,
longSideMm * PdfPageFormat.mm,
);
const margin = 1.5 * PdfPageFormat.mm;
final contentWidth = format.width - (margin * 2);
// QR grande quasi quanto tutta la larghezza disponibile per lettura immediata su 25x38mm
final qrSize = (contentWidth - 1 * PdfPageFormat.mm).clamp(
14 * PdfPageFormat.mm,
24 * PdfPageFormat.mm,
);
final customerName = ticket.customer?.name ?? 'Cliente sconosciuto';
final defectLine = ticket.request.trim().isNotEmpty
? ticket.request.trim()
: (ticket.targetModelName ?? ticket.ticketType.displayValue);
final qrData = ticket.internalDeepLinkUrl.isNotEmpty
? ticket.internalDeepLinkUrl
: (ticket.id ?? '');
pdf.addPage(
pw.Page(
pageFormat: format,
margin: const pw.EdgeInsets.all(2), // Margini minimi per le etichette
margin: const pw.EdgeInsets.all(margin),
build: (context) {
return pw.Row(
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
return pw.Column(
mainAxisAlignment: pw.MainAxisAlignment.start,
crossAxisAlignment: pw.CrossAxisAlignment.center,
children: [
pw.Expanded(
child: pw.Column(
crossAxisAlignment: pw.CrossAxisAlignment.start,
mainAxisAlignment: pw.MainAxisAlignment.center,
children: [
pw.Text(
ticket.referenceId ?? '',
style: pw.TextStyle(font: boldFont, fontSize: 10),
),
pw.Text(
ticket.customer?.name ?? 'Cliente sconosciuto',
style: pw.TextStyle(font: font, fontSize: 9),
),
pw.Text(
ticket.createdAt?.toString().substring(0, 10) ?? '',
style: const pw.TextStyle(fontSize: 7),
),
],
),
),
// QR Code compatto
pw.BarcodeWidget(
barcode: pw.Barcode.qrCode(),
data: ticket.id!,
width: 20,
height: 20,
barcode: pw.Barcode.qrCode(
errorCorrectLevel: pw.BarcodeQRCorrectionLevel.low,
),
data: qrData,
width: qrSize,
height: qrSize,
),
pw.SizedBox(height: 1.5 * PdfPageFormat.mm),
pw.Text(
customerName,
style: pw.TextStyle(font: boldFont, fontSize: 9.5),
textAlign: pw.TextAlign.center,
maxLines: 2,
overflow: pw.TextOverflow.clip,
),
pw.SizedBox(height: 0.8 * PdfPageFormat.mm),
pw.Expanded(
child: pw.Text(
defectLine,
style: pw.TextStyle(font: font, fontSize: 7.2),
textAlign: pw.TextAlign.center,
maxLines: 2,
overflow: pw.TextOverflow.clip,
),
),
],
);
+8
View File
@@ -1,6 +1,8 @@
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flux/core/blocs/session/session_cubit.dart';
import 'package:flux/core/data/core_repository.dart';
import 'package:flux/core/services/email/email_service.dart';
import 'package:flux/core/services/whatsapp/whatsapp_service.dart';
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';
@@ -53,6 +55,12 @@ Future<void> init() async {
: 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo',
);
sl.registerSingleton<SupabaseClient>(Supabase.instance.client);
sl.registerLazySingleton<WhatsAppService>(
() => WhatsAppService(sl<SupabaseClient>()),
);
sl.registerLazySingleton<EmailService>(
() => EmailService(sl<SupabaseClient>()),
);
sl.registerSingleton<SharedPreferences>(
await SharedPreferences.getInstance(),
);
+1 -1
View File
@@ -1,7 +1,7 @@
name: flux
description: "Gestione attività negozio di telefonia"
publish_to: 'none'
version: 2.7.0+95
version: 2.7.1+96
environment:
sdk: ^3.11.3
+6
View File
@@ -433,3 +433,9 @@ entrypoint = "./functions/instant-notifier/index.ts"
# Specifies static files to be bundled with the function. Supports glob patterns.
# For example, if you want to serve static HTML pages in your function:
# static_files = [ "./functions/instant-notifier/*.html" ]
[functions.send-email]
enabled = true
verify_jwt = true
import_map = "./functions/send-email/deno.json"
entrypoint = "./functions/send-email/index.ts"
+5
View File
@@ -0,0 +1,5 @@
{
"imports": {
"nodemailer": "npm:nodemailer@^6.9.16"
}
}
+148
View File
@@ -0,0 +1,148 @@
import nodemailer from "npm:nodemailer@^6.9.16";
const corsHeaders = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers":
"authorization, x-client-info, apikey, content-type",
};
interface EmailAttachmentPayload {
filename: string;
contentBase64: string;
contentType?: string;
}
interface SendEmailRequest {
to?: string;
subject?: string;
text?: string;
html?: string;
replyTo?: string;
account?: string;
attachments?: EmailAttachmentPayload[];
}
Deno.serve(async (req) => {
if (req.method === "OPTIONS") {
return new Response("ok", { headers: corsHeaders });
}
try {
const body = (await req.json()) as SendEmailRequest;
const to = body.to?.trim() ?? "";
const subject = body.subject?.trim() ?? "";
const text = body.text?.trim() ?? "";
const html = body.html?.trim();
const replyTo = body.replyTo?.trim();
if (!to) {
return new Response(
JSON.stringify({
success: false,
error: "Indirizzo email destinatario mancante.",
}),
{
status: 400,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
if (!subject || (!text && !html)) {
return new Response(
JSON.stringify({
success: false,
error: "Oggetto e contenuto dell'email sono obbligatori.",
}),
{
status: 400,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
const smtpHost = Deno.env.get("SMTP_HOST") ?? "stalwart.catelli.it";
const smtpPort = Number(Deno.env.get("SMTP_PORT") ?? "465");
const isAssistenza = body.account?.trim().toLowerCase() === "assistenza";
const smtpUser = isAssistenza
? (Deno.env.get("SMTP_USER_ASSISTENZA") ?? "assistenza@catelli.it")
: (Deno.env.get("SMTP_USER") ?? "ordini@catelli.it");
const smtpPass = isAssistenza
? (Deno.env.get("SMTP_PASS_ASSISTENZA") ?? Deno.env.get("SMTP_PASS"))
: Deno.env.get("SMTP_PASS");
const smtpFrom = isAssistenza
? (Deno.env.get("SMTP_FROM_ASSISTENZA") ??
`Assistenza Catelli <${smtpUser}>`)
: (Deno.env.get("SMTP_FROM") ?? `Ordini Catelli <${smtpUser}>`);
if (!smtpPass) {
return new Response(
JSON.stringify({
success: false,
error: "Credenziali SMTP non configurate sul server (SMTP_PASS).",
}),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
const transporter = nodemailer.createTransport({
host: smtpHost,
port: smtpPort,
secure: smtpPort === 465,
auth: {
user: smtpUser,
pass: smtpPass,
},
});
const attachments = Array.isArray(body.attachments)
? body.attachments
.filter((a) => a && a.filename && a.contentBase64)
.map((a) => ({
filename: a.filename,
content: a.contentBase64,
encoding: "base64",
contentType: a.contentType ?? "application/pdf",
}))
: undefined;
const info = await transporter.sendMail({
from: smtpFrom,
to,
subject,
text: text || undefined,
html: html || undefined,
replyTo: replyTo || undefined,
attachments: attachments && attachments.length > 0 ? attachments : undefined,
});
return new Response(
JSON.stringify({
success: true,
to,
messageId: info.messageId,
}),
{
status: 200,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
} catch (error) {
const message =
error instanceof Error ? error.message : "Errore sconosciuto invio email";
console.error("send-email error:", message);
return new Response(
JSON.stringify({
success: false,
error: `Errore invio email: ${message}`,
}),
{
status: 500,
headers: { ...corsHeaders, "Content-Type": "application/json" },
},
);
}
});
@@ -0,0 +1,71 @@
-- Funzione RPC pubblica (senza autenticazione) per la pagina di tracciamento
-- stato ticket lato cliente: https://flux.catelli.it/ticket/<id>
-- Espone SOLO dati pubblici (mai internal_notes, internal_cost, password o dati sensibili).
CREATE OR REPLACE FUNCTION public.get_public_ticket(p_ticket_id uuid)
RETURNS jsonb
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path = public
AS $$
DECLARE
v_result jsonb;
BEGIN
SELECT jsonb_build_object(
'id', t.id,
'reference_id', t.reference_id,
'created_at', t.created_at,
'closed_at', t.closed_at,
'returned_at', t.returned_at,
'estimated_delivery_at', t.estimated_delivery_at,
'ticket_type', t.ticket_type,
'ticket_status', t.ticket_status,
'ticket_result', t.ticket_result,
'warranty_type', t.warranty_type,
'request', t.request,
'included_accessories', t.included_accessories,
'has_courtesy_device', COALESCE(t.has_courtesy_device, false),
'customer_price', COALESCE(t.customer_price, 0),
'public_notes', t.public_notes,
'resolution_notes', t.resolution_notes,
'target_model_name', m.name_with_brand,
'customer_name', c.name,
'company_name', comp.name,
'company_phone', comp.phone,
'company_email', comp.email,
'company_address', comp.address,
'company_city', comp.city,
'store_name', s.name,
'timeline', COALESCE(
(
SELECT jsonb_agg(
jsonb_build_object(
'id', tr.id,
'created_at', tr.created_at,
'event_type', tr.event_type,
'message', tr.message
)
ORDER BY tr.created_at DESC
)
FROM public.trackings tr
WHERE tr.parent_id = t.id
AND tr.parent_type = 'ticket'
AND COALESCE(tr.is_internal, true) = false
),
'[]'::jsonb
)
)
INTO v_result
FROM public.tickets t
LEFT JOIN public.models m ON m.id = t.target_model_id
LEFT JOIN public.customers c ON c.id = t.customer_id
LEFT JOIN public.companies comp ON comp.id = t.company_id
LEFT JOIN public.stores s ON s.id = t.store_id
WHERE t.id = p_ticket_id;
RETURN v_result;
END;
$$;
REVOKE ALL ON FUNCTION public.get_public_ticket(uuid) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION public.get_public_ticket(uuid) TO anon, authenticated;