feat: conectar alarmas, mensajes y accesos a BD real
- MonitoreoAlarmaPage: alarmas activas/resueltas desde AlarmasDao, alarma más crítica en tiempo real, log completo con zona y estado, pull-to-refresh, estado vacío - MensajeriaPage: mensajes desde MensajesDao, envío guarda en BD, botones pánico y soporte también persisten en BD, estado vacío - ControlAccesoPage: accesos desde AccesosDao con JOIN a usuarios y puertas, método de acceso, autorizado/denegado, pull-to-refresh, estado vacío - AlarmasDao: contarResueltasUltimas24h, getActivasConZona, getAllConZona - AccesosDao: getRecientesConDetalle (JOIN usuarios + puertas) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
49302dfd23
commit
f566139e0a
@@ -46,4 +46,21 @@ class AccesosDao {
|
|||||||
final rows = await db.query('accesos', where: 'sincronizado = 0');
|
final rows = await db.query('accesos', where: 'sincronizado = 0');
|
||||||
return rows.map(Acceso.fromMap).toList();
|
return rows.map(Acceso.fromMap).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Accesos recientes con nombre e iniciales del usuario y nombre de puerta.
|
||||||
|
Future<List<Map<String, dynamic>>> getRecientesConDetalle({int limit = 20}) async {
|
||||||
|
final db = await _db.db;
|
||||||
|
return db.rawQuery('''
|
||||||
|
SELECT a.id, a.timestamp, a.autorizado, a.metodo,
|
||||||
|
u.nombre AS usuario_nombre,
|
||||||
|
u.iniciales AS usuario_iniciales,
|
||||||
|
p.nombre AS puerta_nombre,
|
||||||
|
p.codigo AS puerta_codigo
|
||||||
|
FROM accesos a
|
||||||
|
LEFT JOIN usuarios u ON a.usuario_id = u.id
|
||||||
|
LEFT JOIN puertas p ON a.puerta_id = p.id
|
||||||
|
ORDER BY a.timestamp DESC
|
||||||
|
LIMIT ?
|
||||||
|
''', [limit]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -91,4 +91,42 @@ class AlarmasDao {
|
|||||||
);
|
);
|
||||||
return result.first['c'] as int;
|
return result.first['c'] as int;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<int> contarResueltasUltimas24h() async {
|
||||||
|
final db = await _db.db;
|
||||||
|
final desde = DateTime.now()
|
||||||
|
.subtract(const Duration(hours: 24))
|
||||||
|
.toIso8601String();
|
||||||
|
final result = await db.rawQuery(
|
||||||
|
"SELECT COUNT(*) as c FROM alarmas WHERE estado = 'resuelta' AND timestamp >= ?",
|
||||||
|
[desde],
|
||||||
|
);
|
||||||
|
return result.first['c'] as int;
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Alarmas activas con nombre de zona, ordenadas por severidad DESC.
|
||||||
|
Future<List<Map<String, dynamic>>> getActivasConZona() 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 = 'activa'
|
||||||
|
ORDER BY al.severidad DESC, al.timestamp DESC
|
||||||
|
''');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Todas las alarmas recientes con nombre de zona.
|
||||||
|
Future<List<Map<String, dynamic>>> getAllConZona({int limit = 20}) 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
|
||||||
|
ORDER BY al.timestamp DESC
|
||||||
|
LIMIT ?
|
||||||
|
''', [limit]);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
|
import '../db/dao/accesos_dao.dart';
|
||||||
|
|
||||||
class ControlAccesoPage extends StatefulWidget {
|
class ControlAccesoPage extends StatefulWidget {
|
||||||
const ControlAccesoPage({Key? key}) : super(key: key);
|
const ControlAccesoPage({Key? key}) : super(key: key);
|
||||||
@@ -15,9 +16,48 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
bool _muelleBloqueado = false;
|
bool _muelleBloqueado = false;
|
||||||
bool _serverBloqueado = true;
|
bool _serverBloqueado = true;
|
||||||
|
|
||||||
|
final _dao = AccesosDao();
|
||||||
|
List<Map<String, dynamic>> _accesos = [];
|
||||||
|
bool _cargando = true;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_cargar();
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _cargar() async {
|
||||||
|
setState(() => _cargando = true);
|
||||||
|
try {
|
||||||
|
final lista = await _dao.getRecientesConDetalle(limit: 20);
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() => _accesos = lista);
|
||||||
|
} catch (_) {}
|
||||||
|
if (mounted) setState(() => _cargando = false);
|
||||||
|
}
|
||||||
|
|
||||||
|
String _horaCorta(String iso) {
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(iso).toLocal();
|
||||||
|
return '${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
|
||||||
|
} catch (_) { return '—'; }
|
||||||
|
}
|
||||||
|
|
||||||
|
String _metodoLabel(String metodo) {
|
||||||
|
switch (metodo) {
|
||||||
|
case 'remoto': return 'Apertura Remota';
|
||||||
|
case 'biometrico':return 'Biométrico';
|
||||||
|
default: return 'PIN';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return SingleChildScrollView(
|
return RefreshIndicator(
|
||||||
|
onRefresh: _cargar,
|
||||||
|
color: AppColors.primary,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
primary: false,
|
primary: false,
|
||||||
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -32,6 +72,7 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
_snapshotCamara(),
|
_snapshotCamara(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -252,58 +293,69 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
|||||||
|
|
||||||
// ── Registro de acceso ──────────────────────────────────────────────────────
|
// ── Registro de acceso ──────────────────────────────────────────────────────
|
||||||
Widget _registroAcceso() => Column(
|
Widget _registroAcceso() => Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
|
|
||||||
Text('Registro de Acceso',
|
Text('Registro de Acceso',
|
||||||
style: appHeadline(size: 20, weight: FontWeight.bold)),
|
style: appHeadline(size: 20, weight: FontWeight.bold)),
|
||||||
GestureDetector(
|
const SizedBox(height: 16),
|
||||||
onTap: () {},
|
if (_cargando)
|
||||||
child: Row(children: [
|
const Center(child: Padding(
|
||||||
const Icon(Icons.filter_list,
|
padding: EdgeInsets.symmetric(vertical: 24),
|
||||||
color: AppColors.primary, size: 20),
|
child: CircularProgressIndicator(
|
||||||
const SizedBox(width: 6),
|
strokeWidth: 2, color: AppColors.primary),
|
||||||
Text('FILTRAR',
|
))
|
||||||
style: appLabel(
|
else if (_accesos.isEmpty)
|
||||||
size: 10,
|
Container(
|
||||||
weight: FontWeight.bold,
|
width: double.infinity,
|
||||||
color: AppColors.primary,
|
padding: const EdgeInsets.all(24),
|
||||||
spacing: 2.0)),
|
decoration: BoxDecoration(color: AppColors.surfaceLow,
|
||||||
|
borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: Column(children: [
|
||||||
|
const Icon(Icons.no_accounts_outlined,
|
||||||
|
color: AppColors.outlineVariant, size: 32),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text('Sin registros de acceso',
|
||||||
|
style: appLabel(size: 13, color: AppColors.outlineVariant)),
|
||||||
|
Text('Carga datos de demo o sincroniza',
|
||||||
|
style: appLabel(size: 11, color: AppColors.outlineVariant)),
|
||||||
]),
|
]),
|
||||||
|
)
|
||||||
|
else
|
||||||
|
..._accesos.asMap().entries.map((e) {
|
||||||
|
final a = e.value;
|
||||||
|
final autorizado = (a['autorizado'] as int) == 1;
|
||||||
|
final nombre = a['usuario_nombre'] as String? ?? 'Usuario';
|
||||||
|
final iniciales = a['usuario_iniciales'] as String? ?? _iniciales(nombre);
|
||||||
|
final puerta = a['puerta_nombre'] as String? ?? '—';
|
||||||
|
final metodo = _metodoLabel(a['metodo'] as String? ?? 'pin');
|
||||||
|
final hora = _horaCorta(a['timestamp'] as String? ?? '');
|
||||||
|
final desc = '$puerta · ${autorizado ? metodo : 'Acceso Denegado'}';
|
||||||
|
return Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 20),
|
||||||
|
child: _entradaLog(
|
||||||
|
iniciales: iniciales,
|
||||||
|
colorAvatar: autorizado ? AppColors.primary : AppColors.error,
|
||||||
|
nombre: nombre,
|
||||||
|
hora: hora,
|
||||||
|
descripcion: desc,
|
||||||
|
descColor: autorizado
|
||||||
|
? AppColors.onSurfaceVariant
|
||||||
|
: AppColors.error,
|
||||||
|
estadoOk: autorizado,
|
||||||
),
|
),
|
||||||
]),
|
);
|
||||||
const SizedBox(height: 24),
|
}).toList(),
|
||||||
_entradaLog(
|
|
||||||
iniciales: 'MV',
|
|
||||||
colorAvatar: AppColors.primary,
|
|
||||||
nombre: 'Marcus Vance',
|
|
||||||
hora: '14:22:04',
|
|
||||||
descripcion: 'Lobby Principal • Entrada Autorizada',
|
|
||||||
descColor: AppColors.onSurfaceVariant,
|
|
||||||
estadoOk: true,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_entradaLog(
|
|
||||||
iniciales: 'ER',
|
|
||||||
colorAvatar: AppColors.tertiary,
|
|
||||||
nombre: 'Elena Rodríguez',
|
|
||||||
hora: '13:45:12',
|
|
||||||
descripcion: 'Centro de Datos • Acceso Denegado (Falla de Auth)',
|
|
||||||
descColor: AppColors.tertiary,
|
|
||||||
estadoOk: false,
|
|
||||||
),
|
|
||||||
const SizedBox(height: 24),
|
|
||||||
_entradaLog(
|
|
||||||
iniciales: 'ST',
|
|
||||||
colorAvatar: AppColors.primary,
|
|
||||||
nombre: 'Equipo de Seguridad (R0)',
|
|
||||||
hora: '12:30:00',
|
|
||||||
descripcion: 'Muelle de Carga • Apertura Remota',
|
|
||||||
descColor: AppColors.onSurfaceVariant,
|
|
||||||
estadoOk: true,
|
|
||||||
),
|
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
String _iniciales(String nombre) {
|
||||||
|
final partes = nombre.trim().split(' ');
|
||||||
|
if (partes.length >= 2) {
|
||||||
|
return '${partes.first[0]}${partes.last[0]}'.toUpperCase();
|
||||||
|
}
|
||||||
|
return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?';
|
||||||
|
}
|
||||||
|
|
||||||
Widget _entradaLog({
|
Widget _entradaLog({
|
||||||
required String iniciales,
|
required String iniciales,
|
||||||
required Color colorAvatar,
|
required Color colorAvatar,
|
||||||
|
|||||||
@@ -1,13 +1,7 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
|
import '../db/dao/mensajes_dao.dart';
|
||||||
// ─── Modelo de mensaje ────────────────────────────────────────────────────────
|
import '../models/mensaje.dart';
|
||||||
class _Mensaje {
|
|
||||||
final String texto;
|
|
||||||
final bool esMio;
|
|
||||||
final String hora;
|
|
||||||
_Mensaje({required this.texto, required this.esMio, required this.hora});
|
|
||||||
}
|
|
||||||
|
|
||||||
// ─── Página ───────────────────────────────────────────────────────────────────
|
// ─── Página ───────────────────────────────────────────────────────────────────
|
||||||
class MensajeriaPage extends StatefulWidget {
|
class MensajeriaPage extends StatefulWidget {
|
||||||
@@ -20,34 +14,22 @@ class MensajeriaPage extends StatefulWidget {
|
|||||||
class _MensajeriaPageState extends State<MensajeriaPage> {
|
class _MensajeriaPageState extends State<MensajeriaPage> {
|
||||||
final _inputController = TextEditingController();
|
final _inputController = TextEditingController();
|
||||||
final _scrollController = ScrollController();
|
final _scrollController = ScrollController();
|
||||||
|
final _dao = MensajesDao();
|
||||||
|
|
||||||
final List<_Mensaje> _mensajes = [
|
List<Mensaje> _mensajes = [];
|
||||||
_Mensaje(
|
|
||||||
texto: 'Sistema armado correctamente. Monitoreo activo en todas las zonas.',
|
@override
|
||||||
esMio: false,
|
void initState() {
|
||||||
hora: '08:00',
|
super.initState();
|
||||||
),
|
_cargar();
|
||||||
_Mensaje(
|
}
|
||||||
texto: 'El sensor Z-03 marcó una alerta hace unos minutos, ¿qué pasó?',
|
|
||||||
esMio: true,
|
Future<void> _cargar() async {
|
||||||
hora: '10:46',
|
final lista = await _dao.getAll();
|
||||||
),
|
if (!mounted) return;
|
||||||
_Mensaje(
|
setState(() => _mensajes = lista);
|
||||||
texto: 'Confirmado. Detectamos movimiento en Almacén G-4. Enviamos una unidad para verificar. Estamos en contacto.',
|
_scrollAlFinal();
|
||||||
esMio: false,
|
}
|
||||||
hora: '10:47',
|
|
||||||
),
|
|
||||||
_Mensaje(
|
|
||||||
texto: 'Entendido. ¿Cuánto tiempo tarda la unidad en llegar?',
|
|
||||||
esMio: true,
|
|
||||||
hora: '10:48',
|
|
||||||
),
|
|
||||||
_Mensaje(
|
|
||||||
texto: 'Aproximadamente 8 minutos. Por favor, no ingrese a la zona hasta recibir confirmación de seguridad.',
|
|
||||||
esMio: false,
|
|
||||||
hora: '10:48',
|
|
||||||
),
|
|
||||||
];
|
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
@@ -56,16 +38,22 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
void _enviarMensaje() {
|
Future<void> _enviarMensaje() async {
|
||||||
final texto = _inputController.text.trim();
|
final texto = _inputController.text.trim();
|
||||||
if (texto.isEmpty) return;
|
if (texto.isEmpty) return;
|
||||||
|
|
||||||
setState(() {
|
final nuevo = Mensaje(
|
||||||
_mensajes.add(_Mensaje(texto: texto, esMio: true, hora: _horaActual()));
|
texto: texto,
|
||||||
|
esMio: true,
|
||||||
|
hora: _horaActual(),
|
||||||
|
timestamp: DateTime.now().toIso8601String(),
|
||||||
|
);
|
||||||
_inputController.clear();
|
_inputController.clear();
|
||||||
});
|
await _dao.insert(nuevo);
|
||||||
|
await _cargar();
|
||||||
|
}
|
||||||
|
|
||||||
// Scroll al final
|
void _scrollAlFinal() {
|
||||||
WidgetsBinding.instance!.addPostFrameCallback((_) {
|
WidgetsBinding.instance!.addPostFrameCallback((_) {
|
||||||
if (_scrollController.hasClients) {
|
if (_scrollController.hasClients) {
|
||||||
_scrollController.animateTo(
|
_scrollController.animateTo(
|
||||||
@@ -237,23 +225,15 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
titulo: 'BOTÓN DE\nPÁNICO',
|
titulo: 'BOTÓN DE\nPÁNICO',
|
||||||
descripcion: 'Activa alerta de emergencia inmediata',
|
descripcion: 'Activa alerta de emergencia inmediata',
|
||||||
labelBoton: 'ACTIVAR',
|
labelBoton: 'ACTIVAR',
|
||||||
onTap: () {
|
onTap: () async {
|
||||||
setState(() {
|
final m = Mensaje(
|
||||||
_mensajes.add(_Mensaje(
|
texto: 'ALERTA DE PÁNICO ACTIVADA. Requiero asistencia inmediata.',
|
||||||
texto: '🚨 ALERTA DE PÁNICO ACTIVADA. Requiero asistencia inmediata.',
|
|
||||||
esMio: true,
|
esMio: true,
|
||||||
hora: _horaActual(),
|
hora: _horaActual(),
|
||||||
));
|
timestamp: DateTime.now().toIso8601String(),
|
||||||
});
|
|
||||||
WidgetsBinding.instance!.addPostFrameCallback((_) {
|
|
||||||
if (_scrollController.hasClients) {
|
|
||||||
_scrollController.animateTo(
|
|
||||||
_scrollController.position.maxScrollExtent,
|
|
||||||
duration: const Duration(milliseconds: 300),
|
|
||||||
curve: Curves.easeOut,
|
|
||||||
);
|
);
|
||||||
}
|
await _dao.insert(m);
|
||||||
});
|
await _cargar();
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -267,23 +247,15 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
titulo: 'SOPORTE Y\nASISTENCIA',
|
titulo: 'SOPORTE Y\nASISTENCIA',
|
||||||
descripcion: 'Comunícate con nuestro equipo 24/7',
|
descripcion: 'Comunícate con nuestro equipo 24/7',
|
||||||
labelBoton: 'CONTACTAR',
|
labelBoton: 'CONTACTAR',
|
||||||
onTap: () {
|
onTap: () async {
|
||||||
setState(() {
|
final m = Mensaje(
|
||||||
_mensajes.add(_Mensaje(
|
|
||||||
texto: 'Hola, necesito asistencia técnica.',
|
texto: 'Hola, necesito asistencia técnica.',
|
||||||
esMio: true,
|
esMio: true,
|
||||||
hora: _horaActual(),
|
hora: _horaActual(),
|
||||||
));
|
timestamp: DateTime.now().toIso8601String(),
|
||||||
});
|
|
||||||
WidgetsBinding.instance!.addPostFrameCallback((_) {
|
|
||||||
if (_scrollController.hasClients) {
|
|
||||||
_scrollController.animateTo(
|
|
||||||
_scrollController.position.maxScrollExtent,
|
|
||||||
duration: const Duration(milliseconds: 300),
|
|
||||||
curve: Curves.easeOut,
|
|
||||||
);
|
);
|
||||||
}
|
await _dao.insert(m);
|
||||||
});
|
await _cargar();
|
||||||
},
|
},
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
@@ -360,14 +332,27 @@ class _MensajeriaPageState extends State<MensajeriaPage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// ── Lista de mensajes ──────────────────────────────────────────────────────
|
// ── Lista de mensajes ──────────────────────────────────────────────────────
|
||||||
Widget _listaMensajes() => ListView.builder(
|
Widget _listaMensajes() => _mensajes.isEmpty
|
||||||
|
? Center(
|
||||||
|
child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||||
|
const Icon(Icons.chat_bubble_outline,
|
||||||
|
color: AppColors.outlineVariant, size: 40),
|
||||||
|
const SizedBox(height: 12),
|
||||||
|
Text('Sin mensajes',
|
||||||
|
style: appLabel(size: 13, color: AppColors.outlineVariant)),
|
||||||
|
Text('Carga datos de demo para ver mensajes de ejemplo',
|
||||||
|
style: appLabel(size: 11, color: AppColors.outlineVariant),
|
||||||
|
textAlign: TextAlign.center),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
: ListView.builder(
|
||||||
controller: _scrollController,
|
controller: _scrollController,
|
||||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||||
itemCount: _mensajes.length,
|
itemCount: _mensajes.length,
|
||||||
itemBuilder: (_, i) => _burbuja(_mensajes[i]),
|
itemBuilder: (_, i) => _burbuja(_mensajes[i]),
|
||||||
);
|
);
|
||||||
|
|
||||||
Widget _burbuja(_Mensaje msg) {
|
Widget _burbuja(Mensaje msg) {
|
||||||
final esMio = msg.esMio;
|
final esMio = msg.esMio;
|
||||||
return Padding(
|
return Padding(
|
||||||
padding: const EdgeInsets.only(bottom: 8),
|
padding: const EdgeInsets.only(bottom: 8),
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
|
import '../db/dao/alarmas_dao.dart';
|
||||||
|
|
||||||
class MonitoreoAlarmaPage extends StatefulWidget {
|
class MonitoreoAlarmaPage extends StatefulWidget {
|
||||||
const MonitoreoAlarmaPage({Key? key}) : super(key: key);
|
const MonitoreoAlarmaPage({Key? key}) : super(key: key);
|
||||||
@@ -18,9 +19,17 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
late final Animation<double> _pingScale;
|
late final Animation<double> _pingScale;
|
||||||
late final Animation<double> _pingOpacity;
|
late final Animation<double> _pingOpacity;
|
||||||
|
|
||||||
|
final _dao = AlarmasDao();
|
||||||
|
int _contActivas = 0;
|
||||||
|
int _contResueltas24h = 0;
|
||||||
|
List<Map<String, dynamic>> _activas = [];
|
||||||
|
List<Map<String, dynamic>> _log = [];
|
||||||
|
bool _cargando = true;
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
|
_cargar();
|
||||||
|
|
||||||
_pulseCtrl = AnimationController(vsync: this,
|
_pulseCtrl = AnimationController(vsync: this,
|
||||||
duration: const Duration(seconds: 2))..repeat();
|
duration: const Duration(seconds: 2))..repeat();
|
||||||
@@ -41,6 +50,24 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
.animate(CurvedAnimation(parent: _pingCtrl, curve: Curves.easeOut));
|
.animate(CurvedAnimation(parent: _pingCtrl, curve: Curves.easeOut));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<void> _cargar() async {
|
||||||
|
setState(() => _cargando = true);
|
||||||
|
try {
|
||||||
|
final activas = await _dao.getActivasConZona();
|
||||||
|
final log = await _dao.getAllConZona(limit: 20);
|
||||||
|
final contActivas = await _dao.contarActivas();
|
||||||
|
final contResueltas = await _dao.contarResueltasUltimas24h();
|
||||||
|
if (!mounted) return;
|
||||||
|
setState(() {
|
||||||
|
_activas = activas;
|
||||||
|
_log = log;
|
||||||
|
_contActivas = contActivas;
|
||||||
|
_contResueltas24h = contResueltas;
|
||||||
|
});
|
||||||
|
} catch (_) {}
|
||||||
|
if (mounted) setState(() => _cargando = false);
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
void dispose() {
|
void dispose() {
|
||||||
_pulseCtrl.dispose();
|
_pulseCtrl.dispose();
|
||||||
@@ -48,9 +75,68 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
super.dispose();
|
super.dispose();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Helpers ─────────────────────────────────────────────────────────────────
|
||||||
|
String _tipoLabel(String tipo) {
|
||||||
|
switch (tipo) {
|
||||||
|
case 'intrusion': return 'INTRUSIÓN';
|
||||||
|
case 'humo': return 'HUMO';
|
||||||
|
case 'movimiento':return 'MOVIMIENTO';
|
||||||
|
case 'acceso': return 'ACCESO';
|
||||||
|
default: return tipo.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _severidadColor(int sev) {
|
||||||
|
if (sev >= 5) return AppColors.error;
|
||||||
|
if (sev >= 4) return AppColors.tertiary;
|
||||||
|
if (sev >= 3) return AppColors.secondary;
|
||||||
|
return AppColors.onSurfaceVariant;
|
||||||
|
}
|
||||||
|
|
||||||
|
IconData _tipoIcon(String tipo) {
|
||||||
|
switch (tipo) {
|
||||||
|
case 'intrusion': return Icons.warning_amber;
|
||||||
|
case 'humo': return Icons.local_fire_department;
|
||||||
|
case 'movimiento':return Icons.directions_run;
|
||||||
|
case 'acceso': return Icons.lock_open;
|
||||||
|
default: return Icons.notifications;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String _horaCorta(String iso) {
|
||||||
|
try {
|
||||||
|
final dt = DateTime.parse(iso).toLocal();
|
||||||
|
final h = dt.hour.toString().padLeft(2, '0');
|
||||||
|
final m = dt.minute.toString().padLeft(2, '0');
|
||||||
|
return '$h:$m';
|
||||||
|
} catch (_) { return ''; }
|
||||||
|
}
|
||||||
|
|
||||||
|
String _badgeEstado(String estado) {
|
||||||
|
switch (estado) {
|
||||||
|
case 'activa': return 'ACTIVA';
|
||||||
|
case 'resuelta': return 'RESUELTO';
|
||||||
|
case 'silenciada':return 'SILENCIADA';
|
||||||
|
default: return estado.toUpperCase();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Color _badgeColor(String estado) {
|
||||||
|
switch (estado) {
|
||||||
|
case 'activa': return AppColors.error;
|
||||||
|
case 'resuelta': return AppColors.primary;
|
||||||
|
case 'silenciada':return AppColors.onSurfaceVariant;
|
||||||
|
default: return AppColors.onSurfaceVariant;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@override
|
@override
|
||||||
Widget build(BuildContext context) {
|
Widget build(BuildContext context) {
|
||||||
return SingleChildScrollView(
|
return RefreshIndicator(
|
||||||
|
onRefresh: _cargar,
|
||||||
|
color: AppColors.primary,
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
physics: const AlwaysScrollableScrollPhysics(),
|
||||||
primary: false,
|
primary: false,
|
||||||
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
||||||
child: Column(
|
child: Column(
|
||||||
@@ -65,6 +151,7 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
_tacticalView(),
|
_tacticalView(),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
|
),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -74,10 +161,14 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
Row(children: [
|
Row(children: [
|
||||||
Expanded(child: _miniStatCard(
|
Expanded(child: _miniStatCard(
|
||||||
'ALARMAS ACTIVAS', '03', Icons.warning, AppColors.error)),
|
'ALARMAS ACTIVAS',
|
||||||
|
_cargando ? '—' : '$_contActivas',
|
||||||
|
Icons.warning, AppColors.error)),
|
||||||
const SizedBox(width: 16),
|
const SizedBox(width: 16),
|
||||||
Expanded(child: _miniStatCard(
|
Expanded(child: _miniStatCard(
|
||||||
'RESUELTAS 24H', '142', Icons.check_circle, AppColors.primary)),
|
'RESUELTAS 24H',
|
||||||
|
_cargando ? '—' : '$_contResueltas24h',
|
||||||
|
Icons.check_circle, AppColors.primary)),
|
||||||
]),
|
]),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
@@ -147,23 +238,46 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
]),
|
]),
|
||||||
);
|
);
|
||||||
|
|
||||||
// ── Gráfico de frecuencia ───────────────────────────────────────────────────
|
// ── Alarma más crítica ───────────────────────────────────────────────────────
|
||||||
// ── Eventos críticos ────────────────────────────────────────────────────────
|
Widget _criticalEvents() {
|
||||||
Widget _criticalEvents() => Column(
|
final alarma = _activas.isNotEmpty ? _activas.first : null;
|
||||||
|
final color = alarma != null
|
||||||
|
? _severidadColor(alarma['severidad'] as int)
|
||||||
|
: AppColors.onSurfaceVariant;
|
||||||
|
|
||||||
|
return Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Row(children: [
|
Row(children: [
|
||||||
const Icon(Icons.priority_high, color: AppColors.error, size: 16),
|
Icon(Icons.priority_high, color: color, size: 16),
|
||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Text('EVENTOS CRÍTICOS',
|
Text('ALARMA MÁS CRÍTICA',
|
||||||
style: appHeadline(size: 13, color: AppColors.error, spacing: 1.5)),
|
style: appHeadline(size: 13, color: color, spacing: 1.5)),
|
||||||
]),
|
]),
|
||||||
const SizedBox(height: 16),
|
const SizedBox(height: 16),
|
||||||
|
if (alarma == null)
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
decoration: BoxDecoration(color: AppColors.surfaceHigh,
|
||||||
|
borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: Column(children: [
|
||||||
|
Icon(Icons.shield_outlined, color: AppColors.primary, size: 32),
|
||||||
|
const SizedBox(height: 10),
|
||||||
|
Text('Sin alarmas activas',
|
||||||
|
style: appHeadline(size: 14, color: AppColors.primary)),
|
||||||
|
const SizedBox(height: 4),
|
||||||
|
Text('Todos los sectores en estado normal',
|
||||||
|
style: appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
||||||
|
]),
|
||||||
|
)
|
||||||
|
else
|
||||||
ClipRRect(
|
ClipRRect(
|
||||||
borderRadius: BorderRadius.circular(12),
|
borderRadius: BorderRadius.circular(12),
|
||||||
child: IntrinsicHeight(
|
child: IntrinsicHeight(
|
||||||
child: Row(crossAxisAlignment: CrossAxisAlignment.stretch, children: [
|
child: Row(crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||||
Container(width: 6, color: AppColors.error),
|
children: [
|
||||||
|
Container(width: 6, color: color),
|
||||||
Expanded(
|
Expanded(
|
||||||
child: Container(
|
child: Container(
|
||||||
color: AppColors.surfaceHigh,
|
color: AppColors.surfaceHigh,
|
||||||
@@ -174,18 +288,23 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
Expanded(child: Column(
|
Expanded(child: Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Text('INTRUSIÓN NIVEL 5',
|
Text(
|
||||||
|
'${_tipoLabel(alarma['tipo'] as String)} · NIVEL ${alarma['severidad']}',
|
||||||
style: appLabel(size: 10, weight: FontWeight.bold,
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||||
color: AppColors.error, spacing: 1.5)),
|
color: color, spacing: 1.5),
|
||||||
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text('ALMACÉN PRINCIPAL G-4',
|
Text(
|
||||||
style: appHeadline(size: 18)),
|
(alarma['zona_nombre'] as String? ?? 'Zona desconocida').toUpperCase(),
|
||||||
|
style: appHeadline(size: 18),
|
||||||
|
),
|
||||||
const SizedBox(height: 8),
|
const SizedBox(height: 8),
|
||||||
Row(children: [
|
Row(children: [
|
||||||
const Icon(Icons.schedule, size: 14,
|
const Icon(Icons.schedule, size: 14,
|
||||||
color: AppColors.onSurfaceVariant),
|
color: AppColors.onSurfaceVariant),
|
||||||
const SizedBox(width: 6),
|
const SizedBox(width: 6),
|
||||||
Text('02:14:45', style: appLabel(size: 12)),
|
Text(_horaCorta(alarma['timestamp'] as String),
|
||||||
|
style: appLabel(size: 12)),
|
||||||
]),
|
]),
|
||||||
],
|
],
|
||||||
)),
|
)),
|
||||||
@@ -193,8 +312,8 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
ElevatedButton(
|
ElevatedButton(
|
||||||
onPressed: () {},
|
onPressed: () {},
|
||||||
style: ElevatedButton.styleFrom(
|
style: ElevatedButton.styleFrom(
|
||||||
primary: AppColors.error,
|
primary: color,
|
||||||
onPrimary: AppColors.onError,
|
onPrimary: Colors.white,
|
||||||
padding: const EdgeInsets.symmetric(
|
padding: const EdgeInsets.symmetric(
|
||||||
horizontal: 16, vertical: 10),
|
horizontal: 16, vertical: 10),
|
||||||
shape: RoundedRectangleBorder(
|
shape: RoundedRectangleBorder(
|
||||||
@@ -203,7 +322,7 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
),
|
),
|
||||||
child: Text('RESPONDER',
|
child: Text('RESPONDER',
|
||||||
style: appLabel(size: 12, weight: FontWeight.bold,
|
style: appLabel(size: 12, weight: FontWeight.bold,
|
||||||
color: AppColors.onError)),
|
color: Colors.white)),
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -214,54 +333,83 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
),
|
),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Registro de eventos ─────────────────────────────────────────────────────
|
// ── Registro de alarmas ─────────────────────────────────────────────────────
|
||||||
Widget _eventLog() => Column(
|
Widget _eventLog() => Column(
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
children: [
|
children: [
|
||||||
Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
|
Text('REGISTRO DE ALARMAS',
|
||||||
Text('REGISTRO DE EVENTOS',
|
|
||||||
style: appHeadline(size: 13, spacing: 1.5)),
|
style: appHeadline(size: 13, spacing: 1.5)),
|
||||||
Text('Ver Historial',
|
const SizedBox(height: 16),
|
||||||
style: appLabel(size: 12, weight: FontWeight.bold,
|
if (_cargando)
|
||||||
color: AppColors.primary)),
|
const Center(child: Padding(
|
||||||
|
padding: EdgeInsets.symmetric(vertical: 24),
|
||||||
|
child: CircularProgressIndicator(
|
||||||
|
strokeWidth: 2, color: AppColors.primary),
|
||||||
|
))
|
||||||
|
else if (_log.isEmpty)
|
||||||
|
Container(
|
||||||
|
width: double.infinity,
|
||||||
|
padding: const EdgeInsets.all(24),
|
||||||
|
decoration: BoxDecoration(color: AppColors.surfaceLow,
|
||||||
|
borderRadius: BorderRadius.circular(12)),
|
||||||
|
child: Column(children: [
|
||||||
|
const Icon(Icons.history, color: AppColors.outlineVariant, size: 28),
|
||||||
|
const SizedBox(height: 8),
|
||||||
|
Text('Sin registros',
|
||||||
|
style: appLabel(size: 13, color: AppColors.outlineVariant)),
|
||||||
|
Text('Carga datos de demo o sincroniza',
|
||||||
|
style: appLabel(size: 11, color: AppColors.outlineVariant)),
|
||||||
]),
|
]),
|
||||||
const SizedBox(height: 24),
|
)
|
||||||
_logEntry(icon: Icons.lock_open, iconBg: AppColors.surfaceHighest,
|
else
|
||||||
iconColor: AppColors.secondary,
|
..._log.asMap().entries.map((e) {
|
||||||
title: 'Acceso Autorizado', badge: 'SEGURO',
|
final i = e.key;
|
||||||
badgeTextColor: AppColors.onSurfaceVariant, badgeBg: AppColors.surfaceLow,
|
final a = e.value;
|
||||||
description: 'Entrada: Muelle Trasero - Usuario: #0824',
|
final color = _severidadColor(a['severidad'] as int);
|
||||||
time: '10:45:12', showLine: true),
|
final estado = a['estado'] as String;
|
||||||
_logEntry(icon: Icons.local_fire_department,
|
final badge = _badgeEstado(estado);
|
||||||
iconBg: AppColors.tertiaryContainer, iconColor: AppColors.tertiary,
|
final badgeC = _badgeColor(estado);
|
||||||
title: 'Humo Detectado', badge: 'URGENTE',
|
return _logEntry(
|
||||||
badgeTextColor: AppColors.tertiary, badgeBg: AppColors.tertiaryContainer,
|
icon: _tipoIcon(a['tipo'] as String),
|
||||||
description: 'Sensor #402 - Sala de Servidores A',
|
iconColor: color,
|
||||||
time: '09:12:05', showLine: true),
|
iconBg: color.withOpacity(0.12),
|
||||||
_logEntry(icon: Icons.videocam, iconBg: AppColors.surfaceHighest,
|
title: _tipoLabel(a['tipo'] as String),
|
||||||
iconColor: AppColors.primary,
|
badge: badge,
|
||||||
title: 'Detección de Movimiento', badge: 'RESUELTO',
|
badgeColor: badgeC,
|
||||||
badgeTextColor: AppColors.onSurfaceVariant, badgeBg: AppColors.surfaceLow,
|
zona: a['zona_nombre'] as String? ?? '—',
|
||||||
description: 'Cámara 12 - Cerca Perimetral Sur',
|
time: _horaCorta(a['timestamp'] as String),
|
||||||
time: '08:55:30', showLine: false),
|
showLine: i < _log.length - 1,
|
||||||
|
);
|
||||||
|
}).toList(),
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
Widget _logEntry({
|
Widget _logEntry({
|
||||||
required IconData icon, required Color iconBg, required Color iconColor,
|
required IconData icon,
|
||||||
required String title, required String badge, required Color badgeTextColor,
|
required Color iconBg,
|
||||||
required Color badgeBg, required String description, required String time,
|
required Color iconColor,
|
||||||
|
required String title,
|
||||||
|
required String badge,
|
||||||
|
required Color badgeColor,
|
||||||
|
required String zona,
|
||||||
|
required String time,
|
||||||
required bool showLine,
|
required bool showLine,
|
||||||
}) =>
|
}) =>
|
||||||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
Column(children: [
|
Column(children: [
|
||||||
Container(width: 32, height: 32,
|
Container(
|
||||||
|
width: 32, height: 32,
|
||||||
decoration: BoxDecoration(color: iconBg, shape: BoxShape.circle),
|
decoration: BoxDecoration(color: iconBg, shape: BoxShape.circle),
|
||||||
child: Icon(icon, size: 16, color: iconColor)),
|
child: Icon(icon, size: 16, color: iconColor),
|
||||||
|
),
|
||||||
if (showLine)
|
if (showLine)
|
||||||
Container(width: 1, height: 64, margin: const EdgeInsets.only(top: 4),
|
Container(
|
||||||
color: AppColors.outlineVariant.withOpacity(0.3)),
|
width: 1, height: 56,
|
||||||
|
margin: const EdgeInsets.only(top: 4),
|
||||||
|
color: AppColors.outlineVariant.withOpacity(0.3),
|
||||||
|
),
|
||||||
]),
|
]),
|
||||||
const SizedBox(width: 16),
|
const SizedBox(width: 16),
|
||||||
Expanded(child: Padding(
|
Expanded(child: Padding(
|
||||||
@@ -272,14 +420,16 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
|||||||
const SizedBox(width: 8),
|
const SizedBox(width: 8),
|
||||||
Container(
|
Container(
|
||||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
|
||||||
decoration: BoxDecoration(color: badgeBg,
|
decoration: BoxDecoration(
|
||||||
borderRadius: BorderRadius.circular(4)),
|
color: badgeColor.withOpacity(0.12),
|
||||||
|
borderRadius: BorderRadius.circular(4),
|
||||||
|
),
|
||||||
child: Text(badge, style: appLabel(size: 10,
|
child: Text(badge, style: appLabel(size: 10,
|
||||||
weight: FontWeight.bold, color: badgeTextColor)),
|
weight: FontWeight.bold, color: badgeColor)),
|
||||||
),
|
),
|
||||||
]),
|
]),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(description, style: appLabel(size: 12)),
|
Text(zona, style: appLabel(size: 12)),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(time, style: appLabel(size: 10, color: AppColors.outline)),
|
Text(time, style: appLabel(size: 10, color: AppColors.outline)),
|
||||||
]),
|
]),
|
||||||
|
|||||||
Reference in New Issue
Block a user