- ApiAuthService: login WebControl → guarda jwt + apiKey + db_tenant - Sincronizador: pull alarmas/zonas/usuarios/mensajes/banners + push pendientes - DAOs: métodos adicionales en alarmas, eventos, usuarios - Páginas actualizadas: ConectarProveedorPage, ControlAccesoPage, MensajeríaPage, MonitoreoAlarmaPage Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
262 lines
8.7 KiB
Dart
262 lines
8.7 KiB
Dart
import 'dart:convert';
|
|
import 'package:http/http.dart' as http;
|
|
import 'api_auth_service.dart';
|
|
import '../db/dao/alarmas_dao.dart';
|
|
import '../db/dao/accesos_dao.dart';
|
|
import '../db/dao/usuarios_dao.dart';
|
|
import '../db/dao/zonas_dao.dart';
|
|
import '../db/dao/mensajes_dao.dart';
|
|
import '../db/dao/banners_dao.dart';
|
|
import '../db/dao/sync_log_dao.dart';
|
|
import '../db/dao/configuracion_dao.dart';
|
|
import '../models/alarma.dart';
|
|
import '../models/acceso.dart';
|
|
import '../models/usuario.dart';
|
|
import '../models/zona.dart';
|
|
import '../models/mensaje.dart';
|
|
import '../models/banner_item.dart';
|
|
|
|
/// Orquesta la sincronización entre API_CENTINEL_SECURITY y SQLite.
|
|
/// Las páginas nunca llaman a la API directamente — solo leen SQLite.
|
|
///
|
|
/// Todas las llamadas van a [_centinelBase] usando los headers de
|
|
/// [ApiAuthService.getCentinelHeaders()] (x-api-key + x-database).
|
|
class Sincronizador {
|
|
static const _centinelBase = 'https://api.telcotronics.com';
|
|
|
|
Sincronizador._();
|
|
static final Sincronizador instance = Sincronizador._();
|
|
|
|
final _auth = ApiAuthService.instance;
|
|
final _syncLog = SyncLogDao();
|
|
final _config = ConfiguracionDao();
|
|
|
|
// ── Punto de entrada principal ─────────────────────────────────────────────
|
|
Future<void> sincronizar() async {
|
|
final autenticado = await _auth.isAuthenticated();
|
|
if (!autenticado) {
|
|
await _syncLog.registrar(
|
|
tipo: 'full',
|
|
estado: 'error',
|
|
detalle: 'Sin credenciales Centinel — sincronización omitida',
|
|
);
|
|
return;
|
|
}
|
|
|
|
try {
|
|
await sincronizarZonas();
|
|
await sincronizarUsuarios();
|
|
await sincronizarAlarmas();
|
|
await sincronizarAccesos();
|
|
await sincronizarMensajes();
|
|
await sincronizarBanners();
|
|
await pushPendientes();
|
|
|
|
await _syncLog.registrar(
|
|
tipo: 'full',
|
|
estado: 'ok',
|
|
detalle: 'Sincronización completa',
|
|
);
|
|
} catch (e) {
|
|
await _syncLog.registrar(
|
|
tipo: 'full',
|
|
estado: 'error',
|
|
detalle: e.toString(),
|
|
);
|
|
}
|
|
}
|
|
|
|
// ── Métodos específicos ────────────────────────────────────────────────────
|
|
|
|
Future<void> sincronizarZonas() async {
|
|
final data = await _get('/zonas');
|
|
if (data == null) return;
|
|
final dao = ZonasDao();
|
|
for (final item in data) {
|
|
final z = Zona.fromMap({...item, 'sincronizado': 1});
|
|
final existente = await dao.getById(z.id);
|
|
if (existente == null) {
|
|
await dao.insert(z);
|
|
} else {
|
|
await dao.update(z);
|
|
}
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'zonas: ${data.length} registros');
|
|
}
|
|
|
|
Future<void> sincronizarUsuarios() async {
|
|
final data = await _get('/usuarios');
|
|
if (data == null) return;
|
|
final dao = UsuariosDao();
|
|
for (final item in data) {
|
|
final u = Usuario.fromMap({...item, 'sincronizado': 1});
|
|
final existente = await dao.getById(u.id);
|
|
if (existente == null) {
|
|
await dao.insert(u);
|
|
} else {
|
|
await dao.update(u);
|
|
}
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'usuarios: ${data.length} registros');
|
|
}
|
|
|
|
Future<void> sincronizarAlarmas() async {
|
|
final data = await _get('/alarmas');
|
|
if (data == null) return;
|
|
final dao = AlarmasDao();
|
|
for (final item in data) {
|
|
final a = Alarma.fromMap({...item, 'sincronizado': 1});
|
|
final existente = await dao.getById(a.id);
|
|
if (existente == null) {
|
|
await dao.insert(a);
|
|
} else {
|
|
await dao.update(a);
|
|
}
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'alarmas: ${data.length} registros');
|
|
}
|
|
|
|
Future<void> sincronizarAccesos() async {
|
|
final data = await _get('/accesos');
|
|
if (data == null) return;
|
|
final dao = AccesosDao();
|
|
for (final item in data) {
|
|
final a = Acceso.fromMap({...item, 'sincronizado': 1});
|
|
await dao.insert(a);
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'accesos: ${data.length} registros');
|
|
}
|
|
|
|
Future<void> sincronizarMensajes() async {
|
|
final data = await _get('/mensajes');
|
|
if (data == null) return;
|
|
final dao = MensajesDao();
|
|
for (final item in data) {
|
|
final m = Mensaje.fromMap({...item, 'sincronizado': 1});
|
|
await dao.insert(m);
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'mensajes: ${data.length} registros');
|
|
}
|
|
|
|
Future<void> sincronizarBanners() async {
|
|
final data = await _get('/banners');
|
|
if (data == null) return;
|
|
final dao = BannersDao();
|
|
for (final item in data) {
|
|
final b = BannerItem.fromMap({...item, 'sincronizado': 1});
|
|
final existente = await dao.getById(b.id);
|
|
if (existente == null) {
|
|
await dao.insert(b);
|
|
} else {
|
|
await dao.update(b);
|
|
}
|
|
}
|
|
await _syncLog.registrar(tipo: 'parcial', estado: 'ok',
|
|
detalle: 'banners: ${data.length} registros');
|
|
}
|
|
|
|
// ── Push de pendientes (local → API_CENTINEL_SECURITY) ────────────────────
|
|
Future<void> pushPendientes() async {
|
|
await _pushAlarmasPendientes();
|
|
await _pushUsuariosPendientes();
|
|
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
|
detalle: 'Push de pendientes completado');
|
|
}
|
|
|
|
/// Empuja alarmas con sincronizado=0 usando los endpoints reales de Centinel.
|
|
/// El estado de la alarma determina el endpoint: escalar / resolver / silenciar.
|
|
Future<void> _pushAlarmasPendientes() async {
|
|
final pendientes = await AlarmasDao().getPendientes();
|
|
if (pendientes.isEmpty) return;
|
|
final headers = await _auth.getCentinelHeaders();
|
|
if (headers == null) return;
|
|
|
|
for (final a in pendientes) {
|
|
try {
|
|
final http.Response resp;
|
|
|
|
switch (a.estado) {
|
|
case 'escalada':
|
|
resp = await http.post(
|
|
Uri.parse('$_centinelBase/api/alarmas/${a.id}/escalar'),
|
|
headers: headers,
|
|
body: jsonEncode({'severidad_nueva': a.severidad}),
|
|
).timeout(const Duration(seconds: 8));
|
|
break;
|
|
case 'silenciada':
|
|
resp = await http.put(
|
|
Uri.parse('$_centinelBase/api/alarmas/${a.id}/silenciar'),
|
|
headers: headers,
|
|
body: jsonEncode({}),
|
|
).timeout(const Duration(seconds: 8));
|
|
break;
|
|
default: // resuelta
|
|
resp = await http.put(
|
|
Uri.parse('$_centinelBase/api/alarmas/${a.id}/resolver'),
|
|
headers: headers,
|
|
body: jsonEncode({'notas': a.notas}),
|
|
).timeout(const Duration(seconds: 8));
|
|
}
|
|
|
|
if (resp.statusCode == 200 || resp.statusCode == 204) {
|
|
final db = AlarmasDao();
|
|
await db.update(a);
|
|
}
|
|
} catch (_) {
|
|
// Continúa — se reintentará en el próximo ciclo de sync
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Sincroniza usuarios nuevos (registrados offline) al dispositivo Centinel.
|
|
Future<void> _pushUsuariosPendientes() async {
|
|
final pendientes = await UsuariosDao().getPendientes();
|
|
if (pendientes.isEmpty) return;
|
|
final headers = await _auth.getCentinelHeaders();
|
|
if (headers == null) return;
|
|
// Requiere deviceId configurado — pendiente cuando se registre el dispositivo
|
|
final deviceId = await _config.get('centinel_device_id');
|
|
if (deviceId == null || deviceId.isEmpty) return;
|
|
|
|
for (final u in pendientes) {
|
|
try {
|
|
await http.post(
|
|
Uri.parse('$_centinelBase/api/devices/$deviceId/employees'),
|
|
headers: headers,
|
|
body: jsonEncode({
|
|
'employeeNo': u.id.toString(),
|
|
'name': u.nombre,
|
|
'userType': 'normal',
|
|
}),
|
|
).timeout(const Duration(seconds: 8));
|
|
} catch (_) {}
|
|
}
|
|
}
|
|
|
|
// ── Helpers ────────────────────────────────────────────────────────────────
|
|
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
|
|
final headers = await _auth.getCentinelHeaders();
|
|
if (headers == null) return null;
|
|
|
|
try {
|
|
final resp = await http.get(
|
|
Uri.parse('$_centinelBase$endpoint'),
|
|
headers: headers,
|
|
).timeout(const Duration(seconds: 10));
|
|
|
|
if (resp.statusCode == 200) {
|
|
final body = jsonDecode(resp.body);
|
|
if (body is List) return body.cast<Map<String, dynamic>>();
|
|
}
|
|
return null;
|
|
} catch (_) {
|
|
return null;
|
|
}
|
|
}
|
|
}
|