147 lines
5.0 KiB
Dart
147 lines
5.0 KiB
Dart
import 'dart:convert';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:http/http.dart' as http;
|
|
import '../utils/phone_utils.dart';
|
|
import '../models/pedido.dart';
|
|
|
|
/// Resultado de la operación de envío vía WhatsApp
|
|
class WhatsAppEnvioResult {
|
|
final bool ok;
|
|
final String? error;
|
|
final String numeroDestino;
|
|
|
|
const WhatsAppEnvioResult({
|
|
required this.ok,
|
|
this.error,
|
|
required this.numeroDestino,
|
|
});
|
|
}
|
|
|
|
/// Servicio cliente para el envío de alertas operativas por WhatsApp
|
|
/// a través del Gateway de comunicaciones Sigma-Robot (Meta Cloud API / WS Bot).
|
|
class WhatsAppService {
|
|
// URL base del gateway de comunicaciones de Sigma Robot
|
|
static const String _defaultBaseUrl = 'https://sigma-bot.telcotronics.com';
|
|
|
|
// API Key predeterminada de integración para servicios internos
|
|
static const String _defaultApiKey = 'f6272e6997b1fea4387fa0a582f8b15afbeb51457f030825686e8e2fc5adaf10';
|
|
|
|
/// Envía un mensaje de texto formateado hacia el número de WhatsApp especificado.
|
|
/// El número es normalizado automáticamente mediante expresiones regulares (PhoneUtils).
|
|
static Future<WhatsAppEnvioResult> enviarMensaje({
|
|
required String telefono,
|
|
required String mensaje,
|
|
String? baseUrl,
|
|
String? apiKey,
|
|
String codigoPais = PhoneUtils.defaultCountryCode,
|
|
}) async {
|
|
final numeroLimpio = PhoneUtils.normalizarWhatsApp(telefono, pais: codigoPais);
|
|
|
|
if (!PhoneUtils.esWhatsAppValido(numeroLimpio)) {
|
|
return WhatsAppEnvioResult(
|
|
ok: false,
|
|
error: 'El número de teléfono no es válido para WhatsApp (mínimo 10 dígitos).',
|
|
numeroDestino: numeroLimpio,
|
|
);
|
|
}
|
|
|
|
final url = Uri.parse('${baseUrl ?? _defaultBaseUrl}/api/meta/enviar_mensaje');
|
|
final key = apiKey ?? _defaultApiKey;
|
|
|
|
try {
|
|
final res = await http.post(
|
|
url,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-api-key': key,
|
|
},
|
|
body: jsonEncode({
|
|
'to': numeroLimpio,
|
|
'mensaje': mensaje,
|
|
}),
|
|
).timeout(const Duration(seconds: 12));
|
|
|
|
if (res.statusCode == 200 || res.statusCode == 201) {
|
|
debugPrint('[WhatsAppService] Mensaje enviado con éxito a $numeroLimpio');
|
|
return WhatsAppEnvioResult(ok: true, numeroDestino: numeroLimpio);
|
|
}
|
|
|
|
// Si falla Meta, intentar fallback a wsbot
|
|
final fallbackUrl = Uri.parse('${baseUrl ?? _defaultBaseUrl}/api/wsbot/enviar_mensaje');
|
|
final fallbackRes = await http.post(
|
|
fallbackUrl,
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
'x-api-key': key,
|
|
},
|
|
body: jsonEncode({
|
|
'to': numeroLimpio,
|
|
'mensaje': mensaje,
|
|
}),
|
|
).timeout(const Duration(seconds: 10));
|
|
|
|
if (fallbackRes.statusCode == 200 || fallbackRes.statusCode == 201) {
|
|
debugPrint('[WhatsAppService] Mensaje enviado por WSBot fallback a $numeroLimpio');
|
|
return WhatsAppEnvioResult(ok: true, numeroDestino: numeroLimpio);
|
|
}
|
|
|
|
final errorMsg = 'Error en el Gateway (${res.statusCode}): ${res.body}';
|
|
debugPrint('[WhatsAppService] $errorMsg');
|
|
return WhatsAppEnvioResult(ok: false, error: errorMsg, numeroDestino: numeroLimpio);
|
|
} catch (e) {
|
|
debugPrint('[WhatsAppService] Error de red al enviar WhatsApp: $e');
|
|
return WhatsAppEnvioResult(
|
|
ok: false,
|
|
error: 'No se pudo conectar con el Gateway de WhatsApp ($e)',
|
|
numeroDestino: numeroLimpio,
|
|
);
|
|
}
|
|
}
|
|
|
|
/// Envía un mensaje de prueba al vendedor para verificar la vinculación
|
|
static Future<WhatsAppEnvioResult> enviarAlertaPrueba({
|
|
required String telefono,
|
|
required String nombreVendedor,
|
|
String codigoPais = PhoneUtils.defaultCountryCode,
|
|
}) async {
|
|
final mensaje =
|
|
'🔔 *AGENTE VENTAS — SIGMAC*\n\n'
|
|
'¡Hola $nombreVendedor!\n'
|
|
'Tu número ha sido vinculado correctamente para recibir alertas operativas y resúmenes de venta en ruta.\n\n'
|
|
'⚡ _Enviado automáticamente vía Sigma-Robot Gateway._';
|
|
|
|
return enviarMensaje(
|
|
telefono: telefono,
|
|
mensaje: mensaje,
|
|
codigoPais: codigoPais,
|
|
);
|
|
}
|
|
|
|
/// Envía una alerta de confirmación de pedido generado en campo
|
|
static Future<WhatsAppEnvioResult> enviarAlertaPedido({
|
|
required String telefono,
|
|
required Pedido pedido,
|
|
required String nombreCliente,
|
|
required String nombreVendedor,
|
|
String codigoPais = PhoneUtils.defaultCountryCode,
|
|
}) async {
|
|
final fecha = pedido.fecha.toLocal().toString().split(' ')[0];
|
|
final total = pedido.total.toStringAsFixed(2);
|
|
|
|
final mensaje =
|
|
'📦 *NUEVO PEDIDO GENERADO*\n'
|
|
'• *Pedido:* #${pedido.id}\n'
|
|
'• *Cliente:* $nombreCliente\n'
|
|
'• *Total:* \$$total\n'
|
|
'• *Fecha:* $fecha\n'
|
|
'• *Vendedor:* $nombreVendedor\n\n'
|
|
'✅ _El pedido ha sido registrado en la app móvil y preparado para despacho._';
|
|
|
|
return enviarMensaje(
|
|
telefono: telefono,
|
|
mensaje: mensaje,
|
|
codigoPais: codigoPais,
|
|
);
|
|
}
|
|
}
|