feat: implementacion completa de 8 modulos, sincronizador centinel, mcp y bitacora de errores
This commit is contained in:
@@ -0,0 +1,120 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:flutter/foundation.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'api_auth_service.dart';
|
||||
|
||||
// Comentario explicativo: Servicio cliente para reporte y consulta centralizada de errores en la bitácora
|
||||
// oficial de API-SIGMA-WEBCONTROL (POST/GET https://api.siax-system.net/api/errores).
|
||||
// Implementa deduplicación en memoria, ventana de enfriamiento (cooldown de 10 min) y captura global.
|
||||
class ErrorReporterService {
|
||||
static const String _endpoint = 'https://api.siax-system.net/api/errores';
|
||||
static const String _apiKeyFija = 'e8fc4cc5189d1291026bf5f244b2f43cfa93f8f803fd619cd2943a9383ef1076';
|
||||
static const String _appOrigen = 'Central_monitoreo';
|
||||
|
||||
ErrorReporterService._();
|
||||
static final ErrorReporterService instance = ErrorReporterService._();
|
||||
|
||||
final Map<String, DateTime> _erroresRecientes = {};
|
||||
static const Duration _cooldown = Duration(minutes: 10);
|
||||
|
||||
// Comentario explicativo: Inicializa los escuchadores globales de excepciones no capturadas en Flutter
|
||||
void inicializar() {
|
||||
FlutterError.onError = (details) {
|
||||
FlutterError.presentError(details);
|
||||
reportar(
|
||||
mensaje: details.exceptionAsString(),
|
||||
categoria: 'validacion',
|
||||
clase: details.library ?? 'flutter',
|
||||
detalle: details.stack?.toString(),
|
||||
);
|
||||
};
|
||||
|
||||
PlatformDispatcher.instance.onError = (error, stack) {
|
||||
reportar(
|
||||
mensaje: error.toString(),
|
||||
categoria: 'desconocido',
|
||||
detalle: stack.toString(),
|
||||
);
|
||||
return true;
|
||||
};
|
||||
}
|
||||
|
||||
// Comentario explicativo: Envía un reporte individual a la bitácora centralizada con throttle anti-spam
|
||||
Future<bool> reportar({
|
||||
required String mensaje,
|
||||
String categoria = 'desconocido',
|
||||
String? clase,
|
||||
String? metodo,
|
||||
String nivel = 'error',
|
||||
int? codigo,
|
||||
dynamic detalle,
|
||||
}) async {
|
||||
final firma = '$mensaje:$categoria:$clase:$metodo';
|
||||
final ahora = DateTime.now();
|
||||
|
||||
// Deduplicación en memoria con ventana de 10 minutos
|
||||
if (_erroresRecientes.containsKey(firma)) {
|
||||
final ultimaVez = _erroresRecientes[firma]!;
|
||||
if (ahora.difference(ultimaVez) < _cooldown) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
_erroresRecientes[firma] = ahora;
|
||||
|
||||
try {
|
||||
final usuario = await ApiAuthService.instance.getUsuario() ?? 'anonimo';
|
||||
final plataforma = kIsWeb ? 'web' : Platform.operatingSystem;
|
||||
final versionStr = '1.0.0+1-$plataforma';
|
||||
|
||||
final body = {
|
||||
'app_origen': _appOrigen,
|
||||
'mensaje': mensaje,
|
||||
'categoria': categoria,
|
||||
'nivel': nivel,
|
||||
'usuario': usuario,
|
||||
'version': versionStr,
|
||||
'fecha_evento': ahora.toIso8601String(),
|
||||
if (clase != null) 'clase': clase,
|
||||
if (metodo != null) 'metodo': metodo,
|
||||
if (codigo != null) 'codigo': codigo,
|
||||
if (detalle != null) 'detalle': detalle.toString(),
|
||||
};
|
||||
|
||||
final resp = await http.post(
|
||||
Uri.parse(_endpoint),
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'accept': 'application/json',
|
||||
'x-api-key': _apiKeyFija,
|
||||
},
|
||||
body: jsonEncode(body),
|
||||
).timeout(const Duration(seconds: 5));
|
||||
|
||||
return resp.statusCode == 200 || resp.statusCode == 201;
|
||||
} catch (_) {
|
||||
// Falla silenciosa si no hay conexión de red externa para no interferir con la app
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Comentario explicativo: Consulta los errores registrados de esta app en API-SIGMA-WEBCONTROL para autodiagnóstico
|
||||
Future<List<Map<String, dynamic>>> consultarErrores({int limite = 50}) async {
|
||||
try {
|
||||
final url = Uri.parse('$_endpoint?app_origen=$_appOrigen&limite=$limite');
|
||||
final resp = await http.get(url, headers: {
|
||||
'accept': 'application/json',
|
||||
'x-api-key': _apiKeyFija,
|
||||
}).timeout(const Duration(seconds: 6));
|
||||
|
||||
if (resp.statusCode == 200) {
|
||||
final data = jsonDecode(resp.body);
|
||||
if (data is Map && data['errores'] is List) {
|
||||
return List<Map<String, dynamic>>.from(data['errores']);
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
return [];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user