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
@@ -129,4 +129,32 @@ class AlarmasDao {
|
|||||||
LIMIT ?
|
LIMIT ?
|
||||||
''', [limit]);
|
''', [limit]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Alarmas resueltas y silenciadas (historial).
|
||||||
|
Future<List<Map<String, dynamic>>> getHistorialConZona({int limit = 50}) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
return db.rawQuery('''
|
||||||
|
SELECT al.id, al.tipo, al.severidad, al.timestamp, al.estado, al.notas,
|
||||||
|
z.nombre AS zona_nombre, z.codigo AS zona_codigo
|
||||||
|
FROM alarmas al
|
||||||
|
LEFT JOIN zonas z ON al.zona_id = z.id
|
||||||
|
WHERE al.estado IN ('resuelta', 'silenciada')
|
||||||
|
ORDER BY al.timestamp DESC
|
||||||
|
LIMIT ?
|
||||||
|
''', [limit]);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Incrementa la severidad en 1 (máx 5) y marca para sincronizar.
|
||||||
|
Future<int> escalar(int id) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
final rows = await db.query('alarmas', where: 'id = ?', whereArgs: [id]);
|
||||||
|
if (rows.isEmpty) return 0;
|
||||||
|
final nueva = ((rows.first['severidad'] as int) + 1).clamp(1, 5);
|
||||||
|
return db.update(
|
||||||
|
'alarmas',
|
||||||
|
{'severidad': nueva, 'sincronizado': 0},
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,26 @@ class EventosDao {
|
|||||||
return db.insert('eventos', e.toMap());
|
return db.insert('eventos', e.toMap());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<int> registrar({
|
||||||
|
required String tipo,
|
||||||
|
required String titulo,
|
||||||
|
String? descripcion,
|
||||||
|
}) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
final now = DateTime.now();
|
||||||
|
final hora =
|
||||||
|
'${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
|
||||||
|
return db.insert('eventos', {
|
||||||
|
'tipo': tipo,
|
||||||
|
'titulo': titulo,
|
||||||
|
'descripcion': descripcion,
|
||||||
|
'hora': hora,
|
||||||
|
'timestamp': now.toIso8601String(),
|
||||||
|
'leido': 0,
|
||||||
|
'sincronizado': 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
Future<int> marcarLeido(int id) async {
|
Future<int> marcarLeido(int id) async {
|
||||||
final db = await _db.db;
|
final db = await _db.db;
|
||||||
return db.update(
|
return db.update(
|
||||||
|
|||||||
@@ -56,4 +56,47 @@ class UsuariosDao {
|
|||||||
final rows = await db.query('usuarios', where: 'sincronizado = 0');
|
final rows = await db.query('usuarios', where: 'sincronizado = 0');
|
||||||
return rows.map(Usuario.fromMap).toList();
|
return rows.map(Usuario.fromMap).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<List<Usuario>> getActivos() async {
|
||||||
|
final db = await _db.db;
|
||||||
|
final rows = await db.query(
|
||||||
|
'usuarios',
|
||||||
|
where: 'activo = 1',
|
||||||
|
orderBy: 'nombre ASC',
|
||||||
|
);
|
||||||
|
return rows.map(Usuario.fromMap).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> registrar({
|
||||||
|
required String nombre,
|
||||||
|
required String iniciales,
|
||||||
|
required int nivelAcceso,
|
||||||
|
required String pinHash,
|
||||||
|
String? areas,
|
||||||
|
String? fechaInicio,
|
||||||
|
String? fechaFin,
|
||||||
|
}) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
return db.insert('usuarios', {
|
||||||
|
'nombre': nombre,
|
||||||
|
'iniciales': iniciales,
|
||||||
|
'nivel_acceso': nivelAcceso,
|
||||||
|
'pin_hash': pinHash,
|
||||||
|
'areas': areas,
|
||||||
|
'fecha_inicio': fechaInicio,
|
||||||
|
'fecha_fin': fechaFin,
|
||||||
|
'activo': 1,
|
||||||
|
'sincronizado': 0,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<int> desactivar(int id) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
return db.update(
|
||||||
|
'usuarios',
|
||||||
|
{'activo': 0, 'sincronizado': 0},
|
||||||
|
where: 'id = ?',
|
||||||
|
whereArgs: [id],
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ import 'package:google_fonts/google_fonts.dart';
|
|||||||
import 'package:sqflite/sqflite.dart';
|
import 'package:sqflite/sqflite.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/database_helper.dart';
|
import '../db/database_helper.dart';
|
||||||
|
import '../services/api_auth_service.dart';
|
||||||
|
|
||||||
/// Pantalla de onboarding: el cliente la ve la primera vez que abre la app.
|
/// Pantalla de onboarding: el operador ingresa sus credenciales de WebControl
|
||||||
/// Guarda la URL y usuario del proveedor en `configuracion` y navega al login.
|
/// (api.siax-system.net). La app autentica, recibe apiKey + db_tenant y los
|
||||||
|
/// guarda en SharedPreferences para todas las llamadas a API_CENTINEL_SECURITY.
|
||||||
class ConectarProveedorPage extends StatefulWidget {
|
class ConectarProveedorPage extends StatefulWidget {
|
||||||
const ConectarProveedorPage({Key? key}) : super(key: key);
|
const ConectarProveedorPage({Key? key}) : super(key: key);
|
||||||
|
|
||||||
@@ -18,45 +20,49 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
|||||||
bool _guardando = false;
|
bool _guardando = false;
|
||||||
bool _obscurePass = true;
|
bool _obscurePass = true;
|
||||||
|
|
||||||
final _urlCtrl = TextEditingController();
|
|
||||||
final _usuarioCtrl = TextEditingController();
|
final _usuarioCtrl = TextEditingController();
|
||||||
final _passCtrl = TextEditingController();
|
final _passCtrl = TextEditingController();
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_urlCtrl.dispose();
|
|
||||||
_usuarioCtrl.dispose();
|
_usuarioCtrl.dispose();
|
||||||
_passCtrl.dispose();
|
_passCtrl.dispose();
|
||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
Future<void> _guardarYContinuar() async {
|
Future<void> _guardarYContinuar() async {
|
||||||
final url = _urlCtrl.text.trim();
|
|
||||||
final usuario = _usuarioCtrl.text.trim();
|
final usuario = _usuarioCtrl.text.trim();
|
||||||
|
final pass = _passCtrl.text;
|
||||||
|
|
||||||
if (url.isEmpty || usuario.isEmpty) {
|
if (usuario.isEmpty || pass.isEmpty) {
|
||||||
_snack('Completa la URL y el usuario');
|
_snack('Completa usuario y contraseña');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setState(() => _guardando = true);
|
setState(() => _guardando = true);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
final ok = await ApiAuthService.instance.login(usuario, pass);
|
||||||
|
|
||||||
|
if (!mounted) return;
|
||||||
|
|
||||||
|
if (!ok) {
|
||||||
|
_snack('Credenciales incorrectas o sin conexión');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Guardar usuario en configuracion para referencia local
|
||||||
final db = await DatabaseHelper.instance.db;
|
final db = await DatabaseHelper.instance.db;
|
||||||
await db.insert('configuracion',
|
|
||||||
{'clave': 'api_base_url', 'valor': url},
|
|
||||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
|
||||||
await db.insert('configuracion',
|
await db.insert('configuracion',
|
||||||
{'clave': 'api_usuario', 'valor': usuario},
|
{'clave': 'api_usuario', 'valor': usuario},
|
||||||
conflictAlgorithm: ConflictAlgorithm.replace);
|
conflictAlgorithm: ConflictAlgorithm.replace);
|
||||||
|
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
|
_snack('Conexión establecida', esError: false);
|
||||||
_snack('Configuración guardada', esError: false);
|
|
||||||
Navigator.pop(context);
|
Navigator.pop(context);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
_snack('Error al guardar: $e');
|
_snack('Error: $e');
|
||||||
} finally {
|
} finally {
|
||||||
if (mounted) setState(() => _guardando = false);
|
if (mounted) setState(() => _guardando = false);
|
||||||
}
|
}
|
||||||
@@ -172,8 +178,8 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
|||||||
size: 20, weight: FontWeight.w800, color: AppColors.primary)),
|
size: 20, weight: FontWeight.w800, color: AppColors.primary)),
|
||||||
const SizedBox(height: 12),
|
const SizedBox(height: 12),
|
||||||
Text(
|
Text(
|
||||||
'Para comenzar, conecta tu dispositivo '
|
'Ingresa tus credenciales de Telcotronics WebControl '
|
||||||
'con tu proveedor de servicios de monitoreo.',
|
'para activar el monitoreo en tiempo real.',
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: appLabel(size: 14, color: AppColors.onSurfaceVariant),
|
style: appLabel(size: 14, color: AppColors.onSurfaceVariant),
|
||||||
),
|
),
|
||||||
@@ -184,9 +190,9 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
|||||||
width: double.infinity,
|
width: double.infinity,
|
||||||
child: ElevatedButton.icon(
|
child: ElevatedButton.icon(
|
||||||
onPressed: () => setState(() => _mostrarFormulario = true),
|
onPressed: () => setState(() => _mostrarFormulario = true),
|
||||||
icon: const Icon(Icons.link, size: 20,
|
icon: const Icon(Icons.login, size: 20,
|
||||||
color: AppColors.primaryContainer),
|
color: AppColors.primaryContainer),
|
||||||
label: Text('CONECTAR CON MI PROVEEDOR',
|
label: Text('INICIAR SESIÓN EN WEBCONTROL',
|
||||||
style: GoogleFonts.inter(
|
style: GoogleFonts.inter(
|
||||||
fontSize: 14,
|
fontSize: 14,
|
||||||
fontWeight: FontWeight.bold,
|
fontWeight: FontWeight.bold,
|
||||||
@@ -203,8 +209,8 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Text(
|
Text(
|
||||||
'Solicita los datos de conexión a tu proveedor '
|
'Tus credenciales son las mismas que usas '
|
||||||
'de servicios de monitoreo.',
|
'en el portal Telcotronics WebControl.',
|
||||||
textAlign: TextAlign.center,
|
textAlign: TextAlign.center,
|
||||||
style: appLabel(size: 11, color: AppColors.outlineVariant),
|
style: appLabel(size: 11, color: AppColors.outlineVariant),
|
||||||
),
|
),
|
||||||
@@ -229,25 +235,17 @@ class _ConectarProveedorPageState extends State<ConectarProveedorPage> {
|
|||||||
),
|
),
|
||||||
const SizedBox(height: 20),
|
const SizedBox(height: 20),
|
||||||
|
|
||||||
Text('Datos del proveedor',
|
Text('Credenciales WebControl',
|
||||||
style: appHeadline(size: 17, weight: FontWeight.w700)),
|
style: appHeadline(size: 17, weight: FontWeight.w700)),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text('Ingresa los datos que te entregó tu proveedor de monitoreo.',
|
Text('Las mismas credenciales del portal Telcotronics.',
|
||||||
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
|
|
||||||
_campo(
|
|
||||||
controller: _urlCtrl,
|
|
||||||
label: 'URL del servidor',
|
|
||||||
hint: 'https://monitor.miproveedor.com',
|
|
||||||
icono: Icons.link,
|
|
||||||
tipo: TextInputType.url,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 14),
|
|
||||||
_campo(
|
_campo(
|
||||||
controller: _usuarioCtrl,
|
controller: _usuarioCtrl,
|
||||||
label: 'Usuario / Código de cliente',
|
label: 'Usuario o email',
|
||||||
hint: 'cliente001',
|
hint: 'operador@empresa.com',
|
||||||
icono: Icons.person_outline,
|
icono: Icons.person_outline,
|
||||||
),
|
),
|
||||||
const SizedBox(height: 14),
|
const SizedBox(height: 14),
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
//agregar un boton para registrar usuarios y dale acceso por tiempo y areas
|
|
||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/dao/accesos_dao.dart';
|
import '../db/dao/accesos_dao.dart';
|
||||||
|
import '../db/dao/usuarios_dao.dart';
|
||||||
|
import '../models/usuario.dart';
|
||||||
|
import 'registrar_usuario_page.dart';
|
||||||
|
|
||||||
class ControlAccesoPage extends StatefulWidget {
|
class ControlAccesoPage extends StatefulWidget {
|
||||||
const ControlAccesoPage({Key? key}) : super(key: key);
|
const ControlAccesoPage({Key? key}) : super(key: key);
|
||||||
@@ -17,7 +18,9 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
bool _serverBloqueado = true;
|
bool _serverBloqueado = true;
|
||||||
|
|
||||||
final _dao = AccesosDao();
|
final _dao = AccesosDao();
|
||||||
|
final _usuariosDao = UsuariosDao();
|
||||||
List<Map<String, dynamic>> _accesos = [];
|
List<Map<String, dynamic>> _accesos = [];
|
||||||
|
List<Usuario> _usuarios = [];
|
||||||
bool _cargando = true;
|
bool _cargando = true;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
@@ -29,13 +32,29 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
Future<void> _cargar() async {
|
Future<void> _cargar() async {
|
||||||
setState(() => _cargando = true);
|
setState(() => _cargando = true);
|
||||||
try {
|
try {
|
||||||
final lista = await _dao.getRecientesConDetalle(limit: 20);
|
final results = await Future.wait([
|
||||||
|
_dao.getRecientesConDetalle(limit: 20),
|
||||||
|
_usuariosDao.getActivos(),
|
||||||
|
]);
|
||||||
if (!mounted) return;
|
if (!mounted) return;
|
||||||
setState(() => _accesos = lista);
|
setState(() {
|
||||||
|
_accesos = results[0] as List<Map<String, dynamic>>;
|
||||||
|
_usuarios = results[1] as List<Usuario>;
|
||||||
|
});
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
if (mounted) setState(() => _cargando = false);
|
if (mounted) setState(() => _cargando = false);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void _abrirRegistro() {
|
||||||
|
Navigator.push(
|
||||||
|
context,
|
||||||
|
MaterialPageRoute(
|
||||||
|
fullscreenDialog: true,
|
||||||
|
builder: (_) => const RegistrarUsuarioPage(),
|
||||||
|
),
|
||||||
|
).then((ok) { if (ok == true) _cargar(); });
|
||||||
|
}
|
||||||
|
|
||||||
String _horaCorta(String iso) {
|
String _horaCorta(String iso) {
|
||||||
try {
|
try {
|
||||||
final dt = DateTime.parse(iso).toLocal();
|
final dt = DateTime.parse(iso).toLocal();
|
||||||
@@ -53,13 +72,26 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return RefreshIndicator(
|
return Scaffold(
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
floatingActionButton: FloatingActionButton.extended(
|
||||||
|
onPressed: _abrirRegistro,
|
||||||
|
backgroundColor: AppColors.primary,
|
||||||
|
foregroundColor: AppColors.primaryContainer,
|
||||||
|
icon: const Icon(Icons.person_add_alt_1, size: 20),
|
||||||
|
label: Text('Registrar Usuario',
|
||||||
|
style: appLabel(
|
||||||
|
size: 13,
|
||||||
|
weight: FontWeight.bold,
|
||||||
|
color: AppColors.primaryContainer)),
|
||||||
|
),
|
||||||
|
body: RefreshIndicator(
|
||||||
onRefresh: _cargar,
|
onRefresh: _cargar,
|
||||||
color: AppColors.primary,
|
color: AppColors.primary,
|
||||||
child: SingleChildScrollView(
|
child: SingleChildScrollView(
|
||||||
physics: const AlwaysScrollableScrollPhysics(),
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
primary: false,
|
primary: false,
|
||||||
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
padding: const EdgeInsets.fromLTRB(24, 24, 24, 96),
|
||||||
child: Column(
|
child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
@@ -67,12 +99,15 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
const SizedBox(height: 32),
|
const SizedBox(height: 32),
|
||||||
_gridEntradas(),
|
_gridEntradas(),
|
||||||
const SizedBox(height: 40),
|
const SizedBox(height: 40),
|
||||||
|
_usuariosRegistrados(),
|
||||||
|
const SizedBox(height: 40),
|
||||||
_registroAcceso(),
|
_registroAcceso(),
|
||||||
const SizedBox(height: 24),
|
const SizedBox(height: 24),
|
||||||
_snapshotCamara(),
|
_snapshotCamara(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -291,6 +326,215 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
// ── Usuarios registrados ────────────────────────────────────────────────────
|
||||||
|
Widget _usuariosRegistrados() => Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
children: [
|
||||||
|
Text('Usuarios con Acceso',
|
||||||
|
style: appHeadline(size: 20, weight: FontWeight.bold)),
|
||||||
|
Text('${_usuarios.length} activo${_usuarios.length == 1 ? '' : 's'}',
|
||||||
|
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
const SizedBox(height: 16),
|
||||||
|
if (_cargando)
|
||||||
|
const Center(
|
||||||
|
child: Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 16),
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: AppColors.primary),
|
||||||
|
))
|
||||||
|
else if (_usuarios.isEmpty)
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(20),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.surfaceLow,
|
||||||
|
borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: Column(children: [
|
||||||
|
const Icon(Icons.group_outlined,
|
||||||
|
color: AppColors.outlineVariant, size: 32),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text('Sin usuarios registrados',
|
||||||
|
style: appLabel(
|
||||||
|
size: 13, color: AppColors.outlineVariant)),
|
||||||
|
Text('Usa el botón + para agregar',
|
||||||
|
style:
|
||||||
|
appLabel(size: 11, color: AppColors.outlineVariant)),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
..._usuarios.map((u) => Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 10),
|
||||||
|
child: _cardUsuario(u),
|
||||||
|
)),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
|
static const _nivelLabels = ['', 'Visitante', 'Empleado', 'Supervisor', 'Admin', 'Super Admin'];
|
||||||
|
static const _nivelColors = [
|
||||||
|
Colors.transparent,
|
||||||
|
AppColors.outline,
|
||||||
|
AppColors.secondary,
|
||||||
|
AppColors.primary,
|
||||||
|
AppColors.tertiary,
|
||||||
|
AppColors.error,
|
||||||
|
];
|
||||||
|
|
||||||
|
Widget _cardUsuario(Usuario u) {
|
||||||
|
final nivel = u.nivelAcceso.clamp(1, 5);
|
||||||
|
final nColor = _nivelColors[nivel];
|
||||||
|
final nLabel = _nivelLabels[nivel];
|
||||||
|
final fechaFin = u.fechaFin != null
|
||||||
|
? _formatFecha(u.fechaFin!)
|
||||||
|
: null;
|
||||||
|
final vencido = u.fechaFin != null &&
|
||||||
|
DateTime.tryParse(u.fechaFin!)?.isBefore(DateTime.now()) == true;
|
||||||
|
|
||||||
|
return Container(
|
||||||
|
padding: const EdgeInsets.all(14),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: AppColors.surfaceLow,
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
border: Border.all(
|
||||||
|
color: vencido
|
||||||
|
? AppColors.error.withOpacity(0.3)
|
||||||
|
: AppColors.surfaceHighest,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
child: Row(children: [
|
||||||
|
// Avatar
|
||||||
|
Container(
|
||||||
|
width: 44,
|
||||||
|
height: 44,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: nColor.withOpacity(0.15),
|
||||||
|
borderRadius: BorderRadius.circular(10),
|
||||||
|
border: Border.all(color: nColor.withOpacity(0.3)),
|
||||||
|
),
|
||||||
|
child: Center(
|
||||||
|
child: Text(u.iniciales,
|
||||||
|
style: appHeadline(
|
||||||
|
size: 15, weight: FontWeight.bold, color: nColor)),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
const SizedBox(width: 12),
|
||||||
|
// Info
|
||||||
|
Expanded(
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Row(children: [
|
||||||
|
Expanded(
|
||||||
|
child: Text(u.nombre,
|
||||||
|
style:
|
||||||
|
appHeadline(size: 14, weight: FontWeight.w600)),
|
||||||
|
),
|
||||||
|
// Badge nivel
|
||||||
|
Container(
|
||||||
|
padding:
|
||||||
|
const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: nColor.withOpacity(0.12),
|
||||||
|
borderRadius: BorderRadius.circular(6),
|
||||||
|
),
|
||||||
|
child: Text('N$nivel · $nLabel',
|
||||||
|
style: appLabel(
|
||||||
|
size: 10,
|
||||||
|
weight: FontWeight.bold,
|
||||||
|
color: nColor)),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Row(children: [
|
||||||
|
Icon(Icons.calendar_today,
|
||||||
|
size: 11, color: AppColors.onSurfaceVariant),
|
||||||
|
const SizedBox(width: 4),
|
||||||
|
Text(
|
||||||
|
fechaFin != null
|
||||||
|
? 'Hasta $fechaFin${vencido ? ' · VENCIDO' : ''}'
|
||||||
|
: 'Sin vencimiento',
|
||||||
|
style: appLabel(
|
||||||
|
size: 11,
|
||||||
|
color: vencido
|
||||||
|
? AppColors.error
|
||||||
|
: AppColors.onSurfaceVariant),
|
||||||
|
),
|
||||||
|
if (u.areas != null && u.areas!.isNotEmpty) ...[
|
||||||
|
const SizedBox(width: 10),
|
||||||
|
Icon(Icons.place_outlined,
|
||||||
|
size: 11, color: AppColors.onSurfaceVariant),
|
||||||
|
const SizedBox(width: 3),
|
||||||
|
Expanded(
|
||||||
|
child: Text(
|
||||||
|
u.areas!.replaceAll(',', ', '),
|
||||||
|
style: appLabel(
|
||||||
|
size: 11,
|
||||||
|
color: AppColors.onSurfaceVariant),
|
||||||
|
overflow: TextOverflow.ellipsis,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
]),
|
||||||
|
]),
|
||||||
|
),
|
||||||
|
// Botón desactivar
|
||||||
|
IconButton(
|
||||||
|
icon: const Icon(Icons.person_off_outlined,
|
||||||
|
color: AppColors.outline, size: 18),
|
||||||
|
tooltip: 'Desactivar acceso',
|
||||||
|
onPressed: () => _confirmarDesactivar(u),
|
||||||
|
padding: const EdgeInsets.all(8),
|
||||||
|
constraints: const BoxConstraints(),
|
||||||
|
),
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _formatFecha(String iso) {
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(iso).toLocal();
|
||||||
|
return '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
|
||||||
|
} catch (_) {
|
||||||
|
return '—';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _confirmarDesactivar(Usuario u) async {
|
||||||
|
final ok = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
builder: (_) => AlertDialog(
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
title: Text('Desactivar acceso',
|
||||||
|
style: appHeadline(
|
||||||
|
size: 15, weight: FontWeight.w700, color: AppColors.error)),
|
||||||
|
content: Text(
|
||||||
|
'Se revocará el acceso de "${u.nombre}". Esta acción puede revertirse desde el servidor.',
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, false),
|
||||||
|
child: Text('Cancelar',
|
||||||
|
style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, true),
|
||||||
|
child: Text('DESACTIVAR',
|
||||||
|
style: appLabel(
|
||||||
|
weight: FontWeight.bold, color: AppColors.error)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (ok != true) return;
|
||||||
|
await _usuariosDao.desactivar(u.id);
|
||||||
|
_cargar();
|
||||||
|
}
|
||||||
|
|
||||||
// ── Registro de acceso ──────────────────────────────────────────────────────
|
// ── Registro de acceso ──────────────────────────────────────────────────────
|
||||||
Widget _registroAcceso() => Column(
|
Widget _registroAcceso() => Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
@@ -457,12 +701,12 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
Positioned(
|
Positioned(
|
||||||
left: 40,
|
left: 40,
|
||||||
top: 20,
|
top: 20,
|
||||||
child: _cctv_box(
|
child: _cctvBox(
|
||||||
80, 60, AppColors.primary.withOpacity(0.15))),
|
80, 60, AppColors.primary.withOpacity(0.15))),
|
||||||
Positioned(
|
Positioned(
|
||||||
right: 60,
|
right: 60,
|
||||||
top: 40,
|
top: 40,
|
||||||
child: _cctv_box(
|
child: _cctvBox(
|
||||||
50, 40, AppColors.primary.withOpacity(0.08))),
|
50, 40, AppColors.primary.withOpacity(0.08))),
|
||||||
// Overlay oscuro inferior
|
// Overlay oscuro inferior
|
||||||
Container(
|
Container(
|
||||||
@@ -507,7 +751,7 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
),
|
),
|
||||||
);
|
);
|
||||||
|
|
||||||
Widget _cctv_box(double w, double h, Color color) => Container(
|
Widget _cctvBox(double w, double h, Color color) => Container(
|
||||||
width: w,
|
width: w,
|
||||||
height: h,
|
height: h,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/dao/mensajes_dao.dart';
|
import '../db/dao/mensajes_dao.dart';
|
||||||
|
import '../db/dao/eventos_dao.dart';
|
||||||
import '../models/mensaje.dart';
|
import '../models/mensaje.dart';
|
||||||
import 'llamada_page.dart';
|
import 'llamada_page.dart';
|
||||||
|
|
||||||
@@ -16,6 +17,7 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
final _inputController = TextEditingController();
|
final _inputController = TextEditingController();
|
||||||
final _scrollController = ScrollController();
|
final _scrollController = ScrollController();
|
||||||
final _dao = MensajesDao();
|
final _dao = MensajesDao();
|
||||||
|
final _eventosDao = EventosDao();
|
||||||
|
|
||||||
List<Mensaje> _mensajes = [];
|
List<Mensaje> _mensajes = [];
|
||||||
|
|
||||||
@@ -159,16 +161,7 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
icon: Icons.warning_rounded,
|
icon: Icons.warning_rounded,
|
||||||
label: 'PÁNICO',
|
label: 'PÁNICO',
|
||||||
labelBoton: 'ACTIVAR',
|
labelBoton: 'ACTIVAR',
|
||||||
onTap: () async {
|
onTap: _activarPanico,
|
||||||
final m = Mensaje(
|
|
||||||
texto: 'ALERTA DE PÁNICO ACTIVADA. Requiero asistencia inmediata.',
|
|
||||||
esMio: true,
|
|
||||||
hora: _horaActual(),
|
|
||||||
timestamp: DateTime.now().toIso8601String(),
|
|
||||||
);
|
|
||||||
await _dao.insert(m);
|
|
||||||
await _cargar();
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
const SizedBox(width: 10),
|
const SizedBox(width: 10),
|
||||||
@@ -179,16 +172,7 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
icon: Icons.headset_mic_rounded,
|
icon: Icons.headset_mic_rounded,
|
||||||
label: 'SOPORTE',
|
label: 'SOPORTE',
|
||||||
labelBoton: 'CONTACTAR',
|
labelBoton: 'CONTACTAR',
|
||||||
onTap: () async {
|
onTap: _solicitarSoporte,
|
||||||
final m = Mensaje(
|
|
||||||
texto: 'Hola, necesito asistencia técnica.',
|
|
||||||
esMio: true,
|
|
||||||
hora: _horaActual(),
|
|
||||||
timestamp: DateTime.now().toIso8601String(),
|
|
||||||
);
|
|
||||||
await _dao.insert(m);
|
|
||||||
await _cargar();
|
|
||||||
},
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
]),
|
]),
|
||||||
@@ -236,9 +220,70 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
|
Future<void> _activarPanico() async {
|
||||||
|
final confirmar = await showDialog<bool>(
|
||||||
|
context: context,
|
||||||
|
barrierDismissible: false,
|
||||||
|
builder: (_) => AlertDialog(
|
||||||
|
backgroundColor: AppColors.surfaceHigh,
|
||||||
|
title: Text('Confirmar Alerta de Pánico',
|
||||||
|
style: appHeadline(
|
||||||
|
size: 16, weight: FontWeight.w700, color: AppColors.error)),
|
||||||
|
content: Text(
|
||||||
|
'Se registrará una alerta de pánico de severidad máxima y se notificará a la central cuando el sistema se sincronice.',
|
||||||
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||||
|
),
|
||||||
|
actions: [
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, false),
|
||||||
|
child: Text('Cancelar',
|
||||||
|
style: appLabel(color: AppColors.onSurfaceVariant)),
|
||||||
|
),
|
||||||
|
TextButton(
|
||||||
|
onPressed: () => Navigator.pop(context, true),
|
||||||
|
child: Text('ACTIVAR',
|
||||||
|
style: appLabel(
|
||||||
|
weight: FontWeight.bold, color: AppColors.error)),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
);
|
||||||
|
if (confirmar != true) return;
|
||||||
|
await _eventosDao.registrar(
|
||||||
|
tipo: 'alerta',
|
||||||
|
titulo: 'ALERTA DE PANICO — Severidad maxima',
|
||||||
|
descripcion:
|
||||||
|
'Operador activó alarma de pánico. Requiere atención inmediata de la central.',
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
ScaffoldMessenger.of(context).showSnackBar(
|
||||||
|
SnackBar(
|
||||||
|
backgroundColor: AppColors.error,
|
||||||
|
content: Text('Alerta de pánico registrada',
|
||||||
|
style: appLabel(color: Colors.white, weight: FontWeight.bold)),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _solicitarSoporte() async {
|
||||||
|
await _eventosDao.registrar(
|
||||||
|
tipo: 'notificacion',
|
||||||
|
titulo: 'Solicitud de soporte tecnico',
|
||||||
|
descripcion: 'Operador solicitó asistencia técnica a la central.',
|
||||||
|
);
|
||||||
|
if (!mounted) return;
|
||||||
|
Navigator.push(
|
||||||
|
context,
|
||||||
|
MaterialPageRoute(
|
||||||
|
fullscreenDialog: true,
|
||||||
|
builder: (_) => const LlamadaPage(),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
String _horaActual() {
|
String _horaActual() {
|
||||||
final t = TimeOfDay.now();
|
final now = DateTime.now();
|
||||||
return '${t.hour.toString().padLeft(2, '0')}:${t.minute.toString().padLeft(2, '0')}';
|
return '${now.hour.toString().padLeft(2, '0')}:${now.minute.toString().padLeft(2, '0')}';
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Lista de mensajes ──────────────────────────────────────────────────────
|
// ── Lista de mensajes ──────────────────────────────────────────────────────
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/dao/alarmas_dao.dart';
|
import '../db/dao/alarmas_dao.dart';
|
||||||
|
import 'alarmas_page.dart';
|
||||||
|
|
||||||
class MonitoreoAlarmaPage extends StatefulWidget {
|
class MonitoreoAlarmaPage extends StatefulWidget {
|
||||||
const MonitoreoAlarmaPage({Key? key}) : super(key: key);
|
const MonitoreoAlarmaPage({Key? key}) : super(key: key);
|
||||||
@@ -310,7 +311,11 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
)),
|
)),
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: () {},
|
onPressed: () => Navigator.push(
|
||||||
|
context,
|
||||||
|
MaterialPageRoute(
|
||||||
|
builder: (_) => const AlarmasPage()),
|
||||||
|
).then((_) => _cargar()),
|
||||||
style: ElevatedButton.styleFrom(
|
style: ElevatedButton.styleFrom(
|
||||||
primary: color,
|
primary: color,
|
||||||
onPrimary: Colors.white,
|
onPrimary: Colors.white,
|
||||||
|
|||||||
@@ -2,40 +2,55 @@ import 'dart:convert';
|
|||||||
import 'package:http/http.dart' as http;
|
import 'package:http/http.dart' as http;
|
||||||
import 'package:shared_preferences/shared_preferences.dart';
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
/// Gestiona la autenticación contra la API y el ciclo de vida del token JWT.
|
/// Gestiona la autenticación contra WebControl y las credenciales para Centinel.
|
||||||
/// El token NUNCA se expone a las páginas — solo lo usa [Sincronizador].
|
///
|
||||||
|
/// Flujo:
|
||||||
|
/// login(usuario, password)
|
||||||
|
/// → POST https://api.siax-system.net/api/auth/login
|
||||||
|
/// → recibe { jwt, apiKey, db_tenant }
|
||||||
|
/// → guarda en SharedPreferences
|
||||||
|
///
|
||||||
|
/// Uso posterior (para llamadas a api.telcotronics.com):
|
||||||
|
/// final h = await ApiAuthService.instance.getCentinelHeaders();
|
||||||
|
/// http.get(uri, headers: h)
|
||||||
|
///
|
||||||
|
/// WebControl es el dueño de las API keys.
|
||||||
|
/// Centinel solo las valida — no crea ni gestiona ninguna.
|
||||||
class ApiAuthService {
|
class ApiAuthService {
|
||||||
static const _keyToken = 'api_token';
|
static const _webControlBase = 'https://api.siax-system.net';
|
||||||
static const _keyExpiry = 'api_token_expiry';
|
|
||||||
|
static const _keyJwt = 'webcontrol_jwt';
|
||||||
|
static const _keyApiKey = 'centinel_api_key';
|
||||||
|
static const _keyTenant = 'centinel_tenant';
|
||||||
|
|
||||||
ApiAuthService._();
|
ApiAuthService._();
|
||||||
static final ApiAuthService instance = ApiAuthService._();
|
static final ApiAuthService instance = ApiAuthService._();
|
||||||
|
|
||||||
// ── Login ──────────────────────────────────────────────────────────────────
|
// ── Login ──────────────────────────────────────────────────────────────────
|
||||||
/// Solicita token al servidor.
|
/// Autentica contra WebControl.
|
||||||
/// Devuelve `true` si el login fue exitoso.
|
/// Devuelve `true` si el login fue exitoso y las credenciales quedaron guardadas.
|
||||||
Future<bool> login(String baseUrl, String usuario, String password) async {
|
Future<bool> login(String usuario, String password) async {
|
||||||
try {
|
try {
|
||||||
final resp = await http.post(
|
final resp = await http.post(
|
||||||
Uri.parse('$baseUrl/auth/login'),
|
Uri.parse('$_webControlBase/api/auth/login'),
|
||||||
headers: {'Content-Type': 'application/json'},
|
headers: {'Content-Type': 'application/json'},
|
||||||
body: jsonEncode({'usuario': usuario, 'password': password}),
|
body: jsonEncode({'usuario': usuario, 'password': password}),
|
||||||
).timeout(const Duration(seconds: 10));
|
).timeout(const Duration(seconds: 10));
|
||||||
|
|
||||||
if (resp.statusCode == 200) {
|
if (resp.statusCode != 200) return false;
|
||||||
|
|
||||||
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
final body = jsonDecode(resp.body) as Map<String, dynamic>;
|
||||||
final token = body['token'] as String?;
|
final jwt = body['jwt'] as String?;
|
||||||
final expiryStr = body['expiry'] as String?;
|
final apiKey = body['apiKey'] as String?;
|
||||||
if (token == null) return false;
|
final tenant = body['db_tenant'] as String?;
|
||||||
|
|
||||||
|
if (apiKey == null || tenant == null) return false;
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.setString(_keyToken, token);
|
if (jwt != null) await prefs.setString(_keyJwt, jwt);
|
||||||
if (expiryStr != null) {
|
await prefs.setString(_keyApiKey, apiKey);
|
||||||
await prefs.setString(_keyExpiry, expiryStr);
|
await prefs.setString(_keyTenant, tenant);
|
||||||
}
|
|
||||||
return true;
|
return true;
|
||||||
}
|
|
||||||
return false;
|
|
||||||
} catch (_) {
|
} catch (_) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -44,27 +59,47 @@ class ApiAuthService {
|
|||||||
// ── Logout ─────────────────────────────────────────────────────────────────
|
// ── Logout ─────────────────────────────────────────────────────────────────
|
||||||
Future<void> logout() async {
|
Future<void> logout() async {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
await prefs.remove(_keyToken);
|
await prefs.remove(_keyJwt);
|
||||||
await prefs.remove(_keyExpiry);
|
await prefs.remove(_keyApiKey);
|
||||||
|
await prefs.remove(_keyTenant);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Estado ─────────────────────────────────────────────────────────────────
|
// ── Estado ─────────────────────────────────────────────────────────────────
|
||||||
Future<bool> isAuthenticated() async {
|
Future<bool> isAuthenticated() async {
|
||||||
final token = await getToken();
|
|
||||||
if (token == null || token.isEmpty) return false;
|
|
||||||
|
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
final expiryStr = prefs.getString(_keyExpiry);
|
final apiKey = prefs.getString(_keyApiKey);
|
||||||
if (expiryStr == null) return true; // Sin expiración = válido
|
return apiKey != null && apiKey.isNotEmpty;
|
||||||
|
|
||||||
final expiry = DateTime.tryParse(expiryStr);
|
|
||||||
if (expiry == null) return true;
|
|
||||||
return DateTime.now().isBefore(expiry);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Token ──────────────────────────────────────────────────────────────────
|
// ── Headers para API_CENTINEL_SECURITY ─────────────────────────────────────
|
||||||
|
/// Devuelve los headers necesarios para llamar a api.telcotronics.com.
|
||||||
|
/// Retorna `null` si no hay credenciales guardadas.
|
||||||
|
Future<Map<String, String>?> getCentinelHeaders() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
final apiKey = prefs.getString(_keyApiKey);
|
||||||
|
final tenant = prefs.getString(_keyTenant);
|
||||||
|
if (apiKey == null || apiKey.isEmpty) return null;
|
||||||
|
return {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'x-api-key': apiKey,
|
||||||
|
'x-database': tenant ?? '',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Acceso individual a valores guardados ───────────────────────────────────
|
||||||
|
Future<String?> getApiKey() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
return prefs.getString(_keyApiKey);
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<String?> getTenant() async {
|
||||||
|
final prefs = await SharedPreferences.getInstance();
|
||||||
|
return prefs.getString(_keyTenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// JWT de WebControl — disponible para llamadas a api.siax-system.net si se necesitan.
|
||||||
Future<String?> getToken() async {
|
Future<String?> getToken() async {
|
||||||
final prefs = await SharedPreferences.getInstance();
|
final prefs = await SharedPreferences.getInstance();
|
||||||
return prefs.getString(_keyToken);
|
return prefs.getString(_keyJwt);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -16,9 +16,14 @@ import '../models/zona.dart';
|
|||||||
import '../models/mensaje.dart';
|
import '../models/mensaje.dart';
|
||||||
import '../models/banner_item.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.
|
/// 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 {
|
class Sincronizador {
|
||||||
|
static const _centinelBase = 'https://api.telcotronics.com';
|
||||||
|
|
||||||
Sincronizador._();
|
Sincronizador._();
|
||||||
static final Sincronizador instance = Sincronizador._();
|
static final Sincronizador instance = Sincronizador._();
|
||||||
|
|
||||||
@@ -33,7 +38,7 @@ class Sincronizador {
|
|||||||
await _syncLog.registrar(
|
await _syncLog.registrar(
|
||||||
tipo: 'full',
|
tipo: 'full',
|
||||||
estado: 'error',
|
estado: 'error',
|
||||||
detalle: 'Sin token válido — sincronización omitida',
|
detalle: 'Sin credenciales Centinel — sincronización omitida',
|
||||||
);
|
);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -155,63 +160,79 @@ class Sincronizador {
|
|||||||
detalle: 'banners: ${data.length} registros');
|
detalle: 'banners: ${data.length} registros');
|
||||||
}
|
}
|
||||||
|
|
||||||
// ── Push de pendientes (local → API) ───────────────────────────────────────
|
// ── Push de pendientes (local → API_CENTINEL_SECURITY) ────────────────────
|
||||||
Future<void> pushPendientes() async {
|
Future<void> pushPendientes() async {
|
||||||
await _pushAlarmasPendientes();
|
await _pushAlarmasPendientes();
|
||||||
await _pushAccesosPendientes();
|
await _pushUsuariosPendientes();
|
||||||
await _pushMensajesPendientes();
|
|
||||||
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
||||||
detalle: 'Push de pendientes completado');
|
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 {
|
Future<void> _pushAlarmasPendientes() async {
|
||||||
final pendientes = await AlarmasDao().getPendientes();
|
final pendientes = await AlarmasDao().getPendientes();
|
||||||
if (pendientes.isEmpty) return;
|
if (pendientes.isEmpty) return;
|
||||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
final headers = await _auth.getCentinelHeaders();
|
||||||
final token = await _auth.getToken();
|
if (headers == null) return;
|
||||||
if (baseUrl.isEmpty || token == null) return;
|
|
||||||
for (final a in pendientes) {
|
for (final a in pendientes) {
|
||||||
try {
|
try {
|
||||||
await http.put(
|
final http.Response resp;
|
||||||
Uri.parse('$baseUrl/alarmas/${a.id}'),
|
|
||||||
headers: _headers(token),
|
switch (a.estado) {
|
||||||
body: jsonEncode(a.toMap()),
|
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));
|
).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 (_) {
|
} 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 {
|
/// Sincroniza usuarios nuevos (registrados offline) al dispositivo Centinel.
|
||||||
final pendientes = await AccesosDao().getPendientes();
|
Future<void> _pushUsuariosPendientes() async {
|
||||||
|
final pendientes = await UsuariosDao().getPendientes();
|
||||||
if (pendientes.isEmpty) return;
|
if (pendientes.isEmpty) return;
|
||||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
final headers = await _auth.getCentinelHeaders();
|
||||||
final token = await _auth.getToken();
|
if (headers == null) return;
|
||||||
if (baseUrl.isEmpty || token == null) return;
|
// Requiere deviceId configurado — pendiente cuando se registre el dispositivo
|
||||||
for (final a in pendientes) {
|
final deviceId = await _config.get('centinel_device_id');
|
||||||
try {
|
if (deviceId == null || deviceId.isEmpty) return;
|
||||||
await http.post(
|
|
||||||
Uri.parse('$baseUrl/accesos'),
|
|
||||||
headers: _headers(token),
|
|
||||||
body: jsonEncode(a.toMap()),
|
|
||||||
).timeout(const Duration(seconds: 8));
|
|
||||||
} catch (_) {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Future<void> _pushMensajesPendientes() async {
|
for (final u in pendientes) {
|
||||||
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) {
|
|
||||||
try {
|
try {
|
||||||
await http.post(
|
await http.post(
|
||||||
Uri.parse('$baseUrl/mensajes'),
|
Uri.parse('$_centinelBase/api/devices/$deviceId/employees'),
|
||||||
headers: _headers(token),
|
headers: headers,
|
||||||
body: jsonEncode(m.toMap()),
|
body: jsonEncode({
|
||||||
|
'employeeNo': u.id.toString(),
|
||||||
|
'name': u.nombre,
|
||||||
|
'userType': 'normal',
|
||||||
|
}),
|
||||||
).timeout(const Duration(seconds: 8));
|
).timeout(const Duration(seconds: 8));
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
}
|
}
|
||||||
@@ -219,14 +240,13 @@ class Sincronizador {
|
|||||||
|
|
||||||
// ── Helpers ────────────────────────────────────────────────────────────────
|
// ── Helpers ────────────────────────────────────────────────────────────────
|
||||||
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
|
Future<List<Map<String, dynamic>>?> _get(String endpoint) async {
|
||||||
final baseUrl = await _config.get('api_base_url') ?? '';
|
final headers = await _auth.getCentinelHeaders();
|
||||||
final token = await _auth.getToken();
|
if (headers == null) return null;
|
||||||
if (baseUrl.isEmpty || token == null) return null;
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
final resp = await http.get(
|
final resp = await http.get(
|
||||||
Uri.parse('$baseUrl$endpoint'),
|
Uri.parse('$_centinelBase$endpoint'),
|
||||||
headers: _headers(token),
|
headers: headers,
|
||||||
).timeout(const Duration(seconds: 10));
|
).timeout(const Duration(seconds: 10));
|
||||||
|
|
||||||
if (resp.statusCode == 200) {
|
if (resp.statusCode == 200) {
|
||||||
@@ -238,9 +258,4 @@ class Sincronizador {
|
|||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Map<String, String> _headers(String token) => {
|
|
||||||
'Content-Type': 'application/json',
|
|
||||||
'Authorization': 'Bearer $token',
|
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user