feat: add SQLite data layer, local auth and security settings
- Add offline-first SQLite architecture with DatabaseHelper singleton, 12 CREATE TABLE statements and full seed data on first launch - Add 10 models (fromMap/toMap) and 12 DAOs with CRUD + getPendientes() - Add ApiAuthService (JWT via SharedPreferences) and Sincronizador skeleton - Move login auth from SQLite to SharedPreferences with SHA-256 PIN hash; default PIN 123456, platform-independent (no native plugin required) - Add seguridad_page.dart: change PIN form (current → new → confirm) - Add Cerrar Sesión with confirmation dialog and full stack clear - Redesign settings_page.dart with AppColors dark theme; add Sistema section with "Inicializar base de datos" and "Inicializar sincronización" - Fix Linux desktop: sqflite_common_ffi with platform detection in DatabaseHelper - Fix ScrollController conflict on Linux: primary: false on all IndexedStack pages - Update plan_proyecto.md with session 2–3 progress and auth roadmap Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
8f13d57839
commit
1184ab5fe2
@@ -0,0 +1,412 @@
|
||||
import 'dart:io';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:path/path.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static const _dbName = 'sentinel_one.db';
|
||||
static const _dbVersion = 1;
|
||||
|
||||
DatabaseHelper._();
|
||||
static final DatabaseHelper instance = DatabaseHelper._();
|
||||
|
||||
Database? _db;
|
||||
|
||||
Future<Database> get db async {
|
||||
_db ??= await _initDb();
|
||||
return _db!;
|
||||
}
|
||||
|
||||
/// Cierra la BD y la marca para reinicialización.
|
||||
/// Llamar antes de borrar el archivo de la BD.
|
||||
void resetInstance() {
|
||||
_db?.close();
|
||||
_db = null;
|
||||
}
|
||||
|
||||
Future<Database> _initDb() async {
|
||||
if (Platform.isLinux || Platform.isWindows) {
|
||||
sqfliteFfiInit();
|
||||
final dbPath = join(Directory.current.path, _dbName);
|
||||
return databaseFactoryFfi.openDatabase(
|
||||
dbPath,
|
||||
options: OpenDatabaseOptions(
|
||||
version: _dbVersion,
|
||||
onCreate: _onCreate,
|
||||
),
|
||||
);
|
||||
}
|
||||
final path = join(await getDatabasesPath(), _dbName);
|
||||
return openDatabase(
|
||||
path,
|
||||
version: _dbVersion,
|
||||
onCreate: _onCreate,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onCreate(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE usuarios (
|
||||
id INTEGER PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
iniciales TEXT NOT NULL,
|
||||
nivel_acceso INTEGER NOT NULL DEFAULT 1,
|
||||
pin_hash TEXT NOT NULL,
|
||||
areas TEXT,
|
||||
fecha_inicio TEXT,
|
||||
fecha_fin TEXT,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE zonas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
codigo TEXT NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
descripcion TEXT,
|
||||
estado TEXT NOT NULL DEFAULT 'segura',
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE nodos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
ultima_senal TEXT,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE puertas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
codigo TEXT NOT NULL,
|
||||
bloqueada INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE alarmas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
severidad INTEGER NOT NULL DEFAULT 1,
|
||||
timestamp TEXT NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'activa',
|
||||
resuelto_por INTEGER,
|
||||
notas TEXT,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id),
|
||||
FOREIGN KEY (resuelto_por) REFERENCES usuarios(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE accesos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
usuario_id INTEGER NOT NULL,
|
||||
puerta_id INTEGER NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
autorizado INTEGER NOT NULL DEFAULT 0,
|
||||
metodo TEXT NOT NULL DEFAULT 'pin',
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (usuario_id) REFERENCES usuarios(id),
|
||||
FOREIGN KEY (puerta_id) REFERENCES puertas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE eventos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
tipo TEXT NOT NULL,
|
||||
titulo TEXT NOT NULL,
|
||||
descripcion TEXT,
|
||||
hora TEXT NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
leido INTEGER NOT NULL DEFAULT 0,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE mensajes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
texto TEXT NOT NULL,
|
||||
es_mio INTEGER NOT NULL DEFAULT 1,
|
||||
hora TEXT NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE banners (
|
||||
id INTEGER PRIMARY KEY,
|
||||
badge TEXT NOT NULL,
|
||||
titulo TEXT NOT NULL,
|
||||
subtitulo TEXT,
|
||||
orden INTEGER NOT NULL DEFAULT 0,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sesiones (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
usuario_id INTEGER NOT NULL,
|
||||
timestamp_inicio TEXT NOT NULL,
|
||||
timestamp_fin TEXT,
|
||||
dispositivo TEXT,
|
||||
FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sync_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
estado TEXT NOT NULL,
|
||||
detalle TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE configuracion (
|
||||
clave TEXT PRIMARY KEY,
|
||||
valor TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await _seedData(db);
|
||||
}
|
||||
|
||||
// ─── Datos iniciales ──────────────────────────────────────────────────────
|
||||
// PIN de seed: 123456 → SHA-256 hash real generado externamente
|
||||
// echo -n "123456" | sha256sum → 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
|
||||
static const _pinSeed =
|
||||
'8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92';
|
||||
|
||||
Future<void> _seedData(Database db) async {
|
||||
// ── Zonas ──
|
||||
final zonas = [
|
||||
{'id': 1, 'codigo': 'Z-01', 'nombre': 'Lobby Principal',
|
||||
'descripcion': 'Entrada · 3 cámaras · 2 sensores', 'estado': 'segura'},
|
||||
{'id': 2, 'codigo': 'Z-02', 'nombre': 'Muelle de Carga',
|
||||
'descripcion': 'Carga/descarga · 2 cámaras · 1 sensor', 'estado': 'segura'},
|
||||
{'id': 3, 'codigo': 'Z-03', 'nombre': 'Centro de Datos',
|
||||
'descripcion': 'Sala servidores · 4 cámaras · 3 sensores', 'estado': 'segura'},
|
||||
{'id': 4, 'codigo': 'Z-04', 'nombre': 'Almacén G-4',
|
||||
'descripcion': 'Bodega · 2 cámaras · 4 sensores', 'estado': 'alerta'},
|
||||
{'id': 5, 'codigo': 'Z-05', 'nombre': 'Perímetro Norte',
|
||||
'descripcion': 'Cerca · 4 cámaras', 'estado': 'segura'},
|
||||
{'id': 6, 'codigo': 'Z-06', 'nombre': 'Sala de Servidores A',
|
||||
'descripcion': 'TI · 1 cámara · 2 sensores humo', 'estado': 'segura'},
|
||||
];
|
||||
for (final z in zonas) {
|
||||
await db.insert('zonas', {...z, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Puertas ──
|
||||
final puertas = [
|
||||
{'id': 1, 'zona_id': 1, 'nombre': 'Lobby Principal',
|
||||
'codigo': 'Entrada 01', 'bloqueada': 0},
|
||||
{'id': 2, 'zona_id': 2, 'nombre': 'Muelle de Carga',
|
||||
'codigo': 'Carga 02', 'bloqueada': 0},
|
||||
{'id': 3, 'zona_id': 3, 'nombre': 'Centro de Datos',
|
||||
'codigo': 'Datos 03', 'bloqueada': 1},
|
||||
];
|
||||
for (final p in puertas) {
|
||||
await db.insert('puertas', {...p, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Usuarios ──
|
||||
await db.insert('usuarios', {
|
||||
'id': 1,
|
||||
'nombre': 'Juan Díaz',
|
||||
'iniciales': 'JD',
|
||||
'nivel_acceso': 3,
|
||||
'pin_hash': _pinSeed,
|
||||
'areas': '[1,2,3,4,5,6]',
|
||||
'fecha_inicio': '2026-01-01T00:00:00',
|
||||
'fecha_fin': null,
|
||||
'activo': 1,
|
||||
'sincronizado': 1,
|
||||
});
|
||||
|
||||
// ── Alarmas históricas ──
|
||||
final ahora = DateTime.now();
|
||||
final alarmas = [
|
||||
{
|
||||
'id': 1, 'zona_id': 4, 'tipo': 'intrusion', 'severidad': 5,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||
'estado': 'activa', 'resuelto_por': null, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 2, 'zona_id': 6, 'tipo': 'humo', 'severidad': 3,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': 'Sensor calibrado',
|
||||
},
|
||||
{
|
||||
'id': 3, 'zona_id': 5, 'tipo': 'movimiento', 'severidad': 2,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3, minutes: 20)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 4, 'zona_id': 2, 'tipo': 'acceso', 'severidad': 1,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 5)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 5, 'zona_id': 1, 'tipo': 'intrusion', 'severidad': 2,
|
||||
'timestamp': ahora.subtract(const Duration(days: 1)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
];
|
||||
for (final a in alarmas) {
|
||||
await db.insert('alarmas', {...a, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Accesos ──
|
||||
final accesos = [
|
||||
{
|
||||
'id': 1, 'usuario_id': 1, 'puerta_id': 2,
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 95)).toIso8601String(),
|
||||
'autorizado': 1, 'metodo': 'remoto',
|
||||
},
|
||||
{
|
||||
'id': 2, 'usuario_id': 1, 'puerta_id': 1,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2, minutes: 30)).toIso8601String(),
|
||||
'autorizado': 0, 'metodo': 'pin',
|
||||
},
|
||||
{
|
||||
'id': 3, 'usuario_id': 1, 'puerta_id': 3,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 4)).toIso8601String(),
|
||||
'autorizado': 1, 'metodo': 'pin',
|
||||
},
|
||||
];
|
||||
for (final a in accesos) {
|
||||
await db.insert('accesos', {...a, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Eventos del log de InicioPage ──
|
||||
final eventos = [
|
||||
{
|
||||
'id': 1, 'tipo': 'alerta',
|
||||
'titulo': 'Alerta Crítica',
|
||||
'descripcion': 'Zona G-4: Sensor de movimiento activado.',
|
||||
'hora': '09:41 AM',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 30)).toIso8601String(),
|
||||
'leido': 0,
|
||||
},
|
||||
{
|
||||
'id': 2, 'tipo': 'noticia',
|
||||
'titulo': 'Noticia',
|
||||
'descripcion': 'Actualización de firmware en nodos de la Zona Z-03.',
|
||||
'hora': '08:15 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||
'leido': 1,
|
||||
},
|
||||
{
|
||||
'id': 3, 'tipo': 'notificacion',
|
||||
'titulo': 'Notificación',
|
||||
'descripcion': 'Turno nocturno confirmado para el Sector Norte.',
|
||||
'hora': '07:00 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||
'leido': 1,
|
||||
},
|
||||
{
|
||||
'id': 4, 'tipo': 'general',
|
||||
'titulo': 'Evento General',
|
||||
'descripcion': 'Backup del sistema completado correctamente.',
|
||||
'hora': '02:00 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 8)).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': '09:30',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 45)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Todo en orden por el momento. Revisando sector norte.',
|
||||
'es_mio': 1, 'hora': '09:32',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 43)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Recibido. Se detectó movimiento en zona G-4, ¿confirma?',
|
||||
'es_mio': 0, 'hora': '09:38',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 37)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Afirmativo. Voy a verificar en persona.',
|
||||
'es_mio': 1, 'hora': '09:39',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 36)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Entendido. Enviamos unidad de respaldo. ETA: 8 minutos.',
|
||||
'es_mio': 0, 'hora': '09:40',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 35)).toIso8601String(),
|
||||
},
|
||||
];
|
||||
for (final m in mensajes) {
|
||||
await db.insert('mensajes', {...m, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Banners ──
|
||||
final banners = [
|
||||
{
|
||||
'id': 1, 'badge': 'Premium Access',
|
||||
'titulo': 'Sector Norte Asegurado',
|
||||
'subtitulo': 'Patrullaje nocturno completado · Sin incidencias',
|
||||
'orden': 0, 'activo': 1,
|
||||
},
|
||||
{
|
||||
'id': 2, 'badge': 'Alerta Activa',
|
||||
'titulo': 'Zona G-4 en Revisión',
|
||||
'subtitulo': 'Movimiento detectado · Unidad en camino',
|
||||
'orden': 1, 'activo': 1,
|
||||
},
|
||||
{
|
||||
'id': 3, 'badge': 'Sistema OK',
|
||||
'titulo': '24 Nodos en Línea',
|
||||
'subtitulo': 'Todos los sectores operativos',
|
||||
'orden': 2, 'activo': 1,
|
||||
},
|
||||
];
|
||||
for (final b in banners) {
|
||||
await db.insert('banners', {...b, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Configuración inicial ──
|
||||
final config = [
|
||||
{'clave': 'usuario_activo_id', 'valor': '1'},
|
||||
{'clave': 'notificaciones_activas', 'valor': 'true'},
|
||||
{'clave': 'api_base_url', 'valor': ''},
|
||||
{'clave': 'api_token', 'valor': ''},
|
||||
{'clave': 'api_token_expiry', 'valor': ''},
|
||||
];
|
||||
for (final c in config) {
|
||||
await db.insert('configuracion', c);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user