feat: eventos BD en inicio, DemoDataService y recarga al cambiar tab
- InicioPage conectada a BD: eventos reales, métricas suscripción y nodos - Eventos del log cargan desde EventosDao (getRecientes limit 6) - Métricas: estado suscripción (PROTEGIDO/POR VENCER/SUSPENDIDO/VENCIDO) - NodosDao: nuevo método contarActivos() - InicioPageState pública + método recargar() vía GlobalKey - MainPage: llama recargar() al volver al tab INICIO - DemoDataService: singleton que carga eventos, alarmas, mensajes, accesos y sesiones de prueba - Settings: botón "Datos de demostración" con diálogo de confirmación Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
4d3d298773
commit
80442a1269
+157
-42
@@ -2,6 +2,10 @@ import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/usuarios_dao.dart';
|
||||
import '../db/dao/nodos_dao.dart';
|
||||
import '../db/dao/suscripciones_dao.dart';
|
||||
import '../db/dao/eventos_dao.dart';
|
||||
import '../models/evento.dart';
|
||||
import 'mensageria_page.dart';
|
||||
|
||||
// ─── Datos del banner ─────────────────────────────────────────────────────────
|
||||
@@ -111,16 +115,28 @@ class InicioPage extends StatefulWidget {
|
||||
const InicioPage({Key? key, this.onGoToPerfil}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<InicioPage> createState() => _InicioPageState();
|
||||
State<InicioPage> createState() => InicioPageState();
|
||||
}
|
||||
|
||||
class _InicioPageState extends State<InicioPage>
|
||||
class InicioPageState extends State<InicioPage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
int _bannerPage = 0;
|
||||
final _pageController = PageController();
|
||||
Timer? _bannerTimer;
|
||||
|
||||
String _nombreUsuario = 'Usuario';
|
||||
int _nodosActivos = 0;
|
||||
List<Evento> _eventosDb = [];
|
||||
String _estadoSuscripcion = 'CARGANDO';
|
||||
Color _estadoColor = AppColors.outline;
|
||||
IconData _estadoIcon = Icons.lock_rounded;
|
||||
|
||||
/// Llamado desde MainPage al volver al tab INICIO
|
||||
void recargar() {
|
||||
_cargarUsuario();
|
||||
_cargarMetricas();
|
||||
_cargarEventos();
|
||||
}
|
||||
|
||||
Future<void> _cargarUsuario() async {
|
||||
try {
|
||||
@@ -131,6 +147,63 @@ class _InicioPageState extends State<InicioPage>
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> _cargarEventos() async {
|
||||
try {
|
||||
final data = await EventosDao().getRecientes(limit: 6);
|
||||
if (mounted) setState(() => _eventosDb = data);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
Future<void> _cargarMetricas() async {
|
||||
try {
|
||||
final nodos = await NodosDao().contarActivos();
|
||||
final suscripciones = await SuscripcionesDao().getAll();
|
||||
|
||||
String estado;
|
||||
Color color;
|
||||
IconData icon;
|
||||
|
||||
if (suscripciones.isEmpty) {
|
||||
estado = 'SIN PLAN';
|
||||
color = AppColors.outline;
|
||||
icon = Icons.lock_outline;
|
||||
} else if (suscripciones.any((s) => s.activa)) {
|
||||
final proximasAVencer = suscripciones.where((s) =>
|
||||
s.activa &&
|
||||
DateTime.tryParse(s.fechaVencimiento) != null &&
|
||||
DateTime.parse(s.fechaVencimiento)
|
||||
.difference(DateTime.now())
|
||||
.inDays <= 7).isNotEmpty;
|
||||
if (proximasAVencer) {
|
||||
estado = 'POR VENCER';
|
||||
color = AppColors.tertiary;
|
||||
icon = Icons.lock_clock;
|
||||
} else {
|
||||
estado = 'PROTEGIDO';
|
||||
color = AppColors.primary;
|
||||
icon = Icons.lock_rounded;
|
||||
}
|
||||
} else if (suscripciones.any((s) => s.estado == 'suspendida')) {
|
||||
estado = 'SUSPENDIDO';
|
||||
color = AppColors.tertiary;
|
||||
icon = Icons.lock_outlined;
|
||||
} else {
|
||||
estado = 'VENCIDO';
|
||||
color = AppColors.error;
|
||||
icon = Icons.lock_open;
|
||||
}
|
||||
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_nodosActivos = nodos;
|
||||
_estadoSuscripcion = estado;
|
||||
_estadoColor = color;
|
||||
_estadoIcon = icon;
|
||||
});
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
late final AnimationController _panicCtrl;
|
||||
late final Animation<double> _pingScale;
|
||||
late final Animation<double> _pingOpacity;
|
||||
@@ -139,6 +212,8 @@ class _InicioPageState extends State<InicioPage>
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarUsuario();
|
||||
_cargarMetricas();
|
||||
_cargarEventos();
|
||||
// Auto-avance del banner cada 4 segundos
|
||||
_bannerTimer = Timer.periodic(const Duration(seconds: 4), (_) {
|
||||
final next = (_bannerPage + 1) % _banners.length;
|
||||
@@ -498,11 +573,11 @@ class _InicioPageState extends State<InicioPage>
|
||||
Widget _quickMetrics() => Row(children: [
|
||||
Expanded(
|
||||
child: _metricCard(
|
||||
icon: Icons.lock_rounded,
|
||||
iconColor: AppColors.primary,
|
||||
label: 'Estado Sistema',
|
||||
value: 'PROTEGIDO',
|
||||
valueColor: AppColors.primary,
|
||||
icon: _estadoIcon,
|
||||
iconColor: _estadoColor,
|
||||
label: 'Estado Suscripción',
|
||||
value: _estadoSuscripcion,
|
||||
valueColor: _estadoColor,
|
||||
)),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
@@ -510,7 +585,7 @@ class _InicioPageState extends State<InicioPage>
|
||||
icon: Icons.sensors,
|
||||
iconColor: AppColors.tertiary,
|
||||
label: 'Nodos Activos',
|
||||
value: '12',
|
||||
value: _nodosActivos.toString(),
|
||||
valueSuffix: ' ONLINE',
|
||||
valueColor: AppColors.onSurface,
|
||||
suffixColor: AppColors.outline,
|
||||
@@ -580,32 +655,70 @@ class _InicioPageState extends State<InicioPage>
|
||||
);
|
||||
|
||||
// ── Log de eventos ─────────────────────────────────────────────────────────
|
||||
Widget _eventLog() => Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('LOG DE EVENTOS Y NOTIFICACIONES',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: AppColors.primary.withOpacity(0.8),
|
||||
spacing: 1.5)),
|
||||
const Icon(Icons.filter_list, color: AppColors.outline, size: 20),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
...List.generate(
|
||||
_eventos.length,
|
||||
(i) => _eventItem(
|
||||
data: _eventos[i],
|
||||
showLine: i < _eventos.length - 1,
|
||||
)),
|
||||
],
|
||||
);
|
||||
// Mapeo tipo → icono/colores
|
||||
IconData _iconoPorTipo(String tipo) {
|
||||
switch (tipo) {
|
||||
case 'alerta': return Icons.home_work_outlined;
|
||||
case 'noticia': return Icons.campaign_outlined;
|
||||
case 'notificacion': return Icons.notifications_active_outlined;
|
||||
default: return Icons.history;
|
||||
}
|
||||
}
|
||||
|
||||
Widget _eventItem({required _EventData data, required bool showLine}) =>
|
||||
Color _colorPorTipo(String tipo) {
|
||||
switch (tipo) {
|
||||
case 'alerta': return AppColors.error;
|
||||
case 'noticia': return AppColors.onSecondaryContainer;
|
||||
case 'notificacion': return AppColors.primary;
|
||||
default: return AppColors.outline;
|
||||
}
|
||||
}
|
||||
|
||||
Color _bgPorTipo(String tipo) {
|
||||
switch (tipo) {
|
||||
case 'alerta': return const Color(0xFF93000A);
|
||||
case 'noticia': return AppColors.secondaryContainer;
|
||||
case 'notificacion': return AppColors.primaryContainer;
|
||||
default: return AppColors.surfaceHighest;
|
||||
}
|
||||
}
|
||||
|
||||
Widget _eventLog() {
|
||||
final lista = _eventosDb.isNotEmpty ? _eventosDb : <Evento>[];
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text('LOG DE EVENTOS Y NOTIFICACIONES',
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: AppColors.primary.withOpacity(0.8),
|
||||
spacing: 1.5)),
|
||||
const Icon(Icons.filter_list, color: AppColors.outline, size: 20),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
if (lista.isEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 24),
|
||||
child: Center(
|
||||
child: Text('Sin eventos registrados',
|
||||
style: appLabel(size: 13, color: AppColors.outline)),
|
||||
),
|
||||
)
|
||||
else
|
||||
...List.generate(lista.length, (i) => _eventItem(
|
||||
evento: lista[i],
|
||||
showLine: i < lista.length - 1,
|
||||
)),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _eventItem({required Evento evento, required bool showLine}) =>
|
||||
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
// Ícono + línea vertical
|
||||
Column(children: [
|
||||
@@ -613,10 +726,11 @@ class _InicioPageState extends State<InicioPage>
|
||||
width: 48,
|
||||
height: 48,
|
||||
decoration: BoxDecoration(
|
||||
color: data.iconBg,
|
||||
color: _bgPorTipo(evento.tipo),
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
child: Icon(data.icon, color: data.iconColor, size: 22),
|
||||
child: Icon(_iconoPorTipo(evento.tipo),
|
||||
color: _colorPorTipo(evento.tipo), size: 22),
|
||||
),
|
||||
if (showLine)
|
||||
Container(
|
||||
@@ -637,13 +751,13 @@ class _InicioPageState extends State<InicioPage>
|
||||
Row(
|
||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||
children: [
|
||||
Text(data.tipo.toUpperCase(),
|
||||
Text(evento.tipo.toUpperCase(),
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.bold,
|
||||
color: data.tipoColor,
|
||||
color: _colorPorTipo(evento.tipo),
|
||||
spacing: 1.5)),
|
||||
Text(data.hora,
|
||||
Text(evento.hora,
|
||||
style: appLabel(
|
||||
size: 10,
|
||||
weight: FontWeight.w500,
|
||||
@@ -651,11 +765,12 @@ class _InicioPageState extends State<InicioPage>
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(data.titulo, style: appHeadline(size: 14)),
|
||||
Text(evento.titulo, style: appHeadline(size: 14)),
|
||||
const SizedBox(height: 2),
|
||||
Text(data.descripcion,
|
||||
style:
|
||||
appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
||||
if (evento.descripcion != null)
|
||||
Text(evento.descripcion!,
|
||||
style: appLabel(
|
||||
size: 12, color: AppColors.onSurfaceVariant)),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
@@ -6,6 +6,7 @@ import 'package:path/path.dart' as p;
|
||||
import '../theme.dart';
|
||||
import '../db/database_helper.dart';
|
||||
import '../services/sincronizador.dart';
|
||||
import '../services/demo_data_service.dart';
|
||||
|
||||
class SettingsPage extends StatefulWidget {
|
||||
const SettingsPage({Key? key}) : super(key: key);
|
||||
@@ -21,6 +22,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
|
||||
bool _iniciandoBd = false;
|
||||
bool _sincronizando = false;
|
||||
bool _cargandoDemo = false;
|
||||
|
||||
// ── Build ──────────────────────────────────────────────────────────────────
|
||||
@override
|
||||
@@ -87,6 +89,15 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
cargando: _sincronizando,
|
||||
onTap: _iniciarSincronizacion,
|
||||
),
|
||||
_divider(),
|
||||
_accionItem(
|
||||
icon: Icons.science_outlined,
|
||||
iconColor: AppColors.tertiary,
|
||||
titulo: 'Datos de demostración',
|
||||
subtitulo: 'Carga eventos, alarmas, mensajes y accesos de prueba',
|
||||
cargando: _cargandoDemo,
|
||||
onTap: _cargarDemostracion,
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
@@ -236,6 +247,52 @@ class _SettingsPageState extends State<SettingsPage> {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Datos de demostración ──────────────────────────────────────────────────
|
||||
Future<void> _cargarDemostracion() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Datos de demostración',
|
||||
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
||||
content: Text(
|
||||
'Se reemplazarán los eventos, alarmas, mensajes, accesos y sesiones '
|
||||
'actuales con datos de prueba.\n\nLos usuarios, zonas, clientes y '
|
||||
'suscripciones no se modifican.',
|
||||
style: appLabel(size: 13),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar',
|
||||
style: appLabel(size: 13,
|
||||
color: AppColors.onSurfaceVariant)),
|
||||
),
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
child: Text('Cargar',
|
||||
style: appLabel(size: 13,
|
||||
weight: FontWeight.bold, color: AppColors.tertiary)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmar != true) return;
|
||||
setState(() => _cargandoDemo = true);
|
||||
|
||||
try {
|
||||
await DemoDataService.instance.cargarDatos();
|
||||
if (!mounted) return;
|
||||
_snack('Datos de demostración cargados', esError: false);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
_snack('Error al cargar datos: $e');
|
||||
} finally {
|
||||
if (mounted) setState(() => _cargandoDemo = false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers de UI ──────────────────────────────────────────────────────────
|
||||
void _snack(String msg, {bool esError = true}) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
|
||||
Reference in New Issue
Block a user