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:
Pablinux
2026-04-14 01:56:13 -05:00
co-authored by Claude Sonnet 4.6
parent 8f13d57839
commit 1184ab5fe2
35 changed files with 2735 additions and 346 deletions
+49
View File
@@ -0,0 +1,49 @@
import '../database_helper.dart';
import '../../models/acceso.dart';
class AccesosDao {
final _db = DatabaseHelper.instance;
Future<List<Acceso>> getAll() async {
final db = await _db.db;
final rows = await db.query('accesos', orderBy: 'timestamp DESC');
return rows.map(Acceso.fromMap).toList();
}
Future<List<Acceso>> getRecientes({int limit = 20}) async {
final db = await _db.db;
final rows = await db.query(
'accesos',
orderBy: 'timestamp DESC',
limit: limit,
);
return rows.map(Acceso.fromMap).toList();
}
Future<List<Acceso>> getByPuerta(int puertaId) async {
final db = await _db.db;
final rows = await db.query(
'accesos',
where: 'puerta_id = ?',
whereArgs: [puertaId],
orderBy: 'timestamp DESC',
);
return rows.map(Acceso.fromMap).toList();
}
Future<int> insert(Acceso a) async {
final db = await _db.db;
return db.insert('accesos', a.toMap());
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('accesos', where: 'id = ?', whereArgs: [id]);
}
Future<List<Acceso>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('accesos', where: 'sincronizado = 0');
return rows.map(Acceso.fromMap).toList();
}
}
+94
View File
@@ -0,0 +1,94 @@
import '../database_helper.dart';
import '../../models/alarma.dart';
class AlarmasDao {
final _db = DatabaseHelper.instance;
Future<List<Alarma>> getAll() async {
final db = await _db.db;
final rows = await db.query('alarmas', orderBy: 'timestamp DESC');
return rows.map(Alarma.fromMap).toList();
}
Future<List<Alarma>> getActivas() async {
final db = await _db.db;
final rows = await db.query(
'alarmas',
where: 'estado = ?',
whereArgs: ['activa'],
orderBy: 'severidad DESC, timestamp DESC',
);
return rows.map(Alarma.fromMap).toList();
}
Future<List<Alarma>> getByZona(int zonaId) async {
final db = await _db.db;
final rows = await db.query(
'alarmas',
where: 'zona_id = ?',
whereArgs: [zonaId],
orderBy: 'timestamp DESC',
);
return rows.map(Alarma.fromMap).toList();
}
Future<Alarma?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('alarmas', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Alarma.fromMap(rows.first);
}
Future<int> insert(Alarma a) async {
final db = await _db.db;
return db.insert('alarmas', a.toMap());
}
Future<int> update(Alarma a) async {
final db = await _db.db;
return db.update('alarmas', a.toMap(), where: 'id = ?', whereArgs: [a.id]);
}
Future<int> resolver(int id, int usuarioId, {String? notas}) async {
final db = await _db.db;
return db.update(
'alarmas',
{
'estado': 'resuelta',
'resuelto_por': usuarioId,
'notas': notas,
'sincronizado': 0,
},
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> silenciar(int id) async {
final db = await _db.db;
return db.update(
'alarmas',
{'estado': 'silenciada', 'sincronizado': 0},
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('alarmas', where: 'id = ?', whereArgs: [id]);
}
Future<List<Alarma>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('alarmas', where: 'sincronizado = 0');
return rows.map(Alarma.fromMap).toList();
}
Future<int> contarActivas() async {
final db = await _db.db;
final result = await db.rawQuery(
"SELECT COUNT(*) as c FROM alarmas WHERE estado = 'activa'",
);
return result.first['c'] as int;
}
}
+43
View File
@@ -0,0 +1,43 @@
import '../database_helper.dart';
import '../../models/banner_item.dart';
class BannersDao {
final _db = DatabaseHelper.instance;
Future<List<BannerItem>> getActivos() async {
final db = await _db.db;
final rows = await db.query(
'banners',
where: 'activo = 1',
orderBy: 'orden ASC',
);
return rows.map(BannerItem.fromMap).toList();
}
Future<BannerItem?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('banners', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : BannerItem.fromMap(rows.first);
}
Future<int> insert(BannerItem b) async {
final db = await _db.db;
return db.insert('banners', b.toMap());
}
Future<int> update(BannerItem b) async {
final db = await _db.db;
return db.update('banners', b.toMap(), where: 'id = ?', whereArgs: [b.id]);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('banners', where: 'id = ?', whereArgs: [id]);
}
Future<List<BannerItem>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('banners', where: 'sincronizado = 0');
return rows.map(BannerItem.fromMap).toList();
}
}
+30
View File
@@ -0,0 +1,30 @@
import 'package:sqflite/sqflite.dart';
import '../database_helper.dart';
class ConfiguracionDao {
final _db = DatabaseHelper.instance;
Future<String?> get(String clave) async {
final db = await _db.db;
final rows = await db.query(
'configuracion',
where: 'clave = ?',
whereArgs: [clave],
);
return rows.isEmpty ? null : rows.first['valor'] as String?;
}
Future<void> set(String clave, String valor) async {
final db = await _db.db;
await db.insert(
'configuracion',
{'clave': clave, 'valor': valor},
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<void> delete(String clave) async {
final db = await _db.db;
await db.delete('configuracion', where: 'clave = ?', whereArgs: [clave]);
}
}
+62
View File
@@ -0,0 +1,62 @@
import '../database_helper.dart';
import '../../models/evento.dart';
class EventosDao {
final _db = DatabaseHelper.instance;
Future<List<Evento>> getAll() async {
final db = await _db.db;
final rows = await db.query('eventos', orderBy: 'timestamp DESC');
return rows.map(Evento.fromMap).toList();
}
Future<List<Evento>> getRecientes({int limit = 10}) async {
final db = await _db.db;
final rows = await db.query(
'eventos',
orderBy: 'timestamp DESC',
limit: limit,
);
return rows.map(Evento.fromMap).toList();
}
Future<Evento?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('eventos', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Evento.fromMap(rows.first);
}
Future<int> insert(Evento e) async {
final db = await _db.db;
return db.insert('eventos', e.toMap());
}
Future<int> marcarLeido(int id) async {
final db = await _db.db;
return db.update(
'eventos',
{'leido': 1, 'sincronizado': 0},
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('eventos', where: 'id = ?', whereArgs: [id]);
}
Future<List<Evento>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('eventos', where: 'sincronizado = 0');
return rows.map(Evento.fromMap).toList();
}
Future<int> contarNoLeidos() async {
final db = await _db.db;
final result = await db.rawQuery(
'SELECT COUNT(*) as c FROM eventos WHERE leido = 0',
);
return result.first['c'] as int;
}
}
+28
View File
@@ -0,0 +1,28 @@
import '../database_helper.dart';
import '../../models/mensaje.dart';
class MensajesDao {
final _db = DatabaseHelper.instance;
Future<List<Mensaje>> getAll() async {
final db = await _db.db;
final rows = await db.query('mensajes', orderBy: 'timestamp ASC');
return rows.map(Mensaje.fromMap).toList();
}
Future<int> insert(Mensaje m) async {
final db = await _db.db;
return db.insert('mensajes', m.toMap());
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('mensajes', where: 'id = ?', whereArgs: [id]);
}
Future<List<Mensaje>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('mensajes', where: 'sincronizado = 0');
return rows.map(Mensaje.fromMap).toList();
}
}
+45
View File
@@ -0,0 +1,45 @@
import '../database_helper.dart';
import '../../models/nodo.dart';
class NodosDao {
final _db = DatabaseHelper.instance;
Future<List<Nodo>> getAll() async {
final db = await _db.db;
final rows = await db.query('nodos', orderBy: 'nombre ASC');
return rows.map(Nodo.fromMap).toList();
}
Future<List<Nodo>> getByZona(int zonaId) async {
final db = await _db.db;
final rows = await db.query('nodos', where: 'zona_id = ?', whereArgs: [zonaId]);
return rows.map(Nodo.fromMap).toList();
}
Future<Nodo?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('nodos', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Nodo.fromMap(rows.first);
}
Future<int> insert(Nodo n) async {
final db = await _db.db;
return db.insert('nodos', n.toMap());
}
Future<int> update(Nodo n) async {
final db = await _db.db;
return db.update('nodos', n.toMap(), where: 'id = ?', whereArgs: [n.id]);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('nodos', where: 'id = ?', whereArgs: [id]);
}
Future<List<Nodo>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('nodos', where: 'sincronizado = 0');
return rows.map(Nodo.fromMap).toList();
}
}
+49
View File
@@ -0,0 +1,49 @@
import '../database_helper.dart';
import '../../models/puerta.dart';
class PuertasDao {
final _db = DatabaseHelper.instance;
Future<List<Puerta>> getAll() async {
final db = await _db.db;
final rows = await db.query('puertas', orderBy: 'nombre ASC');
return rows.map(Puerta.fromMap).toList();
}
Future<Puerta?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('puertas', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Puerta.fromMap(rows.first);
}
Future<int> insert(Puerta p) async {
final db = await _db.db;
return db.insert('puertas', p.toMap());
}
Future<int> update(Puerta p) async {
final db = await _db.db;
return db.update('puertas', p.toMap(), where: 'id = ?', whereArgs: [p.id]);
}
Future<int> setBloqueada(int id, bool bloqueada) async {
final db = await _db.db;
return db.update(
'puertas',
{'bloqueada': bloqueada ? 1 : 0, 'sincronizado': 0},
where: 'id = ?',
whereArgs: [id],
);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('puertas', where: 'id = ?', whereArgs: [id]);
}
Future<List<Puerta>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('puertas', where: 'sincronizado = 0');
return rows.map(Puerta.fromMap).toList();
}
}
+47
View File
@@ -0,0 +1,47 @@
import '../database_helper.dart';
import '../../models/sesion.dart';
class SesionesDao {
final _db = DatabaseHelper.instance;
Future<List<Sesion>> getByUsuario(int usuarioId) async {
final db = await _db.db;
final rows = await db.query(
'sesiones',
where: 'usuario_id = ?',
whereArgs: [usuarioId],
orderBy: 'timestamp_inicio DESC',
);
return rows.map(Sesion.fromMap).toList();
}
Future<Sesion?> getSesionActiva(int usuarioId) async {
final db = await _db.db;
final rows = await db.query(
'sesiones',
where: 'usuario_id = ? AND timestamp_fin IS NULL',
whereArgs: [usuarioId],
limit: 1,
);
return rows.isEmpty ? null : Sesion.fromMap(rows.first);
}
Future<int> iniciar(int usuarioId, {String? dispositivo}) async {
final db = await _db.db;
return db.insert('sesiones', {
'usuario_id': usuarioId,
'timestamp_inicio': DateTime.now().toIso8601String(),
'dispositivo': dispositivo,
});
}
Future<int> cerrar(int id) async {
final db = await _db.db;
return db.update(
'sesiones',
{'timestamp_fin': DateTime.now().toIso8601String()},
where: 'id = ?',
whereArgs: [id],
);
}
}
+28
View File
@@ -0,0 +1,28 @@
import '../database_helper.dart';
class SyncLogDao {
final _db = DatabaseHelper.instance;
Future<int> registrar({
required String tipo,
required String estado,
String? detalle,
}) async {
final db = await _db.db;
return db.insert('sync_log', {
'timestamp': DateTime.now().toIso8601String(),
'tipo': tipo,
'estado': estado,
'detalle': detalle,
});
}
Future<List<Map<String, dynamic>>> getRecientes({int limit = 20}) async {
final db = await _db.db;
return db.query(
'sync_log',
orderBy: 'timestamp DESC',
limit: limit,
);
}
}
+49
View File
@@ -0,0 +1,49 @@
import '../database_helper.dart';
import '../../models/usuario.dart';
class UsuariosDao {
final _db = DatabaseHelper.instance;
Future<List<Usuario>> getAll() async {
final db = await _db.db;
final rows = await db.query('usuarios', orderBy: 'nombre ASC');
return rows.map(Usuario.fromMap).toList();
}
Future<Usuario?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('usuarios', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Usuario.fromMap(rows.first);
}
Future<Usuario?> getByPinHash(String pinHash) async {
final db = await _db.db;
final rows = await db.query(
'usuarios',
where: 'pin_hash = ? AND activo = 1',
whereArgs: [pinHash],
);
return rows.isEmpty ? null : Usuario.fromMap(rows.first);
}
Future<int> insert(Usuario u) async {
final db = await _db.db;
return db.insert('usuarios', u.toMap());
}
Future<int> update(Usuario u) async {
final db = await _db.db;
return db.update('usuarios', u.toMap(), where: 'id = ?', whereArgs: [u.id]);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('usuarios', where: 'id = ?', whereArgs: [id]);
}
Future<List<Usuario>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('usuarios', where: 'sincronizado = 0');
return rows.map(Usuario.fromMap).toList();
}
}
+39
View File
@@ -0,0 +1,39 @@
import '../database_helper.dart';
import '../../models/zona.dart';
class ZonasDao {
final _db = DatabaseHelper.instance;
Future<List<Zona>> getAll() async {
final db = await _db.db;
final rows = await db.query('zonas', orderBy: 'codigo ASC');
return rows.map(Zona.fromMap).toList();
}
Future<Zona?> getById(int id) async {
final db = await _db.db;
final rows = await db.query('zonas', where: 'id = ?', whereArgs: [id]);
return rows.isEmpty ? null : Zona.fromMap(rows.first);
}
Future<int> insert(Zona z) async {
final db = await _db.db;
return db.insert('zonas', z.toMap());
}
Future<int> update(Zona z) async {
final db = await _db.db;
return db.update('zonas', z.toMap(), where: 'id = ?', whereArgs: [z.id]);
}
Future<int> delete(int id) async {
final db = await _db.db;
return db.delete('zonas', where: 'id = ?', whereArgs: [id]);
}
Future<List<Zona>> getPendientes() async {
final db = await _db.db;
final rows = await db.query('zonas', where: 'sincronizado = 0');
return rows.map(Zona.fromMap).toList();
}
}
+412
View File
@@ -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);
}
}
}