216 lines
7.3 KiB
Dart
216 lines
7.3 KiB
Dart
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 (_) {}
|
|
}
|
|
}
|