feat: add email service and automated customer order notifications
This commit is contained in:
1 parent
0bc8ae92b9
commit
1fbd2bf8db
17 files changed
+1735
-31
No files matched your search
@@ -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];
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
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';
|
||||
|
||||
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,
|
||||
}) 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,
|
||||
if (html != null && html.trim().isNotEmpty) 'html': html.trim(),
|
||||
if (replyTo != null && replyTo.trim().isNotEmpty)
|
||||
'replyTo': replyTo.trim(),
|
||||
},
|
||||
);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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,15 +245,56 @@ 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;
|
||||
@@ -256,6 +306,7 @@ class CustomerOrderFormCubit extends Cubit<CustomerOrderFormState> {
|
||||
: CustomerOrderFormStatus.saved,
|
||||
order: saved,
|
||||
justMarkedArrived: transitionedToArrived,
|
||||
receiptNotificationResult: receiptNotificationResult,
|
||||
errorMessage: null,
|
||||
),
|
||||
);
|
||||
|
||||
@@ -16,6 +16,7 @@ class CustomerOrderFormState extends Equatable {
|
||||
final List<String> availableTags;
|
||||
final String? errorMessage;
|
||||
final bool justMarkedArrived;
|
||||
final OrderNotificationResult? receiptNotificationResult;
|
||||
|
||||
const CustomerOrderFormState({
|
||||
this.status = CustomerOrderFormStatus.initial,
|
||||
@@ -23,6 +24,7 @@ class CustomerOrderFormState extends Equatable {
|
||||
this.availableTags = const [],
|
||||
this.errorMessage,
|
||||
this.justMarkedArrived = false,
|
||||
this.receiptNotificationResult,
|
||||
});
|
||||
|
||||
CustomerOrderFormState copyWith({
|
||||
@@ -31,6 +33,7 @@ class CustomerOrderFormState extends Equatable {
|
||||
List<String>? availableTags,
|
||||
String? errorMessage,
|
||||
bool? justMarkedArrived,
|
||||
OrderNotificationResult? receiptNotificationResult,
|
||||
}) {
|
||||
return CustomerOrderFormState(
|
||||
status: status ?? this.status,
|
||||
@@ -38,6 +41,7 @@ class CustomerOrderFormState extends Equatable {
|
||||
availableTags: availableTags ?? this.availableTags,
|
||||
errorMessage: errorMessage,
|
||||
justMarkedArrived: justMarkedArrived ?? false,
|
||||
receiptNotificationResult: receiptNotificationResult,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -48,5 +52,6 @@ class CustomerOrderFormState extends Equatable {
|
||||
availableTags,
|
||||
errorMessage,
|
||||
justMarkedArrived,
|
||||
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,
|
||||
];
|
||||
}
|
||||
@@ -264,12 +264,30 @@ 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 (_closeAfterSave && context.mounted) {
|
||||
Navigator.of(context).pop();
|
||||
} else if (context.mounted) {
|
||||
} else if (receiptResult == null && context.mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('Ordine aggiornato con successo!'),
|
||||
|
||||
@@ -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('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"')
|
||||
.replaceAll("'", ''');
|
||||
}
|
||||
|
||||
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>
|
||||
''';
|
||||
}
|
||||
}
|
||||
@@ -26,9 +26,9 @@ class CustomerOrderLabelPdfService {
|
||||
final effectiveW = pageFormat.width;
|
||||
final effectiveH = pageFormat.height;
|
||||
final minSide = effectiveW < effectiveH ? effectiveW : effectiveH;
|
||||
final qrSize = (minSide - 6 * PdfPageFormat.mm).clamp(
|
||||
14 * PdfPageFormat.mm,
|
||||
26 * PdfPageFormat.mm,
|
||||
final qrSize = (minSide * 0.45).clamp(
|
||||
10 * PdfPageFormat.mm,
|
||||
16 * PdfPageFormat.mm,
|
||||
);
|
||||
|
||||
final customerName = order.customer?.name ?? 'Cliente';
|
||||
@@ -46,36 +46,57 @@ class CustomerOrderLabelPdfService {
|
||||
pageFormat: pageFormat,
|
||||
margin: const pw.EdgeInsets.all(2 * PdfPageFormat.mm),
|
||||
build: (context) {
|
||||
final infoBlock = pw.Column(
|
||||
final headerName = pw.Container(
|
||||
width: double.infinity,
|
||||
padding: const pw.EdgeInsets.only(bottom: 1.5),
|
||||
decoration: const pw.BoxDecoration(
|
||||
border: pw.Border(
|
||||
bottom: pw.BorderSide(width: 0.5, color: PdfColors.grey600),
|
||||
),
|
||||
),
|
||||
child: pw.FittedBox(
|
||||
fit: pw.BoxFit.scaleDown,
|
||||
alignment: pw.Alignment.centerLeft,
|
||||
child: pw.Text(
|
||||
customerName,
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 11.5),
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
final detailsBlock = pw.Column(
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.start,
|
||||
mainAxisAlignment: pw.MainAxisAlignment.center,
|
||||
mainAxisSize: pw.MainAxisSize.min,
|
||||
children: [
|
||||
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: font, fontSize: 7.5),
|
||||
maxLines: 2,
|
||||
overflow: pw.TextOverflow.clip,
|
||||
),
|
||||
if (codeStr.isNotEmpty || priceStr.isNotEmpty) ...[
|
||||
pw.SizedBox(height: 2),
|
||||
if (codeStr.isNotEmpty) ...[
|
||||
pw.SizedBox(height: 1.5),
|
||||
pw.Text(
|
||||
[
|
||||
if (codeStr.isNotEmpty) 'Cod: $codeStr',
|
||||
if (priceStr.isNotEmpty) priceStr,
|
||||
].join(' • '),
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 7.5),
|
||||
'Cod: $codeStr',
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 7.2),
|
||||
maxLines: 1,
|
||||
overflow: pw.TextOverflow.clip,
|
||||
),
|
||||
],
|
||||
if (priceStr.isNotEmpty) ...[
|
||||
pw.SizedBox(height: 2),
|
||||
pw.FittedBox(
|
||||
fit: pw.BoxFit.scaleDown,
|
||||
alignment: pw.Alignment.centerLeft,
|
||||
child: pw.Text(
|
||||
priceStr,
|
||||
style: pw.TextStyle(font: boldFont, fontSize: 11.5),
|
||||
maxLines: 1,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
);
|
||||
|
||||
@@ -88,23 +109,33 @@ class CustomerOrderLabelPdfService {
|
||||
|
||||
if (effectiveH > effectiveW) {
|
||||
return pw.Column(
|
||||
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
infoBlock,
|
||||
headerName,
|
||||
pw.SizedBox(height: 2),
|
||||
qrWidget,
|
||||
pw.Expanded(child: detailsBlock),
|
||||
pw.SizedBox(height: 2),
|
||||
pw.Center(child: qrWidget),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
return pw.Row(
|
||||
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||
return pw.Column(
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
pw.Expanded(child: infoBlock),
|
||||
pw.SizedBox(width: 2 * PdfPageFormat.mm),
|
||||
qrWidget,
|
||||
headerName,
|
||||
pw.SizedBox(height: 2),
|
||||
pw.Expanded(
|
||||
child: pw.Row(
|
||||
mainAxisAlignment: pw.MainAxisAlignment.spaceBetween,
|
||||
crossAxisAlignment: pw.CrossAxisAlignment.center,
|
||||
children: [
|
||||
pw.Expanded(child: detailsBlock),
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
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';
|
||||
@@ -57,6 +58,9 @@ Future<void> init() async {
|
||||
sl.registerLazySingleton<WhatsAppService>(
|
||||
() => WhatsAppService(sl<SupabaseClient>()),
|
||||
);
|
||||
sl.registerLazySingleton<EmailService>(
|
||||
() => EmailService(sl<SupabaseClient>()),
|
||||
);
|
||||
sl.registerSingleton<SharedPreferences>(
|
||||
await SharedPreferences.getInstance(),
|
||||
);
|
||||
|
||||
@@ -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"
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"imports": {
|
||||
"nodemailer": "npm:nodemailer@^6.9.16"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import nodemailer from "nodemailer";
|
||||
|
||||
const corsHeaders = {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Headers":
|
||||
"authorization, x-client-info, apikey, content-type",
|
||||
};
|
||||
|
||||
interface SendEmailRequest {
|
||||
to?: string;
|
||||
subject?: string;
|
||||
text?: string;
|
||||
html?: string;
|
||||
replyTo?: string;
|
||||
}
|
||||
|
||||
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 smtpUser = Deno.env.get("SMTP_USER") ?? "ordini@catelli.it";
|
||||
const smtpPass = Deno.env.get("SMTP_PASS");
|
||||
const smtpFrom = Deno.env.get("SMTP_FROM") ?? `Ordini <${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 info = await transporter.sendMail({
|
||||
from: smtpFrom,
|
||||
to,
|
||||
subject,
|
||||
text: text || undefined,
|
||||
html: html || undefined,
|
||||
replyTo: replyTo || 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" },
|
||||
},
|
||||
);
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user