353 lines
12 KiB
Dart
353 lines
12 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();
|
|
return openDatabase(path, version: _dbVersion, onCreate: _onCreate);
|
|
}
|
|
|
|
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,
|
|
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,
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 102,
|
|
'nombre': 'Centro Comercial Gran Plaza',
|
|
'estado': 'alerta',
|
|
'alarmas_activas': 1,
|
|
'alarmas_criticas': 0,
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 103,
|
|
'nombre': 'Torre Empresarial Sigma',
|
|
'estado': 'normal',
|
|
'alarmas_activas': 0,
|
|
'alarmas_criticas': 0,
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 104,
|
|
'nombre': 'Depósito Logístico Industrial Norte',
|
|
'estado': 'alerta',
|
|
'alarmas_activas': 1,
|
|
'alarmas_criticas': 0,
|
|
'ultima_actualizacion': nowIso,
|
|
},
|
|
{
|
|
'id': 105,
|
|
'nombre': 'Residencial Altos del Valle',
|
|
'estado': 'normal',
|
|
'alarmas_activas': 0,
|
|
'alarmas_criticas': 0,
|
|
'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: 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');
|
|
}
|
|
}
|