feat: suite de tiendas, sync reactivo, bitácora de errores y alertas whatsapp
This commit is contained in:
@@ -82,6 +82,23 @@ class AuthService {
|
||||
/// Retorna `null` si no hay conexión (fallback a modo offline).
|
||||
/// Lanza [AuthException] si las credenciales son incorrectas.
|
||||
static Future<AuthSession?> login(String email, String password) async {
|
||||
// Intercepción de credenciales de evaluación para tiendas (Google Play Store / Apple App Store).
|
||||
// Proporciona una sesión válida local e independiente de la conectividad al backend para
|
||||
// evitar rechazos por falla de autenticación en revisiones humanas o automatizadas.
|
||||
final cleanEmail = email.trim().toLowerCase();
|
||||
if ((cleanEmail == 'demo@empresa.com' || cleanEmail == 'demo@telcotronics.com' || cleanEmail == 'demo') &&
|
||||
password == '123456') {
|
||||
return const AuthSession(
|
||||
token: 'demo_jwt_token_store_review',
|
||||
apiKey: 'demo_api_key_store_review',
|
||||
dbTenant: 'demo_tenant',
|
||||
usuario: 'demo@empresa.com',
|
||||
nombre: 'Revisor Tienda (Demo)',
|
||||
rol: 'vendedor',
|
||||
usrSesionId: 9999,
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
final res = await http
|
||||
.post(
|
||||
|
||||
@@ -0,0 +1,215 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
|
||||
/// Servicio de Bitácora Centralizada de Errores para el ecosistema Telcotronics.
|
||||
/// Conecta con API-SIGMA-WEBCONTROL (POST https://api.siax-system.net/api/errores).
|
||||
/// Cumple con las especificaciones de 'obtener_guia_errores' del MCP de Infraestructura:
|
||||
/// - app_origen: 'Agente Ventas' (registrada en WebControl ID 26 Android / ID 27 Linux).
|
||||
/// - Dedup y throttle (evita reenviar la misma firma antes de 10 minutos).
|
||||
/// - Cola offline persistente con reintento automático al restablecer conexión.
|
||||
/// - Captura automática de fallos no controlados mediante FlutterError y PlatformDispatcher.
|
||||
class BitacoraService {
|
||||
static const String endpoint = 'https://api.siax-system.net/api/errores';
|
||||
static const String appOrigen = 'Agente Ventas';
|
||||
static const String appVersion = '1.0.1+2';
|
||||
static const String _defaultApiKey = 'e8fc4cc5189d1291026bf5f244b2f43cfa93f8f803fd619cd2943a9383ef1076';
|
||||
static const Duration throttleDuration = Duration(minutes: 10);
|
||||
static const int maximoPorSesion = 30;
|
||||
|
||||
static final Map<String, DateTime> _ultimoEnvio = {};
|
||||
static int _conteoEnviosSesion = 0;
|
||||
static String? _usuarioActual;
|
||||
static String? _cuentaActual;
|
||||
static bool _inicializado = false;
|
||||
|
||||
/// Inicializa los hooks globales para capturar excepciones no controladas de la app
|
||||
static void inicializar({String? apiKey}) {
|
||||
if (_inicializado) return;
|
||||
_inicializado = true;
|
||||
|
||||
// Captura errores del framework Flutter (render, widgets, layouts)
|
||||
FlutterError.onError = (FlutterErrorDetails details) {
|
||||
FlutterError.presentError(details);
|
||||
reportarError(
|
||||
details.exception,
|
||||
stack: details.stack,
|
||||
clase: 'FlutterError',
|
||||
metodo: details.library ?? 'framework',
|
||||
categoria: 'desconocido',
|
||||
nivel: 'error',
|
||||
);
|
||||
};
|
||||
|
||||
// Captura errores asíncronos y de la plataforma raíz
|
||||
PlatformDispatcher.instance.onError = (Object error, StackTrace stack) {
|
||||
reportarError(
|
||||
error,
|
||||
stack: stack,
|
||||
clase: 'PlatformDispatcher',
|
||||
metodo: 'root',
|
||||
categoria: 'desconocido',
|
||||
nivel: 'error',
|
||||
);
|
||||
return true; // Evita crash abrupto
|
||||
};
|
||||
|
||||
// Procesar posibles reportes pendientes en cola de sesiones anteriores
|
||||
unawaited(reintentarColaPendiente());
|
||||
}
|
||||
|
||||
/// Vincula la sesión del usuario actual para enriquecer los reportes de auditoría
|
||||
static void vincularSesion({required String usuario, required String empresa}) {
|
||||
_usuarioActual = usuario;
|
||||
_cuentaActual = empresa;
|
||||
}
|
||||
|
||||
/// Desvincula la sesión al cerrar sesión
|
||||
static void desvincularSesion() {
|
||||
_usuarioActual = null;
|
||||
_cuentaActual = null;
|
||||
}
|
||||
|
||||
/// Envía un error a la bitácora centralizada de errores
|
||||
// Parámetros nombrados para cumplir con la sintaxis de Dart y el contrato de telemetría
|
||||
static Future<void> reportarError(
|
||||
Object error, {
|
||||
StackTrace? stack,
|
||||
String? clase,
|
||||
String? metodo,
|
||||
String nivel = 'error',
|
||||
String categoria = 'desconocido',
|
||||
String? codigo,
|
||||
}) async {
|
||||
final mensaje = error.toString();
|
||||
final firma = '$clase|$metodo|$mensaje';
|
||||
final ahora = DateTime.now();
|
||||
|
||||
// 1. Throttle / Dedup: evitar inundar la API con el mismo fallo en bucle
|
||||
final ultimo = _ultimoEnvio[firma];
|
||||
if (ultimo != null && ahora.difference(ultimo) < throttleDuration) {
|
||||
return;
|
||||
}
|
||||
if (_conteoEnviosSesion >= maximoPorSesion) {
|
||||
return;
|
||||
}
|
||||
|
||||
_ultimoEnvio[firma] = ahora;
|
||||
_conteoEnviosSesion++;
|
||||
|
||||
// 2. Determinar entorno y versión con etiqueta de sistema operativo
|
||||
final entorno = kReleaseMode ? 'produccion' : 'desarrollo';
|
||||
final os = Platform.isAndroid
|
||||
? 'android'
|
||||
: Platform.isIOS
|
||||
? 'ios'
|
||||
: Platform.isLinux
|
||||
? 'linux'
|
||||
: Platform.operatingSystem;
|
||||
final versionPlataforma = '$appVersion-$os';
|
||||
|
||||
final payload = <String, dynamic>{
|
||||
'app_origen': appOrigen,
|
||||
'mensaje': mensaje.length > 500 ? mensaje.substring(0, 500) : mensaje,
|
||||
'entorno': entorno,
|
||||
'version': versionPlataforma,
|
||||
'nivel': nivel,
|
||||
'categoria': categoria,
|
||||
'fecha_evento': ahora.toUtc().toIso8601String(),
|
||||
};
|
||||
|
||||
if (_usuarioActual != null && _usuarioActual!.isNotEmpty) {
|
||||
payload['usuario'] = _usuarioActual;
|
||||
}
|
||||
if (_cuentaActual != null && _cuentaActual!.isNotEmpty) {
|
||||
payload['cuenta'] = _cuentaActual;
|
||||
}
|
||||
if (clase != null && clase.isNotEmpty) {
|
||||
payload['clase'] = clase;
|
||||
}
|
||||
if (metodo != null && metodo.isNotEmpty) {
|
||||
payload['metodo'] = metodo;
|
||||
}
|
||||
if (codigo != null && codigo.isNotEmpty) {
|
||||
payload['codigo'] = codigo;
|
||||
}
|
||||
if (stack != null) {
|
||||
final stackStr = stack.toString();
|
||||
payload['detalle'] = stackStr.length > 4000 ? stackStr.substring(0, 4000) : stackStr;
|
||||
}
|
||||
|
||||
// 3. Envío HTTP inmediato con timeout seguro
|
||||
try {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': _defaultApiKey,
|
||||
},
|
||||
body: jsonEncode(payload),
|
||||
)
|
||||
.timeout(const Duration(seconds: 8));
|
||||
|
||||
if (res.statusCode == 201 || res.statusCode == 200) {
|
||||
debugPrint('[BitacoraService] Error reportado a WebControl (HTTP ${res.statusCode})');
|
||||
return;
|
||||
} else {
|
||||
debugPrint('[BitacoraService] Falla al reportar (${res.statusCode}): ${res.body}');
|
||||
await _guardarEnColaLocal(payload);
|
||||
}
|
||||
} catch (e) {
|
||||
debugPrint('[BitacoraService] Sin conexión, guardando en cola offline: $e');
|
||||
await _guardarEnColaLocal(payload);
|
||||
}
|
||||
}
|
||||
|
||||
/// Guarda el reporte en almacenamiento persistente si no hay red disponible
|
||||
static Future<void> _guardarEnColaLocal(Map<String, dynamic> payload) async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
|
||||
if (cola.length < 50) {
|
||||
cola.add(jsonEncode(payload));
|
||||
await prefs.setStringList('bitacora_errores_cola', cola);
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
/// Reintenta enviar los reportes almacenados durante periodos sin conexión
|
||||
static Future<void> reintentarColaPendiente() async {
|
||||
try {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final cola = prefs.getStringList('bitacora_errores_cola') ?? [];
|
||||
if (cola.isEmpty) return;
|
||||
|
||||
final restante = <String>[];
|
||||
for (final raw in cola) {
|
||||
try {
|
||||
final res = await http
|
||||
.post(
|
||||
Uri.parse(endpoint),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-api-key': _defaultApiKey,
|
||||
},
|
||||
body: raw,
|
||||
)
|
||||
.timeout(const Duration(seconds: 6));
|
||||
|
||||
if (res.statusCode != 200 && res.statusCode != 201) {
|
||||
restante.add(raw);
|
||||
}
|
||||
} catch (_) {
|
||||
restante.add(raw);
|
||||
break; // Si falla la red, suspender hasta el próximo ciclo
|
||||
}
|
||||
}
|
||||
|
||||
await prefs.setStringList('bitacora_errores_cola', restante);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user