447 lines
17 KiB
Dart
447 lines
17 KiB
Dart
import 'dart:io';
|
|
import 'package:flutter/foundation.dart';
|
|
import 'package:path/path.dart';
|
|
// Comentario explicativo: sqflite_common_ffi provee la interfaz Database y funciones FFI para Linux/móvil
|
|
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
|
|
|
class DatabaseHelper {
|
|
static const _dbName = 'central_monitoreo.db';
|
|
static const _dbVersion = 1;
|
|
|
|
DatabaseHelper._();
|
|
static final DatabaseHelper instance = DatabaseHelper._();
|
|
|
|
Database? _db;
|
|
|
|
Future<Database> get db async {
|
|
_db ??= await _initDb();
|
|
return _db!;
|
|
}
|
|
|
|
Future<Database> _initDb() async {
|
|
if (!kIsWeb && (Platform.isLinux || Platform.isWindows)) {
|
|
sqfliteFfiInit();
|
|
databaseFactory = databaseFactoryFfi;
|
|
}
|
|
|
|
final path = await _dbPath();
|
|
final database = await openDatabase(path, version: _dbVersion, onCreate: _onCreate);
|
|
|
|
// Comentario explicativo: Migración progresiva para garantizar la columna 'tipo_servicio' en cache_clientes si la base de datos ya existía en disco
|
|
try {
|
|
await database.execute("ALTER TABLE cache_clientes ADD COLUMN tipo_servicio TEXT DEFAULT 'Monitoreo de Alarmas'");
|
|
} catch (_) {
|
|
// Ignorar si la columna ya existe en la tabla
|
|
}
|
|
|
|
return database;
|
|
}
|
|
|
|
Future<String> _dbPath() async {
|
|
if (!kIsWeb && Platform.isLinux) {
|
|
final home = Platform.environment['HOME'] ?? '';
|
|
final dir = Directory('$home/.local/share/central_monitoreo');
|
|
if (!dir.existsSync()) dir.createSync(recursive: true);
|
|
return join(dir.path, _dbName);
|
|
}
|
|
final base = await getDatabasesPath();
|
|
return join(base, _dbName);
|
|
}
|
|
|
|
Future<void> _onCreate(Database db, int version) async {
|
|
await db.execute('''
|
|
CREATE TABLE configuracion (
|
|
clave TEXT PRIMARY KEY,
|
|
valor TEXT
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE sesiones_operador (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
nombre TEXT NOT NULL,
|
|
usuario TEXT NOT NULL,
|
|
inicio TEXT NOT NULL,
|
|
fin TEXT,
|
|
activa INTEGER NOT NULL DEFAULT 1
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE cache_clientes (
|
|
id INTEGER PRIMARY KEY,
|
|
nombre TEXT NOT NULL,
|
|
estado TEXT NOT NULL DEFAULT 'normal',
|
|
alarmas_activas INTEGER NOT NULL DEFAULT 0,
|
|
alarmas_criticas INTEGER NOT NULL DEFAULT 0,
|
|
tipo_servicio TEXT NOT NULL DEFAULT 'Monitoreo de Alarmas',
|
|
ultima_actualizacion TEXT
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE cache_alarmas (
|
|
id INTEGER PRIMARY KEY,
|
|
cliente_id INTEGER NOT NULL,
|
|
cliente_nombre TEXT,
|
|
tipo TEXT NOT NULL,
|
|
severidad INTEGER NOT NULL DEFAULT 1,
|
|
estado TEXT NOT NULL DEFAULT 'activa',
|
|
zona_nombre TEXT,
|
|
timestamp TEXT NOT NULL,
|
|
notas TEXT
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE incidentes (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
alarma_id INTEGER,
|
|
cliente_id INTEGER,
|
|
cliente_nombre TEXT,
|
|
tipo TEXT NOT NULL,
|
|
operador TEXT NOT NULL,
|
|
notas TEXT,
|
|
timestamp TEXT NOT NULL,
|
|
resuelto INTEGER NOT NULL DEFAULT 0,
|
|
sincronizado INTEGER NOT NULL DEFAULT 0
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE operadores (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
nombre TEXT NOT NULL,
|
|
iniciales TEXT NOT NULL,
|
|
nivel INTEGER NOT NULL DEFAULT 1,
|
|
activo INTEGER NOT NULL DEFAULT 1,
|
|
en_turno INTEGER NOT NULL DEFAULT 0
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE sync_log (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
tipo TEXT NOT NULL,
|
|
estado TEXT NOT NULL,
|
|
detalle TEXT,
|
|
timestamp TEXT NOT NULL
|
|
)
|
|
''');
|
|
|
|
// Configuración por defecto
|
|
await db.insert('configuracion', {'clave': 'poll_interval_seg', 'valor': '30'});
|
|
await db.insert('configuracion', {'clave': 'sonido_alerta', 'valor': '1'});
|
|
}
|
|
|
|
// Comentario explicativo: Método para inicializar y poblar datos de prueba locales para la
|
|
// cuenta demo requerida por los revisores de Google Play Store y Apple App Store.
|
|
// Garantiza que la app funcione 100% offline sin pantallas vacías ni dependencias de red externa.
|
|
Future<void> poblarDatosDemo({bool force = false}) async {
|
|
final database = await db;
|
|
|
|
if (!force) {
|
|
final clientesExistentes = await database.rawQuery('SELECT COUNT(*) as c FROM cache_clientes');
|
|
final cant = (clientesExistentes.first['c'] as int?) ?? 0;
|
|
if (cant > 0) return; // Ya contiene datos poblados
|
|
}
|
|
|
|
final batch = database.batch();
|
|
|
|
// 1. Clientes de prueba
|
|
batch.delete('cache_clientes');
|
|
final nowIso = DateTime.now().toIso8601String();
|
|
final clientes = [
|
|
{
|
|
'id': 101,
|
|
'nombre': 'Banco Metropolitano - Sede Central',
|
|
'estado': 'critica',
|
|
'alarmas_activas': 2,
|
|
'alarmas_criticas': 1,
|
|
// Comentario explicativo: Servicio integral asignado al cliente bancario con alarmas y video
|
|
'tipo_servicio': 'Servicio Integral 360',
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 102,
|
|
'nombre': 'Centro Comercial Gran Plaza',
|
|
'estado': 'alerta',
|
|
'alarmas_activas': 1,
|
|
'alarmas_criticas': 0,
|
|
// Comentario explicativo: Servicio de videovigilancia CCTV asociado al centro comercial
|
|
'tipo_servicio': 'CCTV / Video-vigilancia',
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 103,
|
|
'nombre': 'Torre Empresarial Sigma',
|
|
'estado': 'normal',
|
|
'alarmas_activas': 0,
|
|
'alarmas_criticas': 0,
|
|
// Comentario explicativo: Servicio de control de acceso corporativo
|
|
'tipo_servicio': 'Control de Acceso',
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 104,
|
|
'nombre': 'Depósito Logístico Industrial Norte',
|
|
'estado': 'alerta',
|
|
'alarmas_activas': 1,
|
|
'alarmas_criticas': 0,
|
|
// Comentario explicativo: Servicio de rastreo vehicular GPS para la flota logística
|
|
'tipo_servicio': 'Rastreo Satelital GPS',
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 105,
|
|
'nombre': 'Residencial Altos del Valle',
|
|
'estado': 'normal',
|
|
'alarmas_activas': 0,
|
|
'alarmas_criticas': 0,
|
|
// Comentario explicativo: Servicio clásico de monitoreo de alarmas perimetrales
|
|
'tipo_servicio': 'Monitoreo de Alarmas',
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
];
|
|
for (final c in clientes) {
|
|
batch.insert('cache_clientes', c, conflictAlgorithm: ConflictAlgorithm.replace);
|
|
}
|
|
|
|
// 2. Alarmas de prueba
|
|
batch.delete('cache_alarmas');
|
|
final alarmas = [
|
|
{
|
|
'id': 201,
|
|
'cliente_id': 101,
|
|
'cliente_nombre': 'Banco Metropolitano - Sede Central',
|
|
'tipo': 'Pánico Bóveda Principal',
|
|
'severidad': 4,
|
|
'estado': 'activa',
|
|
'zona_nombre': 'Zona 01 - Bóveda',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 4)).toIso8601String(),
|
|
'notas': 'Sensor de vibración activado y pulsador de pánico manual accionado.',
|
|
},
|
|
{
|
|
'id': 202,
|
|
'cliente_id': 101,
|
|
'cliente_nombre': 'Banco Metropolitano - Sede Central',
|
|
'tipo': 'Intrusión Perimetral',
|
|
'severidad': 3,
|
|
'estado': 'activa',
|
|
'zona_nombre': 'Zona 04 - Acceso Trasero',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 12)).toIso8601String(),
|
|
'notas': 'Doble haz infrarrojo perimetral interrumpido.',
|
|
},
|
|
{
|
|
'id': 203,
|
|
'cliente_id': 102,
|
|
'cliente_nombre': 'Centro Comercial Gran Plaza',
|
|
'tipo': 'Detección de Humo',
|
|
'severidad': 3,
|
|
'estado': 'activa',
|
|
'zona_nombre': 'Zona 12 - Pasillo Comercial',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 25)).toIso8601String(),
|
|
'notas': 'Sensor óptico activado en pasillo de locales comerciales.',
|
|
},
|
|
{
|
|
'id': 204,
|
|
'cliente_id': 104,
|
|
'cliente_nombre': 'Depósito Logístico Industrial Norte',
|
|
'tipo': 'Fallo de Red / Desconexión',
|
|
'severidad': 2,
|
|
'estado': 'activa',
|
|
'zona_nombre': 'Zona 02 - Portón A',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 45)).toIso8601String(),
|
|
'notas': 'Pérdida temporal de enlace IP con panel de alarma.',
|
|
},
|
|
{
|
|
'id': 205,
|
|
'cliente_id': 103,
|
|
'cliente_nombre': 'Torre Empresarial Sigma',
|
|
'tipo': 'Apertura Fuera de Horario',
|
|
'severidad': 1,
|
|
'estado': 'silenciada',
|
|
'zona_nombre': 'Zona 08 - Puerta Técnica',
|
|
'timestamp': DateTime.now().subtract(const Duration(hours: 2)).toIso8601String(),
|
|
'notas': 'Autorización técnica en curso por soporte contratista.',
|
|
},
|
|
];
|
|
for (final a in alarmas) {
|
|
batch.insert('cache_alarmas', a, conflictAlgorithm: ConflictAlgorithm.replace);
|
|
}
|
|
|
|
// 3. Incidentes de auditoría de prueba
|
|
batch.delete('incidentes');
|
|
final incidentes = [
|
|
{
|
|
'id': 301,
|
|
'alarma_id': 201,
|
|
'cliente_id': 101,
|
|
'cliente_nombre': 'Banco Metropolitano - Sede Central',
|
|
'tipo': 'despacho_patrulla',
|
|
'operador': 'Operador Demo',
|
|
'notas': 'Patrulla de seguridad despachada en código rojo. Verificación en sitio.',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 3)).toIso8601String(),
|
|
'resuelto': 0,
|
|
'sincronizado': 1,
|
|
},
|
|
{
|
|
'id': 302,
|
|
'alarma_id': 202,
|
|
'cliente_id': 101,
|
|
'cliente_nombre': 'Banco Metropolitano - Sede Central',
|
|
'tipo': 'contacto_cliente',
|
|
'operador': 'Operador Demo',
|
|
'notas': 'Comunicación con encargado de seguridad confirmando ronda perimetral.',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 10)).toIso8601String(),
|
|
'resuelto': 0,
|
|
'sincronizado': 1,
|
|
},
|
|
{
|
|
'id': 303,
|
|
'alarma_id': 203,
|
|
'cliente_id': 102,
|
|
'cliente_nombre': 'Centro Comercial Gran Plaza',
|
|
'tipo': 'verificacion',
|
|
'operador': 'Operador Demo',
|
|
'notas': 'Brigada de seguridad interna notificada para verificación de zona.',
|
|
'timestamp': DateTime.now().subtract(const Duration(minutes: 20)).toIso8601String(),
|
|
'resuelto': 0,
|
|
'sincronizado': 1,
|
|
},
|
|
{
|
|
'id': 304,
|
|
'alarma_id': 205,
|
|
'cliente_id': 103,
|
|
'cliente_nombre': 'Torre Empresarial Sigma',
|
|
'tipo': 'falsa_alarma',
|
|
'operador': 'Operador Demo',
|
|
'notas': 'Mantenimiento preventivo autorizado de fibra óptica.',
|
|
'timestamp': DateTime.now().subtract(const Duration(hours: 2)).toIso8601String(),
|
|
'resuelto': 1,
|
|
'sincronizado': 1,
|
|
},
|
|
];
|
|
for (final inc in incidentes) {
|
|
batch.insert('incidentes', inc, conflictAlgorithm: ConflictAlgorithm.replace);
|
|
}
|
|
|
|
// 4. Operadores de prueba
|
|
batch.delete('operadores');
|
|
final operadores = [
|
|
{'id': 1, 'nombre': 'Operador Demo', 'iniciales': 'OD', 'nivel': 3, 'activo': 1, 'en_turno': 1},
|
|
{'id': 2, 'nombre': 'Carlos Mendoza', 'iniciales': 'CM', 'nivel': 2, 'activo': 1, 'en_turno': 1},
|
|
{'id': 3, 'nombre': 'Diana Ospina', 'iniciales': 'DO', 'nivel': 2, 'activo': 1, 'en_turno': 0},
|
|
];
|
|
for (final op in operadores) {
|
|
batch.insert('operadores', op, conflictAlgorithm: ConflictAlgorithm.replace);
|
|
}
|
|
|
|
// 5. Log de sincronización de prueba
|
|
batch.insert('sync_log', {
|
|
'tipo': 'demo_init',
|
|
'estado': 'ok',
|
|
'detalle': 'Conjunto de datos de prueba offline inicializado exitosamente',
|
|
'timestamp': nowIso,
|
|
});
|
|
|
|
await batch.commit(noResult: true);
|
|
}
|
|
|
|
// Comentario explicativo: Obtiene el resumen numérico de registros locales para auditar el estado del almacenamiento SQLite en la pantalla de Configuración
|
|
Future<Map<String, int>> getMetricasDb() async {
|
|
final dbInstance = await db;
|
|
final alarmasRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_alarmas');
|
|
final clientesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_clientes');
|
|
final incidentesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM incidentes');
|
|
final syncLogsRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM sync_log');
|
|
|
|
return {
|
|
'alarmas': (alarmasRes.isNotEmpty ? alarmasRes.first['c'] as int? : 0) ?? 0,
|
|
'clientes': (clientesRes.isNotEmpty ? clientesRes.first['c'] as int? : 0) ?? 0,
|
|
'incidentes': (incidentesRes.isNotEmpty ? incidentesRes.first['c'] as int? : 0) ?? 0,
|
|
'sync_logs': (syncLogsRes.isNotEmpty ? syncLogsRes.first['c'] as int? : 0) ?? 0,
|
|
};
|
|
}
|
|
|
|
// Comentario explicativo: Obtiene métricas ampliadas de todas las tablas de SQLite para el panel de Administrar Datos
|
|
Future<Map<String, int>> getMetricasDetalladasDb() async {
|
|
final dbInstance = await db;
|
|
final alarmasRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_alarmas');
|
|
final clientesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM cache_clientes');
|
|
final incidentesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM incidentes');
|
|
final syncLogsRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM sync_log');
|
|
final operadoresRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM operadores');
|
|
final sesionesRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM sesiones_operador');
|
|
final configRes = await dbInstance.rawQuery('SELECT COUNT(*) as c FROM configuracion');
|
|
|
|
return {
|
|
'alarmas': (alarmasRes.isNotEmpty ? alarmasRes.first['c'] as int? : 0) ?? 0,
|
|
'clientes': (clientesRes.isNotEmpty ? clientesRes.first['c'] as int? : 0) ?? 0,
|
|
'incidentes': (incidentesRes.isNotEmpty ? incidentesRes.first['c'] as int? : 0) ?? 0,
|
|
'sync_logs': (syncLogsRes.isNotEmpty ? syncLogsRes.first['c'] as int? : 0) ?? 0,
|
|
'operadores': (operadoresRes.isNotEmpty ? operadoresRes.first['c'] as int? : 0) ?? 0,
|
|
'sesiones': (sesionesRes.isNotEmpty ? sesionesRes.first['c'] as int? : 0) ?? 0,
|
|
'config': (configRes.isNotEmpty ? configRes.first['c'] as int? : 0) ?? 0,
|
|
};
|
|
}
|
|
|
|
// Comentario explicativo: Reinicializa completamente la base de datos local SQLite, vaciando todas las tablas
|
|
// operativas y restableciendo los parámetros por defecto del sistema
|
|
Future<void> reinicializarBaseDatos() async {
|
|
final dbInstance = await db;
|
|
final batch = dbInstance.batch();
|
|
|
|
// Vaciado de tablas operativas
|
|
batch.delete('cache_alarmas');
|
|
batch.delete('cache_clientes');
|
|
batch.delete('incidentes');
|
|
batch.delete('operadores');
|
|
batch.delete('sesiones_operador');
|
|
batch.delete('sync_log');
|
|
|
|
// Restablecimiento de configuración por defecto
|
|
batch.delete('configuracion');
|
|
batch.insert('configuracion', {'clave': 'poll_interval_seg', 'valor': '30'});
|
|
batch.insert('configuracion', {'clave': 'sonido_alerta', 'valor': '1'});
|
|
batch.insert('configuracion', {'clave': 'alerta_prioritaria','valor': '1'});
|
|
|
|
// Registro de auditoría del evento de reinicio
|
|
batch.insert('sync_log', {
|
|
'tipo': 'db_init_reset',
|
|
'estado': 'ok',
|
|
'detalle': 'Base de datos reinicializada manualmente a estado de fábrica',
|
|
'timestamp': DateTime.now().toIso8601String(),
|
|
});
|
|
|
|
await batch.commit(noResult: true);
|
|
}
|
|
|
|
// Comentario explicativo: Vacía únicamente las tablas de caché temporal (alarmas y clientes) sin alterar incidentes ni operadores
|
|
Future<void> vaciarCacheOperativo() async {
|
|
final dbInstance = await db;
|
|
final batch = dbInstance.batch();
|
|
batch.delete('cache_alarmas');
|
|
batch.delete('cache_clientes');
|
|
batch.insert('sync_log', {
|
|
'tipo': 'cache_clear',
|
|
'estado': 'ok',
|
|
'detalle': 'Caché operativo de alarmas y clientes vaciado manualmente',
|
|
'timestamp': DateTime.now().toIso8601String(),
|
|
});
|
|
await batch.commit(noResult: true);
|
|
}
|
|
|
|
// Comentario explicativo: Vacía la tabla de incidentes locales para reiniciar el registro de eventos de turno
|
|
Future<void> limpiarIncidentes() async {
|
|
final dbInstance = await db;
|
|
await dbInstance.delete('incidentes');
|
|
}
|
|
|
|
// Comentario explicativo: Limpia el historial de sincronización local conservando la integridad de las demás tablas
|
|
Future<void> limpiarSyncLogs() async {
|
|
final dbInstance = await db;
|
|
await dbInstance.delete('sync_log');
|
|
}
|
|
}
|