feat: servicios WhatsApp, Bitácora WebControl, SQLite v4, UI y store listing
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../db/dao/sync_log_dao.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
|
||||
/// Servicio responsable del envío de alertas críticas por WhatsApp
|
||||
/// utilizando sigma-robot como Gateway de comunicaciones omnicanal.
|
||||
///
|
||||
/// Todas las validaciones de números telefónicos exigen código de país
|
||||
/// al inicio conforme al estándar internacional E.164.
|
||||
class WhatsAppAlertService {
|
||||
WhatsAppAlertService._();
|
||||
static final WhatsAppAlertService instance = WhatsAppAlertService._();
|
||||
|
||||
final _syncLogDao = SyncLogDao();
|
||||
final _usuariosDao = UsuariosDao();
|
||||
final _configDao = ConfiguracionDao();
|
||||
|
||||
/// Expresión regular que exige código de país al inicio (no empieza con 0)
|
||||
/// y una longitud internacional total de 10 a 15 dígitos numéricos (estándar E.164).
|
||||
/// Acepta prefijo opcional '+'.
|
||||
static final RegExp regexTelefonoE164 = RegExp(r'^\+?[1-9]\d{8,14}$');
|
||||
|
||||
/// Endpoint default de envío de mensajes en sigma-robot
|
||||
static const String endpointDefault =
|
||||
'https://sigma-bot.telcotronics.com/api/meta/enviar_mensaje';
|
||||
|
||||
/// Limpia caracteres no numéricos excepto el '+' inicial
|
||||
static String normalizarTelefono(String raw) {
|
||||
var limpio = raw.trim().replaceAll(RegExp(r'[\s\-()]'), '');
|
||||
// Si inicia con '+', preservamos el '+' y filtramos el resto a solo números
|
||||
if (limpio.startsWith('+')) {
|
||||
final resto = limpio.substring(1).replaceAll(RegExp(r'\D'), '');
|
||||
return '+$resto';
|
||||
}
|
||||
return limpio.replaceAll(RegExp(r'\D'), '');
|
||||
}
|
||||
|
||||
/// Valida si un número telefónico cumple con el estándar E.164 con código de país
|
||||
static bool esNumeroValido(String raw) {
|
||||
final normalizado = normalizarTelefono(raw);
|
||||
if (normalizado.isEmpty) return false;
|
||||
return regexTelefonoE164.hasMatch(normalizado);
|
||||
}
|
||||
|
||||
/// Envía un mensaje de texto por WhatsApp a un número destinatario
|
||||
Future<bool> enviarMensaje({
|
||||
required String telefonoDestino,
|
||||
required String mensaje,
|
||||
}) async {
|
||||
final telLimpio = normalizarTelefono(telefonoDestino);
|
||||
|
||||
if (!esNumeroValido(telLimpio)) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'error',
|
||||
detalle: 'Número inválido sin código de país: $telefonoDestino',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Consultar endpoint configurable o usar default
|
||||
final endpoint = await _configDao.get('sigma_whatsapp_endpoint') ??
|
||||
endpointDefault;
|
||||
|
||||
// El número para WhatsApp no requiere el signo '+' en la API de Meta/sigma-robot
|
||||
final numeroApi = telLimpio.startsWith('+') ? telLimpio.substring(1) : telLimpio;
|
||||
|
||||
final payload = jsonEncode({
|
||||
'telefono': numeroApi,
|
||||
'mensaje': mensaje,
|
||||
'origen': 'SENTINEL_ONE',
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
});
|
||||
|
||||
final response = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: payload,
|
||||
)
|
||||
.timeout(const Duration(seconds: 10));
|
||||
|
||||
final ok = response.statusCode >= 200 && response.statusCode < 300;
|
||||
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: ok ? 'ok' : 'error',
|
||||
detalle: 'Envío a $telLimpio: HTTP ${response.statusCode}',
|
||||
);
|
||||
|
||||
return ok;
|
||||
} catch (e) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'error',
|
||||
detalle: 'Excepción de red al enviar WhatsApp: $e',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/// Despacha una alerta de seguridad de severidad alta/crítica (4 o 5)
|
||||
Future<bool> dispararAlertaSeguridad({
|
||||
required String titulo,
|
||||
required String zona,
|
||||
required int severidad,
|
||||
required String descripcion,
|
||||
}) async {
|
||||
// Obtener usuario principal para enviar la notificación
|
||||
final usuario = await _usuariosDao.getById(1);
|
||||
final telefono = usuario?.telefono;
|
||||
|
||||
if (telefono == null || telefono.trim().isEmpty) {
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'whatsapp_alert',
|
||||
estado: 'omitido',
|
||||
detalle: 'Alerta $titulo no enviada: usuario sin número configurado',
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
final hora = DateTime.now().toLocal().toString().substring(11, 16);
|
||||
final textoAlerta = '🚨 *ALERTA CRÍTICA SENTINEL ONE*\n'
|
||||
'• Severidad: NIVEL $severidad\n'
|
||||
'• Evento: $titulo\n'
|
||||
'• Zona: $zona\n'
|
||||
'• Hora: $hora\n'
|
||||
'• Detalle: $descripcion\n\n'
|
||||
'Por favor verificar de inmediato en la consola de monitoreo.';
|
||||
|
||||
return enviarMensaje(telefonoDestino: telefono, mensaje: textoAlerta);
|
||||
}
|
||||
|
||||
/// Despacha una alerta de PÁNICO / SOS activada por el operador
|
||||
Future<bool> dispararPanicoSOS({
|
||||
required String operador,
|
||||
String? ubicacion,
|
||||
}) async {
|
||||
final usuario = await _usuariosDao.getById(1);
|
||||
final telefono = usuario?.telefono;
|
||||
|
||||
if (telefono == null || telefono.trim().isEmpty) {
|
||||
return false;
|
||||
}
|
||||
|
||||
final hora = DateTime.now().toLocal().toString().substring(11, 19);
|
||||
final textoPanico = '🆘 *BOTÓN DE PÁNICO ACTIVADO*\n'
|
||||
'• Operador: $operador\n'
|
||||
'• Hora de activación: $hora\n'
|
||||
'${ubicacion != null ? "• Ubicación: $ubicacion\n" : ""}'
|
||||
'• Estado: EMERGENCIA ACTIVA\n\n'
|
||||
'Unidad táctica y supervisión en ruta.';
|
||||
|
||||
return enviarMensaje(telefonoDestino: telefono, mensaje: textoPanico);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user