feat: implementacion completa de 8 modulos, sincronizador centinel, mcp y bitacora de errores
This commit is contained in:
@@ -0,0 +1,244 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/foundation.dart';
|
||||
// Comentario explicativo: Importación de services.dart para reproducir alertas sonoras con SystemSound ante pánico
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import 'api_auth_service.dart';
|
||||
import '../db/dao/incidentes_dao.dart';
|
||||
import '../db/dao/cache_alarmas_dao.dart';
|
||||
import '../db/dao/cache_clientes_dao.dart';
|
||||
import '../db/dao/sync_log_dao.dart';
|
||||
import '../db/dao/configuracion_dao.dart';
|
||||
|
||||
/// Servicio de sincronización periódica en segundo plano.
|
||||
/// Administra el ciclo offline-first entre SQLite local y los backends del ecosistema:
|
||||
/// - Empuja incidentes locales no sincronizados hacia Centinel / WebControl.
|
||||
/// - Consulta el estado de alarmas y clientes para refrescar el caché SQLite.
|
||||
/// - Registra cada ciclo en la tabla sync_log para auditoría de conectividad.
|
||||
class Sincronizador {
|
||||
static const String _centinelBase = 'https://api.telcotronics.com';
|
||||
static const String _webcontrolBase = 'https://api.siax-system.net';
|
||||
|
||||
Sincronizador._();
|
||||
static final Sincronizador instance = Sincronizador._();
|
||||
|
||||
Timer? _timer;
|
||||
int _intervaloSegundos = 30;
|
||||
|
||||
final ValueNotifier<bool> isSyncing = ValueNotifier<bool>(false);
|
||||
final ValueNotifier<DateTime?> lastSyncTime = ValueNotifier<DateTime?>(null);
|
||||
final ValueNotifier<String?> lastSyncStatus = ValueNotifier<String?>(null);
|
||||
|
||||
final _incidentesDao = IncidentesDao();
|
||||
final _alarmasDao = CacheAlarmasDao();
|
||||
final _clientesDao = CacheClientesDao();
|
||||
final _syncLogDao = SyncLogDao();
|
||||
final _configDao = ConfiguracionDao();
|
||||
|
||||
// Comentario explicativo: Notificador del conteo de alarmas críticas para señalización visual y sonora
|
||||
final ValueNotifier<int> criticalAlarmsCount = ValueNotifier<int>(0);
|
||||
|
||||
// Comentario explicativo: Getter público para consultar el intervalo actual de sincronización
|
||||
int get intervaloSegundos => _intervaloSegundos;
|
||||
|
||||
// Comentario explicativo: Inicia el ciclo periódico de sincronización automática
|
||||
void iniciar({int intervaloSegundos = 30}) {
|
||||
_intervaloSegundos = intervaloSegundos;
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(Duration(seconds: _intervaloSegundos), (_) => sincronizarAhora());
|
||||
// Ejecuta una sincronización inmediata al arrancar
|
||||
sincronizarAhora();
|
||||
}
|
||||
|
||||
// Comentario explicativo: Modifica en caliente la frecuencia del timer de sincronización periódica
|
||||
void cambiarIntervalo(int nuevosSegundos) {
|
||||
_intervaloSegundos = nuevosSegundos;
|
||||
if (_timer != null) {
|
||||
_timer?.cancel();
|
||||
_timer = Timer.periodic(Duration(seconds: _intervaloSegundos), (_) => sincronizarAhora());
|
||||
}
|
||||
}
|
||||
|
||||
// Comentario explicativo: Detiene el timer periódico (ej. al cerrar sesión o cerrar la app)
|
||||
void detener() {
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
|
||||
// Comentario explicativo: Ejecuta un ciclo manual o programado de sincronización completa
|
||||
Future<bool> sincronizarAhora() async {
|
||||
if (isSyncing.value) return false;
|
||||
|
||||
isSyncing.value = true;
|
||||
int pushCount = 0;
|
||||
int pullAlarmasCount = 0;
|
||||
bool exito = true;
|
||||
|
||||
try {
|
||||
final headers = await ApiAuthService.instance.getCentinelHeaders();
|
||||
|
||||
// ── Paso 1: Push de incidentes locales pendientes (sincronizado = 0) ───
|
||||
final pendientes = await _incidentesDao.getPendientes();
|
||||
for (final inc in pendientes) {
|
||||
final id = inc['id'] as int;
|
||||
bool enviado = false;
|
||||
|
||||
if (headers != null) {
|
||||
try {
|
||||
final url = Uri.parse('$_centinelBase/api/incidents');
|
||||
final resp = await http.post(
|
||||
url,
|
||||
headers: headers,
|
||||
body: jsonEncode({
|
||||
'alarmaId': inc['alarma_id'],
|
||||
'clienteId': inc['cliente_id'],
|
||||
'tipo': inc['tipo'],
|
||||
'operador': inc['operador'],
|
||||
'notas': inc['notas'],
|
||||
'timestamp': inc['timestamp'],
|
||||
'resuelto': inc['resuelto'] == 1,
|
||||
}),
|
||||
).timeout(const Duration(seconds: 5));
|
||||
|
||||
if (resp.statusCode == 200 || resp.statusCode == 201) {
|
||||
enviado = true;
|
||||
}
|
||||
} catch (_) {
|
||||
// Error de red puntual al empujar incidente
|
||||
}
|
||||
} else {
|
||||
// En modo demo local, se marca como procesado para la sesión
|
||||
enviado = true;
|
||||
}
|
||||
|
||||
if (enviado) {
|
||||
await _incidentesDao.marcarSincronizado(id);
|
||||
pushCount++;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paso 2: Pull de alarmas activas ───────────────────────────────────
|
||||
// Comentario explicativo: Soporta tanto respuestas tipo List como payload {success:true, data:[...]} de Centinel API
|
||||
if (headers != null) {
|
||||
try {
|
||||
final url = Uri.parse('$_centinelBase/api/alarmas');
|
||||
final resp = await http.get(url, headers: headers).timeout(const Duration(seconds: 6));
|
||||
if (resp.statusCode == 200) {
|
||||
final decoded = jsonDecode(resp.body);
|
||||
List<dynamic>? rawList;
|
||||
if (decoded is List) {
|
||||
rawList = decoded;
|
||||
} else if (decoded is Map && decoded['data'] is List) {
|
||||
rawList = decoded['data'] as List;
|
||||
}
|
||||
|
||||
if (rawList != null && rawList.isNotEmpty) {
|
||||
final mapped = rawList.map((item) {
|
||||
final m = item is Map<String, dynamic> ? item : Map<String, dynamic>.from(item as Map);
|
||||
final estadoRaw = (m['estado'] as String? ?? 'activa').toLowerCase();
|
||||
final notas = m['notas'] as String? ?? '';
|
||||
final dbName = m['database_name'] as String?;
|
||||
final clienteNombre = m['clienteNombre'] ?? m['cliente_nombre'] ?? (dbName != null ? 'Cliente ($dbName)' : 'Cliente Centinel');
|
||||
final tipo = m['tipo'] ?? (notas.toLowerCase().contains('panico') ? 'pánico' : 'intrusión');
|
||||
|
||||
return {
|
||||
'id': m['id'] ?? DateTime.now().millisecondsSinceEpoch,
|
||||
'cliente_id': m['clienteId'] ?? m['cliente_id'] ?? 1,
|
||||
'cliente_nombre': clienteNombre,
|
||||
'tipo': tipo,
|
||||
'severidad': m['severidad'] ?? 3,
|
||||
'zona_nombre': m['zona_nombre'] ?? m['zona'] ?? 'Zona Principal',
|
||||
'estado': estadoRaw,
|
||||
'timestamp': m['timestamp_evento'] ?? m['timestamp'] ?? m['created_at'] ?? DateTime.now().toIso8601String(),
|
||||
'notas': notas,
|
||||
};
|
||||
}).toList();
|
||||
await _alarmasDao.reemplazarTodas(mapped);
|
||||
pullAlarmasCount = mapped.length;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Si Centinel no responde, se conserva el caché local de SQLite
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paso 3: Pull de clientes desde WebControl para actualizar cache_clientes ─
|
||||
// Comentario explicativo: Consulta clientes en WebControl y mapea exactamente los campos del esquema SQLite (cache_clientes)
|
||||
int pullClientesCount = 0;
|
||||
if (headers != null) {
|
||||
try {
|
||||
final url = Uri.parse('$_webcontrolBase/api/clientes');
|
||||
final resp = await http.get(url, headers: headers).timeout(const Duration(seconds: 6));
|
||||
if (resp.statusCode == 200) {
|
||||
final decoded = jsonDecode(resp.body);
|
||||
List<dynamic>? rawList;
|
||||
if (decoded is List) {
|
||||
rawList = decoded;
|
||||
} else if (decoded is Map && decoded['data'] is List) {
|
||||
rawList = decoded['data'] as List;
|
||||
}
|
||||
|
||||
if (rawList != null && rawList.isNotEmpty) {
|
||||
final mapped = rawList.map((item) {
|
||||
final m = item is Map<String, dynamic> ? item : Map<String, dynamic>.from(item as Map);
|
||||
return {
|
||||
'id': m['id'] ?? DateTime.now().millisecondsSinceEpoch,
|
||||
'nombre': m['nombre'] ?? 'Cliente',
|
||||
'estado': m['estado'] ?? 'normal',
|
||||
'alarmas_activas': m['alarmasActivas'] ?? m['alarmas_activas'] ?? 0,
|
||||
'alarmas_criticas': m['alarmasCriticas'] ?? m['alarmas_criticas'] ?? 0,
|
||||
'ultima_actualizacion': DateTime.now().toIso8601String(),
|
||||
};
|
||||
}).toList();
|
||||
await _clientesDao.reemplazarTodos(mapped);
|
||||
pullClientesCount = mapped.length;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Si WebControl no responde, se conserva el caché local
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paso 3.1: Evaluar conteo de alarmas críticas y emitir alerta acústica ─
|
||||
// Comentario explicativo: Monitorea alarmas críticas activas y dispara alerta sonora si está habilitada en la configuración
|
||||
final criticas = await _alarmasDao.contarCriticas();
|
||||
criticalAlarmsCount.value = criticas;
|
||||
if (criticas > 0) {
|
||||
final sonido = await _configDao.get('sonido_alerta');
|
||||
if (sonido == null || sonido == '1') {
|
||||
try {
|
||||
await SystemSound.play(SystemSoundType.alert);
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Paso 4: Registro en bitácora local sync_log ────────────────────────
|
||||
final detalle = headers == null
|
||||
? 'Sincronización local / modo demo activa ($pushCount incidentes procesados)'
|
||||
: 'Sync OK: $pushCount incidentes enviados, $pullAlarmasCount alarmas, $pullClientesCount clientes';
|
||||
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'ciclo_periodico',
|
||||
estado: 'ok',
|
||||
detalle: detalle,
|
||||
);
|
||||
|
||||
lastSyncTime.value = DateTime.now();
|
||||
lastSyncStatus.value = detalle;
|
||||
} catch (e) {
|
||||
exito = false;
|
||||
final err = 'Fallo en ciclo de sincronización: $e';
|
||||
lastSyncStatus.value = err;
|
||||
await _syncLogDao.registrar(
|
||||
tipo: 'ciclo_periodico',
|
||||
estado: 'error',
|
||||
detalle: err,
|
||||
);
|
||||
} finally {
|
||||
isSyncing.value = false;
|
||||
}
|
||||
|
||||
return exito;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user