feat: ApiAuthService + Sincronizador reescritos para WebControl/Centinel
- 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>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
4724f84b04
commit
efa4a792f4
@@ -16,9 +16,14 @@ import '../models/zona.dart';
|
||||
import '../models/mensaje.dart';
|
||||
import '../models/banner_item.dart';
|
||||
|
||||
/// Orquesta la sincronización entre la API y SQLite.
|
||||
/// 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._();
|
||||
|
||||
@@ -33,7 +38,7 @@ class Sincronizador {
|
||||
await _syncLog.registrar(
|
||||
tipo: 'full',
|
||||
estado: 'error',
|
||||
detalle: 'Sin token válido — sincronización omitida',
|
||||
detalle: 'Sin credenciales Centinel — sincronización omitida',
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -155,63 +160,79 @@ class Sincronizador {
|
||||
detalle: 'banners: ${data.length} registros');
|
||||
}
|
||||
|
||||
// ── Push de pendientes (local → API) ───────────────────────────────────────
|
||||
// ── Push de pendientes (local → API_CENTINEL_SECURITY) ────────────────────
|
||||
Future<void> pushPendientes() async {
|
||||
await _pushAlarmasPendientes();
|
||||
await _pushAccesosPendientes();
|
||||
await _pushMensajesPendientes();
|
||||
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 baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
final headers = await _auth.getCentinelHeaders();
|
||||
if (headers == null) return;
|
||||
|
||||
for (final a in pendientes) {
|
||||
try {
|
||||
await http.put(
|
||||
Uri.parse('$baseUrl/alarmas/${a.id}'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(a.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
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 con el siguiente — se reintentará en el próximo ciclo
|
||||
// Continúa — se reintentará en el próximo ciclo de sync
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _pushAccesosPendientes() async {
|
||||
final pendientes = await AccesosDao().getPendientes();
|
||||
/// Sincroniza usuarios nuevos (registrados offline) al dispositivo Centinel.
|
||||
Future<void> _pushUsuariosPendientes() async {
|
||||
final pendientes = await UsuariosDao().getPendientes();
|
||||
if (pendientes.isEmpty) return;
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
for (final a in pendientes) {
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$baseUrl/accesos'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(a.toMap()),
|
||||
).timeout(const Duration(seconds: 8));
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
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;
|
||||
|
||||
Future<void> _pushMensajesPendientes() async {
|
||||
final pendientes = await MensajesDao().getPendientes();
|
||||
if (pendientes.isEmpty) return;
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return;
|
||||
for (final m in pendientes) {
|
||||
for (final u in pendientes) {
|
||||
try {
|
||||
await http.post(
|
||||
Uri.parse('$baseUrl/mensajes'),
|
||||
headers: _headers(token),
|
||||
body: jsonEncode(m.toMap()),
|
||||
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 (_) {}
|
||||
}
|
||||
@@ -219,14 +240,13 @@ class Sincronizador {
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
|
||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
||||
final token = await _auth.getToken();
|
||||
if (baseUrl.isEmpty || token == null) return null;
|
||||
final headers = await _auth.getCentinelHeaders();
|
||||
if (headers == null) return null;
|
||||
|
||||
try {
|
||||
final resp = await http.get(
|
||||
Uri.parse('$baseUrl$endpoint'),
|
||||
headers: _headers(token),
|
||||
Uri.parse('$_centinelBase$endpoint'),
|
||||
headers: headers,
|
||||
).timeout(const Duration(seconds: 10));
|
||||
|
||||
if (resp.statusCode == 200) {
|
||||
@@ -238,9 +258,4 @@ class Sincronizador {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> _headers(String token) => {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user