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
@@ -37,6 +37,13 @@ class NodosDao {
|
|||||||
return db.delete('nodos', where: 'id = ?', whereArgs: [id]);
|
return db.delete('nodos', where: 'id = ?', whereArgs: [id]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Future<int> contarActivos() async {
|
||||||
|
final db = await _db.db;
|
||||||
|
final result = await db.rawQuery(
|
||||||
|
'SELECT COUNT(*) as total FROM nodos WHERE activo = 1');
|
||||||
|
return result.first['total'] as int? ?? 0;
|
||||||
|
}
|
||||||
|
|
||||||
Future<List<Nodo>> getPendientes() async {
|
Future<List<Nodo>> getPendientes() async {
|
||||||
final db = await _db.db;
|
final db = await _db.db;
|
||||||
final rows = await db.query('nodos', where: 'sincronizado = 0');
|
final rows = await db.query('nodos', where: 'sincronizado = 0');
|
||||||
|
|||||||
+4
-2
@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';
|
|||||||
import 'theme.dart';
|
import 'theme.dart';
|
||||||
import 'pages/control_acceso_page.dart';
|
import 'pages/control_acceso_page.dart';
|
||||||
import 'pages/monitoreo_alarma_page.dart';
|
import 'pages/monitoreo_alarma_page.dart';
|
||||||
import 'pages/inicio_page.dart';
|
import 'pages/inicio_page.dart' show InicioPage, InicioPageState;
|
||||||
import 'pages/perfil_usuario_page.dart';
|
import 'pages/perfil_usuario_page.dart';
|
||||||
import 'widgets/app_menu_button.dart';
|
import 'widgets/app_menu_button.dart';
|
||||||
|
|
||||||
@@ -17,9 +17,10 @@ class MainPage extends StatefulWidget {
|
|||||||
class _MainPageState extends State<MainPage> {
|
class _MainPageState extends State<MainPage> {
|
||||||
late final PageController _pageController;
|
late final PageController _pageController;
|
||||||
int _navSelected = 0;
|
int _navSelected = 0;
|
||||||
|
final _inicioKey = GlobalKey<InicioPageState>();
|
||||||
|
|
||||||
List<Widget> get _pages => [
|
List<Widget> get _pages => [
|
||||||
InicioPage(onGoToPerfil: () => _onNavTap(3)),
|
InicioPage(key: _inicioKey, onGoToPerfil: () => _onNavTap(3)),
|
||||||
const ControlAccesoPage(),
|
const ControlAccesoPage(),
|
||||||
const MonitoreoAlarmaPage(),
|
const MonitoreoAlarmaPage(),
|
||||||
const PerfilUsuarioPage(),
|
const PerfilUsuarioPage(),
|
||||||
@@ -39,6 +40,7 @@ class _MainPageState extends State<MainPage> {
|
|||||||
}
|
}
|
||||||
|
|
||||||
void _onNavTap(int idx) {
|
void _onNavTap(int idx) {
|
||||||
|
if (idx == 0) _inicioKey.currentState?.recargar();
|
||||||
_pageController.animateToPage(
|
_pageController.animateToPage(
|
||||||
idx,
|
idx,
|
||||||
duration: const Duration(milliseconds: 300),
|
duration: const Duration(milliseconds: 300),
|
||||||
|
|||||||
+157
-42
@@ -2,6 +2,10 @@ import 'dart:async';
|
|||||||
import 'package:flutter/material.dart';
|
import 'package:flutter/material.dart';
|
||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/dao/usuarios_dao.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';
|
import 'mensageria_page.dart';
|
||||||
|
|
||||||
// ─── Datos del banner ─────────────────────────────────────────────────────────
|
// ─── Datos del banner ─────────────────────────────────────────────────────────
|
||||||
@@ -111,16 +115,28 @@ class InicioPage extends StatefulWidget {
|
|||||||
const InicioPage({Key? key, this.onGoToPerfil}) : super(key: key);
|
const InicioPage({Key? key, this.onGoToPerfil}) : super(key: key);
|
||||||
|
|
||||||
@override
|
@override
|
||||||
State<InicioPage> createState() => _InicioPageState();
|
State<InicioPage> createState() => InicioPageState();
|
||||||
}
|
}
|
||||||
|
|
||||||
class _InicioPageState extends State<InicioPage>
|
class InicioPageState extends State<InicioPage>
|
||||||
with SingleTickerProviderStateMixin {
|
with SingleTickerProviderStateMixin {
|
||||||
int _bannerPage = 0;
|
int _bannerPage = 0;
|
||||||
final _pageController = PageController();
|
final _pageController = PageController();
|
||||||
Timer? _bannerTimer;
|
Timer? _bannerTimer;
|
||||||
|
|
||||||
String _nombreUsuario = 'Usuario';
|
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 {
|
Future<void> _cargarUsuario() async {
|
||||||
try {
|
try {
|
||||||
@@ -131,6 +147,63 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
} catch (_) {}
|
} 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 AnimationController _panicCtrl;
|
||||||
late final Animation<double> _pingScale;
|
late final Animation<double> _pingScale;
|
||||||
late final Animation<double> _pingOpacity;
|
late final Animation<double> _pingOpacity;
|
||||||
@@ -139,6 +212,8 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
void initState() {
|
void initState() {
|
||||||
super.initState();
|
super.initState();
|
||||||
_cargarUsuario();
|
_cargarUsuario();
|
||||||
|
_cargarMetricas();
|
||||||
|
_cargarEventos();
|
||||||
// Auto-avance del banner cada 4 segundos
|
// Auto-avance del banner cada 4 segundos
|
||||||
_bannerTimer = Timer.periodic(const Duration(seconds: 4), (_) {
|
_bannerTimer = Timer.periodic(const Duration(seconds: 4), (_) {
|
||||||
final next = (_bannerPage + 1) % _banners.length;
|
final next = (_bannerPage + 1) % _banners.length;
|
||||||
@@ -498,11 +573,11 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
Widget _quickMetrics() => Row(children: [
|
Widget _quickMetrics() => Row(children: [
|
||||||
Expanded(
|
Expanded(
|
||||||
child: _metricCard(
|
child: _metricCard(
|
||||||
icon: Icons.lock_rounded,
|
icon: _estadoIcon,
|
||||||
iconColor: AppColors.primary,
|
iconColor: _estadoColor,
|
||||||
label: 'Estado Sistema',
|
label: 'Estado Suscripción',
|
||||||
value: 'PROTEGIDO',
|
value: _estadoSuscripcion,
|
||||||
valueColor: AppColors.primary,
|
valueColor: _estadoColor,
|
||||||
)),
|
)),
|
||||||
const SizedBox(width: 12),
|
const SizedBox(width: 12),
|
||||||
Expanded(
|
Expanded(
|
||||||
@@ -510,7 +585,7 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
icon: Icons.sensors,
|
icon: Icons.sensors,
|
||||||
iconColor: AppColors.tertiary,
|
iconColor: AppColors.tertiary,
|
||||||
label: 'Nodos Activos',
|
label: 'Nodos Activos',
|
||||||
value: '12',
|
value: _nodosActivos.toString(),
|
||||||
valueSuffix: ' ONLINE',
|
valueSuffix: ' ONLINE',
|
||||||
valueColor: AppColors.onSurface,
|
valueColor: AppColors.onSurface,
|
||||||
suffixColor: AppColors.outline,
|
suffixColor: AppColors.outline,
|
||||||
@@ -580,32 +655,70 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
);
|
);
|
||||||
|
|
||||||
// ── Log de eventos ─────────────────────────────────────────────────────────
|
// ── Log de eventos ─────────────────────────────────────────────────────────
|
||||||
Widget _eventLog() => Column(
|
// Mapeo tipo → icono/colores
|
||||||
crossAxisAlignment: CrossAxisAlignment.start,
|
IconData _iconoPorTipo(String tipo) {
|
||||||
children: [
|
switch (tipo) {
|
||||||
Row(
|
case 'alerta': return Icons.home_work_outlined;
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
case 'noticia': return Icons.campaign_outlined;
|
||||||
children: [
|
case 'notificacion': return Icons.notifications_active_outlined;
|
||||||
Text('LOG DE EVENTOS Y NOTIFICACIONES',
|
default: return Icons.history;
|
||||||
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,
|
|
||||||
)),
|
|
||||||
],
|
|
||||||
);
|
|
||||||
|
|
||||||
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: [
|
Row(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||||
// Ícono + línea vertical
|
// Ícono + línea vertical
|
||||||
Column(children: [
|
Column(children: [
|
||||||
@@ -613,10 +726,11 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
width: 48,
|
width: 48,
|
||||||
height: 48,
|
height: 48,
|
||||||
decoration: BoxDecoration(
|
decoration: BoxDecoration(
|
||||||
color: data.iconBg,
|
color: _bgPorTipo(evento.tipo),
|
||||||
shape: BoxShape.circle,
|
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)
|
if (showLine)
|
||||||
Container(
|
Container(
|
||||||
@@ -637,13 +751,13 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
Row(
|
Row(
|
||||||
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
children: [
|
children: [
|
||||||
Text(data.tipo.toUpperCase(),
|
Text(evento.tipo.toUpperCase(),
|
||||||
style: appLabel(
|
style: appLabel(
|
||||||
size: 10,
|
size: 10,
|
||||||
weight: FontWeight.bold,
|
weight: FontWeight.bold,
|
||||||
color: data.tipoColor,
|
color: _colorPorTipo(evento.tipo),
|
||||||
spacing: 1.5)),
|
spacing: 1.5)),
|
||||||
Text(data.hora,
|
Text(evento.hora,
|
||||||
style: appLabel(
|
style: appLabel(
|
||||||
size: 10,
|
size: 10,
|
||||||
weight: FontWeight.w500,
|
weight: FontWeight.w500,
|
||||||
@@ -651,11 +765,12 @@ class _InicioPageState extends State<InicioPage>
|
|||||||
],
|
],
|
||||||
),
|
),
|
||||||
const SizedBox(height: 4),
|
const SizedBox(height: 4),
|
||||||
Text(data.titulo, style: appHeadline(size: 14)),
|
Text(evento.titulo, style: appHeadline(size: 14)),
|
||||||
const SizedBox(height: 2),
|
const SizedBox(height: 2),
|
||||||
Text(data.descripcion,
|
if (evento.descripcion != null)
|
||||||
style:
|
Text(evento.descripcion!,
|
||||||
appLabel(size: 12, color: AppColors.onSurfaceVariant)),
|
style: appLabel(
|
||||||
|
size: 12, color: AppColors.onSurfaceVariant)),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import 'package:path/path.dart' as p;
|
|||||||
import '../theme.dart';
|
import '../theme.dart';
|
||||||
import '../db/database_helper.dart';
|
import '../db/database_helper.dart';
|
||||||
import '../services/sincronizador.dart';
|
import '../services/sincronizador.dart';
|
||||||
|
import '../services/demo_data_service.dart';
|
||||||
|
|
||||||
class SettingsPage extends StatefulWidget {
|
class SettingsPage extends StatefulWidget {
|
||||||
const SettingsPage({Key? key}) : super(key: key);
|
const SettingsPage({Key? key}) : super(key: key);
|
||||||
@@ -21,6 +22,7 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
|
|
||||||
bool _iniciandoBd = false;
|
bool _iniciandoBd = false;
|
||||||
bool _sincronizando = false;
|
bool _sincronizando = false;
|
||||||
|
bool _cargandoDemo = false;
|
||||||
|
|
||||||
// ── Build ──────────────────────────────────────────────────────────────────
|
// ── Build ──────────────────────────────────────────────────────────────────
|
||||||
@override
|
@override
|
||||||
@@ -87,6 +89,15 @@ class _SettingsPageState extends State<SettingsPage> {
|
|||||||
cargando: _sincronizando,
|
cargando: _sincronizando,
|
||||||
onTap: _iniciarSincronizacion,
|
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),
|
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 ──────────────────────────────────────────────────────────
|
// ── Helpers de UI ──────────────────────────────────────────────────────────
|
||||||
void _snack(String msg, {bool esError = true}) {
|
void _snack(String msg, {bool esError = true}) {
|
||||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||||
|
|||||||
@@ -0,0 +1,219 @@
|
|||||||
|
import '../db/database_helper.dart';
|
||||||
|
|
||||||
|
/// Inserta datos de demostración en todas las tablas operacionales.
|
||||||
|
/// No toca: usuarios, zonas, nodos, puertas, clientes, suscripciones, configuracion.
|
||||||
|
/// Borra los datos existentes de las tablas operacionales antes de insertar.
|
||||||
|
class DemoDataService {
|
||||||
|
DemoDataService._();
|
||||||
|
static final DemoDataService instance = DemoDataService._();
|
||||||
|
|
||||||
|
Future<void> cargarDatos() async {
|
||||||
|
final db = await DatabaseHelper.instance.db;
|
||||||
|
final ahora = DateTime.now();
|
||||||
|
|
||||||
|
// ── Limpiar datos anteriores ──────────────────────────────────────────────
|
||||||
|
await db.delete('eventos');
|
||||||
|
await db.delete('mensajes');
|
||||||
|
await db.delete('alarmas');
|
||||||
|
await db.delete('accesos');
|
||||||
|
await db.delete('sesiones');
|
||||||
|
|
||||||
|
// ── Eventos ───────────────────────────────────────────────────────────────
|
||||||
|
final eventos = [
|
||||||
|
{
|
||||||
|
'tipo': 'alerta',
|
||||||
|
'titulo': 'Apertura No Autorizada',
|
||||||
|
'descripcion': 'Zona A-3: sensor de puerta perimetral activado sin credencial válida.',
|
||||||
|
'hora': _hora(ahora, -30),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 30)).toIso8601String(),
|
||||||
|
'leido': 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'tipo': 'alerta',
|
||||||
|
'titulo': 'Movimiento Detectado',
|
||||||
|
'descripcion': 'Zona G-4: sensor de movimiento activado fuera de horario.',
|
||||||
|
'hora': _hora(ahora, -55),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 55)).toIso8601String(),
|
||||||
|
'leido': 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'tipo': 'noticia',
|
||||||
|
'titulo': 'Mantenimiento Programado',
|
||||||
|
'descripcion': 'Actualización de firmware para sensores de movimiento el 24/05.',
|
||||||
|
'hora': _hora(ahora, -120),
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||||
|
'leido': 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'tipo': 'notificacion',
|
||||||
|
'titulo': 'Sistema Armado',
|
||||||
|
'descripcion': 'Activación exitosa por operador en turno nocturno.',
|
||||||
|
'hora': _hora(ahora, -180),
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||||
|
'leido': 1,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'tipo': 'notificacion',
|
||||||
|
'titulo': 'Suscripción por Vencer',
|
||||||
|
'descripcion': 'El plan de Pedro García — Negocio Centro vence en 5 días.',
|
||||||
|
'hora': _hora(ahora, -240),
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 4)).toIso8601String(),
|
||||||
|
'leido': 0,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'tipo': 'general',
|
||||||
|
'titulo': 'Cierre Periódico',
|
||||||
|
'descripcion': 'Revisión de integridad del sistema completada sin errores.',
|
||||||
|
'hora': 'AYER',
|
||||||
|
'timestamp': ahora.subtract(const Duration(days: 1)).toIso8601String(),
|
||||||
|
'leido': 1,
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (final e in eventos) {
|
||||||
|
await db.insert('eventos', {...e, 'sincronizado': 1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Mensajes del chat ─────────────────────────────────────────────────────
|
||||||
|
final mensajes = [
|
||||||
|
{
|
||||||
|
'texto': 'Central de monitoreo en línea. ¿En qué podemos ayudarle?',
|
||||||
|
'es_mio': 0,
|
||||||
|
'hora': _horaHHMM(ahora, -45),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 45)).toIso8601String(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'texto': 'Todo en orden por el momento. Revisando sector norte.',
|
||||||
|
'es_mio': 1,
|
||||||
|
'hora': _horaHHMM(ahora, -43),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 43)).toIso8601String(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'texto': 'Recibido. Se detectó movimiento en zona G-4, ¿confirma?',
|
||||||
|
'es_mio': 0,
|
||||||
|
'hora': _horaHHMM(ahora, -37),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 37)).toIso8601String(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'texto': 'Afirmativo. Voy a verificar en persona.',
|
||||||
|
'es_mio': 1,
|
||||||
|
'hora': _horaHHMM(ahora, -36),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 36)).toIso8601String(),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'texto': 'Entendido. Enviamos unidad de respaldo. ETA: 8 minutos.',
|
||||||
|
'es_mio': 0,
|
||||||
|
'hora': _horaHHMM(ahora, -35),
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 35)).toIso8601String(),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (final m in mensajes) {
|
||||||
|
await db.insert('mensajes', {...m, 'sincronizado': 1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Alarmas ───────────────────────────────────────────────────────────────
|
||||||
|
final alarmas = [
|
||||||
|
{
|
||||||
|
'zona_id': 4, 'tipo': 'intrusion', 'severidad': 5,
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 30)).toIso8601String(),
|
||||||
|
'estado': 'activa', 'resuelto_por': null, 'notas': null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'zona_id': 4, 'tipo': 'movimiento', 'severidad': 3,
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 55)).toIso8601String(),
|
||||||
|
'estado': 'activa', 'resuelto_por': null, 'notas': null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'zona_id': 6, 'tipo': 'humo', 'severidad': 3,
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||||
|
'estado': 'resuelta', 'resuelto_por': 1, 'notas': 'Sensor calibrado',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'zona_id': 5, 'tipo': 'movimiento', 'severidad': 2,
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 4)).toIso8601String(),
|
||||||
|
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'zona_id': 2, 'tipo': 'acceso', 'severidad': 1,
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 5)).toIso8601String(),
|
||||||
|
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'zona_id': 1, 'tipo': 'intrusion', 'severidad': 4,
|
||||||
|
'timestamp': ahora.subtract(const Duration(days: 1)).toIso8601String(),
|
||||||
|
'estado': 'resuelta', 'resuelto_por': 1, 'notas': 'Falsa alarma — personal autorizado',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (final a in alarmas) {
|
||||||
|
await db.insert('alarmas', {...a, 'sincronizado': 1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Accesos ───────────────────────────────────────────────────────────────
|
||||||
|
final accesos = [
|
||||||
|
{
|
||||||
|
'usuario_id': 1, 'puerta_id': 2,
|
||||||
|
'timestamp': ahora.subtract(const Duration(minutes: 95)).toIso8601String(),
|
||||||
|
'autorizado': 1, 'metodo': 'remoto',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'usuario_id': 1, 'puerta_id': 1,
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 2, minutes: 30)).toIso8601String(),
|
||||||
|
'autorizado': 0, 'metodo': 'pin',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'usuario_id': 1, 'puerta_id': 3,
|
||||||
|
'timestamp': ahora.subtract(const Duration(hours: 4)).toIso8601String(),
|
||||||
|
'autorizado': 1, 'metodo': 'pin',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'usuario_id': 1, 'puerta_id': 1,
|
||||||
|
'timestamp': ahora.subtract(const Duration(days: 1, hours: 1)).toIso8601String(),
|
||||||
|
'autorizado': 1, 'metodo': 'remoto',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (final a in accesos) {
|
||||||
|
await db.insert('accesos', {...a, 'sincronizado': 1});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Sesiones de ejemplo ───────────────────────────────────────────────────
|
||||||
|
final sesiones = [
|
||||||
|
{
|
||||||
|
'usuario_id': 1,
|
||||||
|
'timestamp_inicio': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||||
|
'timestamp_fin': null,
|
||||||
|
'dispositivo': 'Linux Desktop',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'usuario_id': 1,
|
||||||
|
'timestamp_inicio': ahora.subtract(const Duration(days: 1, hours: 3)).toIso8601String(),
|
||||||
|
'timestamp_fin': ahora.subtract(const Duration(days: 1)).toIso8601String(),
|
||||||
|
'dispositivo': 'Android',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'usuario_id': 1,
|
||||||
|
'timestamp_inicio': ahora.subtract(const Duration(days: 2, hours: 1)).toIso8601String(),
|
||||||
|
'timestamp_fin': ahora.subtract(const Duration(days: 2)).toIso8601String(),
|
||||||
|
'dispositivo': 'Android',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
for (final s in sesiones) {
|
||||||
|
await db.insert('sesiones', s);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Helpers de formato de hora ────────────────────────────────────────────
|
||||||
|
String _hora(DateTime base, int minutosAtras) {
|
||||||
|
final dt = base.subtract(Duration(minutes: -minutosAtras)).toLocal();
|
||||||
|
final h = dt.hour;
|
||||||
|
final m = dt.minute.toString().padLeft(2, '0');
|
||||||
|
final periodo = h >= 12 ? 'PM' : 'AM';
|
||||||
|
final h12 = h > 12 ? h - 12 : (h == 0 ? 12 : h);
|
||||||
|
return '$h12:$m $periodo';
|
||||||
|
}
|
||||||
|
|
||||||
|
String _horaHHMM(DateTime base, int minutosAtras) {
|
||||||
|
final dt = base.subtract(Duration(minutes: -minutosAtras)).toLocal();
|
||||||
|
final h = dt.hour.toString().padLeft(2, '0');
|
||||||
|
final m = dt.minute.toString().padLeft(2, '0');
|
||||||
|
return '$h:$m';
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user