diff --git a/lib/core/services/whatsapp/whatsapp_response_model.dart b/lib/core/services/whatsapp/whatsapp_response_model.dart new file mode 100644 index 0000000..24f5c05 --- /dev/null +++ b/lib/core/services/whatsapp/whatsapp_response_model.dart @@ -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 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 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 get props => [ + success, + exists, + phone, + chatId, + session, + messageId, + error, + ]; +} diff --git a/lib/core/services/whatsapp/whatsapp_service.dart b/lib/core/services/whatsapp/whatsapp_service.dart new file mode 100644 index 0000000..e9f146d --- /dev/null +++ b/lib/core/services/whatsapp/whatsapp_service.dart @@ -0,0 +1,136 @@ +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 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, + }); + } + + /// Verifica se il numero è registrato su WhatsApp senza inviare alcun messaggio. + Future 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 hasWhatsApp(String phone) async { + final result = await checkNumber(phone); + return result.exists; + } + + Future _invoke(Map 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? _decodeData(dynamic raw) { + if (raw is Map) { + return raw; + } + if (raw is Map) { + return Map.from(raw); + } + if (raw is String && raw.trim().isNotEmpty) { + try { + final decoded = jsonDecode(raw); + if (decoded is Map) { + return decoded; + } + if (decoded is Map) { + return Map.from(decoded); + } + } catch (_) { + return null; + } + } + return null; + } +} diff --git a/lib/service_locator.dart b/lib/service_locator.dart index bf1eecd..055b93d 100644 --- a/lib/service_locator.dart +++ b/lib/service_locator.dart @@ -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/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 +54,9 @@ Future init() async { : 'sb_publishable_kyzeAS6kxuGB9WLkRilc79_pYWsKdVo', ); sl.registerSingleton(Supabase.instance.client); + sl.registerLazySingleton( + () => WhatsAppService(sl()), + ); sl.registerSingleton( await SharedPreferences.getInstance(), );