diff --git a/lib/db/dao/accesos_dao.dart b/lib/db/dao/accesos_dao.dart new file mode 100644 index 0000000..5fc72b9 --- /dev/null +++ b/lib/db/dao/accesos_dao.dart @@ -0,0 +1,49 @@ +import '../database_helper.dart'; +import '../../models/acceso.dart'; + +class AccesosDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('accesos', orderBy: 'timestamp DESC'); + return rows.map(Acceso.fromMap).toList(); + } + + Future> 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> 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 insert(Acceso a) async { + final db = await _db.db; + return db.insert('accesos', a.toMap()); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('accesos', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('accesos', where: 'sincronizado = 0'); + return rows.map(Acceso.fromMap).toList(); + } +} diff --git a/lib/db/dao/alarmas_dao.dart b/lib/db/dao/alarmas_dao.dart new file mode 100644 index 0000000..c0b9ba1 --- /dev/null +++ b/lib/db/dao/alarmas_dao.dart @@ -0,0 +1,94 @@ +import '../database_helper.dart'; +import '../../models/alarma.dart'; + +class AlarmasDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('alarmas', orderBy: 'timestamp DESC'); + return rows.map(Alarma.fromMap).toList(); + } + + Future> 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> 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 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 insert(Alarma a) async { + final db = await _db.db; + return db.insert('alarmas', a.toMap()); + } + + Future update(Alarma a) async { + final db = await _db.db; + return db.update('alarmas', a.toMap(), where: 'id = ?', whereArgs: [a.id]); + } + + Future 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 silenciar(int id) async { + final db = await _db.db; + return db.update( + 'alarmas', + {'estado': 'silenciada', 'sincronizado': 0}, + where: 'id = ?', + whereArgs: [id], + ); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('alarmas', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('alarmas', where: 'sincronizado = 0'); + return rows.map(Alarma.fromMap).toList(); + } + + Future 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; + } +} diff --git a/lib/db/dao/banners_dao.dart b/lib/db/dao/banners_dao.dart new file mode 100644 index 0000000..7ca1e3f --- /dev/null +++ b/lib/db/dao/banners_dao.dart @@ -0,0 +1,43 @@ +import '../database_helper.dart'; +import '../../models/banner_item.dart'; + +class BannersDao { + final _db = DatabaseHelper.instance; + + Future> 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 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 insert(BannerItem b) async { + final db = await _db.db; + return db.insert('banners', b.toMap()); + } + + Future update(BannerItem b) async { + final db = await _db.db; + return db.update('banners', b.toMap(), where: 'id = ?', whereArgs: [b.id]); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('banners', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('banners', where: 'sincronizado = 0'); + return rows.map(BannerItem.fromMap).toList(); + } +} diff --git a/lib/db/dao/configuracion_dao.dart b/lib/db/dao/configuracion_dao.dart new file mode 100644 index 0000000..2d83ed1 --- /dev/null +++ b/lib/db/dao/configuracion_dao.dart @@ -0,0 +1,30 @@ +import 'package:sqflite/sqflite.dart'; +import '../database_helper.dart'; + +class ConfiguracionDao { + final _db = DatabaseHelper.instance; + + Future 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 set(String clave, String valor) async { + final db = await _db.db; + await db.insert( + 'configuracion', + {'clave': clave, 'valor': valor}, + conflictAlgorithm: ConflictAlgorithm.replace, + ); + } + + Future delete(String clave) async { + final db = await _db.db; + await db.delete('configuracion', where: 'clave = ?', whereArgs: [clave]); + } +} diff --git a/lib/db/dao/eventos_dao.dart b/lib/db/dao/eventos_dao.dart new file mode 100644 index 0000000..4a5bf63 --- /dev/null +++ b/lib/db/dao/eventos_dao.dart @@ -0,0 +1,62 @@ +import '../database_helper.dart'; +import '../../models/evento.dart'; + +class EventosDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('eventos', orderBy: 'timestamp DESC'); + return rows.map(Evento.fromMap).toList(); + } + + Future> 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 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 insert(Evento e) async { + final db = await _db.db; + return db.insert('eventos', e.toMap()); + } + + Future marcarLeido(int id) async { + final db = await _db.db; + return db.update( + 'eventos', + {'leido': 1, 'sincronizado': 0}, + where: 'id = ?', + whereArgs: [id], + ); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('eventos', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('eventos', where: 'sincronizado = 0'); + return rows.map(Evento.fromMap).toList(); + } + + Future 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; + } +} diff --git a/lib/db/dao/mensajes_dao.dart b/lib/db/dao/mensajes_dao.dart new file mode 100644 index 0000000..a6d0a8e --- /dev/null +++ b/lib/db/dao/mensajes_dao.dart @@ -0,0 +1,28 @@ +import '../database_helper.dart'; +import '../../models/mensaje.dart'; + +class MensajesDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('mensajes', orderBy: 'timestamp ASC'); + return rows.map(Mensaje.fromMap).toList(); + } + + Future insert(Mensaje m) async { + final db = await _db.db; + return db.insert('mensajes', m.toMap()); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('mensajes', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('mensajes', where: 'sincronizado = 0'); + return rows.map(Mensaje.fromMap).toList(); + } +} diff --git a/lib/db/dao/nodos_dao.dart b/lib/db/dao/nodos_dao.dart new file mode 100644 index 0000000..fd1afa9 --- /dev/null +++ b/lib/db/dao/nodos_dao.dart @@ -0,0 +1,45 @@ +import '../database_helper.dart'; +import '../../models/nodo.dart'; + +class NodosDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('nodos', orderBy: 'nombre ASC'); + return rows.map(Nodo.fromMap).toList(); + } + + Future> 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 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 insert(Nodo n) async { + final db = await _db.db; + return db.insert('nodos', n.toMap()); + } + + Future update(Nodo n) async { + final db = await _db.db; + return db.update('nodos', n.toMap(), where: 'id = ?', whereArgs: [n.id]); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('nodos', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('nodos', where: 'sincronizado = 0'); + return rows.map(Nodo.fromMap).toList(); + } +} diff --git a/lib/db/dao/puertas_dao.dart b/lib/db/dao/puertas_dao.dart new file mode 100644 index 0000000..36ebb5f --- /dev/null +++ b/lib/db/dao/puertas_dao.dart @@ -0,0 +1,49 @@ +import '../database_helper.dart'; +import '../../models/puerta.dart'; + +class PuertasDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('puertas', orderBy: 'nombre ASC'); + return rows.map(Puerta.fromMap).toList(); + } + + Future 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 insert(Puerta p) async { + final db = await _db.db; + return db.insert('puertas', p.toMap()); + } + + Future update(Puerta p) async { + final db = await _db.db; + return db.update('puertas', p.toMap(), where: 'id = ?', whereArgs: [p.id]); + } + + Future 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 delete(int id) async { + final db = await _db.db; + return db.delete('puertas', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('puertas', where: 'sincronizado = 0'); + return rows.map(Puerta.fromMap).toList(); + } +} diff --git a/lib/db/dao/sesiones_dao.dart b/lib/db/dao/sesiones_dao.dart new file mode 100644 index 0000000..8eb9160 --- /dev/null +++ b/lib/db/dao/sesiones_dao.dart @@ -0,0 +1,47 @@ +import '../database_helper.dart'; +import '../../models/sesion.dart'; + +class SesionesDao { + final _db = DatabaseHelper.instance; + + Future> 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 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 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 cerrar(int id) async { + final db = await _db.db; + return db.update( + 'sesiones', + {'timestamp_fin': DateTime.now().toIso8601String()}, + where: 'id = ?', + whereArgs: [id], + ); + } +} diff --git a/lib/db/dao/sync_log_dao.dart b/lib/db/dao/sync_log_dao.dart new file mode 100644 index 0000000..5202be4 --- /dev/null +++ b/lib/db/dao/sync_log_dao.dart @@ -0,0 +1,28 @@ +import '../database_helper.dart'; + +class SyncLogDao { + final _db = DatabaseHelper.instance; + + Future 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>> getRecientes({int limit = 20}) async { + final db = await _db.db; + return db.query( + 'sync_log', + orderBy: 'timestamp DESC', + limit: limit, + ); + } +} diff --git a/lib/db/dao/usuarios_dao.dart b/lib/db/dao/usuarios_dao.dart new file mode 100644 index 0000000..1f511c1 --- /dev/null +++ b/lib/db/dao/usuarios_dao.dart @@ -0,0 +1,49 @@ +import '../database_helper.dart'; +import '../../models/usuario.dart'; + +class UsuariosDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('usuarios', orderBy: 'nombre ASC'); + return rows.map(Usuario.fromMap).toList(); + } + + Future 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 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 insert(Usuario u) async { + final db = await _db.db; + return db.insert('usuarios', u.toMap()); + } + + Future update(Usuario u) async { + final db = await _db.db; + return db.update('usuarios', u.toMap(), where: 'id = ?', whereArgs: [u.id]); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('usuarios', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('usuarios', where: 'sincronizado = 0'); + return rows.map(Usuario.fromMap).toList(); + } +} diff --git a/lib/db/dao/zonas_dao.dart b/lib/db/dao/zonas_dao.dart new file mode 100644 index 0000000..1e46694 --- /dev/null +++ b/lib/db/dao/zonas_dao.dart @@ -0,0 +1,39 @@ +import '../database_helper.dart'; +import '../../models/zona.dart'; + +class ZonasDao { + final _db = DatabaseHelper.instance; + + Future> getAll() async { + final db = await _db.db; + final rows = await db.query('zonas', orderBy: 'codigo ASC'); + return rows.map(Zona.fromMap).toList(); + } + + Future 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 insert(Zona z) async { + final db = await _db.db; + return db.insert('zonas', z.toMap()); + } + + Future update(Zona z) async { + final db = await _db.db; + return db.update('zonas', z.toMap(), where: 'id = ?', whereArgs: [z.id]); + } + + Future delete(int id) async { + final db = await _db.db; + return db.delete('zonas', where: 'id = ?', whereArgs: [id]); + } + + Future> getPendientes() async { + final db = await _db.db; + final rows = await db.query('zonas', where: 'sincronizado = 0'); + return rows.map(Zona.fromMap).toList(); + } +} diff --git a/lib/db/database_helper.dart b/lib/db/database_helper.dart new file mode 100644 index 0000000..53a7d9d --- /dev/null +++ b/lib/db/database_helper.dart @@ -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 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 _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 _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 _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); + } + } +} diff --git a/lib/main.dart b/lib/main.dart index 0533052..ef67552 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -1,12 +1,16 @@ +import 'dart:convert'; +import 'package:crypto/crypto.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:google_fonts/google_fonts.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import 'theme.dart'; import 'main_page.dart'; import 'pages/register_page.dart'; import 'widgets/app_menu_button.dart'; -void main() { +void main() async { + WidgetsFlutterBinding.ensureInitialized(); runApp(const MyApp()); } @@ -44,6 +48,8 @@ class _LoginPageState extends State { final List _focusNodes = List.generate(_codeLength, (_) => FocusNode()); + bool _cargando = false; + @override void dispose() { for (final c in _controllers) c.dispose(); @@ -69,18 +75,52 @@ class _LoginPageState extends State { } } - void _handleLogin() { - final filled = _controllers.where((c) => c.text.isNotEmpty).length; - if (filled < 4) { + // PIN inicial por defecto: 123456 — el usuario puede cambiarlo desde ajustes + static const _keyPinHash = 'local_pin_hash'; + static const _defaultPin = '123456'; + + static String _hashPin(String pin) => + sha256.convert(utf8.encode(pin)).toString(); + + Future _handleLogin() async { + final pin = _controllers.map((c) => c.text).join(); + if (pin.length < 4) { ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text('Introduce al menos 4 dígitos')), ); return; } - Navigator.pushReplacement( - context, - MaterialPageRoute(builder: (_) => const MainPage(initialIndex: 0)), - ); + + setState(() => _cargando = true); + + try { + final prefs = await SharedPreferences.getInstance(); + // Si aún no hay PIN guardado, usamos el por defecto + final storedHash = prefs.getString(_keyPinHash) ?? + _hashPin(_defaultPin); + + if (_hashPin(pin) != storedHash) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('PIN incorrecto')), + ); + _clearCode(); + return; + } + + if (!mounted) return; + Navigator.pushReplacement( + context, + MaterialPageRoute(builder: (_) => const MainPage(initialIndex: 0)), + ); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Error: $e')), + ); + } finally { + if (mounted) setState(() => _cargando = false); + } } void _clearCode() { @@ -176,7 +216,7 @@ class _LoginPageState extends State { SizedBox( width: double.infinity, child: ElevatedButton( - onPressed: filled >= 4 ? _handleLogin : null, + onPressed: (filled >= 4 && !_cargando) ? _handleLogin : null, style: ElevatedButton.styleFrom( primary: AppColors.primary, onPrimary: AppColors.primaryContainer, @@ -185,14 +225,20 @@ class _LoginPageState extends State { borderRadius: BorderRadius.circular(12)), elevation: 0, ), - child: Text('INGRESAR', - style: GoogleFonts.inter( - fontSize: 14, - fontWeight: FontWeight.bold, - letterSpacing: 1.5, - color: filled >= 4 - ? AppColors.primaryContainer - : AppColors.onSurfaceVariant)), + child: _cargando + ? const SizedBox( + width: 20, height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: AppColors.primaryContainer)) + : Text('INGRESAR', + style: GoogleFonts.inter( + fontSize: 14, + fontWeight: FontWeight.bold, + letterSpacing: 1.5, + color: filled >= 4 + ? AppColors.primaryContainer + : AppColors.onSurfaceVariant)), ), ), const SizedBox(height: 12), diff --git a/lib/models/acceso.dart b/lib/models/acceso.dart new file mode 100644 index 0000000..fe72e76 --- /dev/null +++ b/lib/models/acceso.dart @@ -0,0 +1,39 @@ +class Acceso { + final int id; + final int usuarioId; + final int puertaId; + final String timestamp; + final bool autorizado; + final String metodo; // pin / remoto / biometrico + final bool sincronizado; + + const Acceso({ + required this.id, + required this.usuarioId, + required this.puertaId, + required this.timestamp, + this.autorizado = false, + this.metodo = 'pin', + this.sincronizado = false, + }); + + factory Acceso.fromMap(Map m) => Acceso( + id: m['id'] as int, + usuarioId: m['usuario_id'] as int, + puertaId: m['puerta_id'] as int, + timestamp: m['timestamp'] as String, + autorizado: (m['autorizado'] as int) == 1, + metodo: m['metodo'] as String, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'usuario_id': usuarioId, + 'puerta_id': puertaId, + 'timestamp': timestamp, + 'autorizado': autorizado ? 1 : 0, + 'metodo': metodo, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/alarma.dart b/lib/models/alarma.dart new file mode 100644 index 0000000..214ae6b --- /dev/null +++ b/lib/models/alarma.dart @@ -0,0 +1,60 @@ +class Alarma { + final int id; + final int zonaId; + final String tipo; // intrusion / humo / movimiento / acceso + final int severidad; // 1–5 + final String timestamp; + final String estado; // activa / silenciada / resuelta + final int? resueltoPor; + final String? notas; + final bool sincronizado; + + const Alarma({ + required this.id, + required this.zonaId, + required this.tipo, + required this.severidad, + required this.timestamp, + this.estado = 'activa', + this.resueltoPor, + this.notas, + this.sincronizado = false, + }); + + factory Alarma.fromMap(Map m) => Alarma( + id: m['id'] as int, + zonaId: m['zona_id'] as int, + tipo: m['tipo'] as String, + severidad: m['severidad'] as int, + timestamp: m['timestamp'] as String, + estado: m['estado'] as String, + resueltoPor: m['resuelto_por'] as int?, + notas: m['notas'] as String?, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'zona_id': zonaId, + 'tipo': tipo, + 'severidad': severidad, + 'timestamp': timestamp, + 'estado': estado, + 'resuelto_por': resueltoPor, + 'notas': notas, + 'sincronizado': sincronizado ? 1 : 0, + }; + + Alarma copyWith({String? estado, int? resueltoPor, String? notas, bool? sincronizado}) => + Alarma( + id: id, + zonaId: zonaId, + tipo: tipo, + severidad: severidad, + timestamp: timestamp, + estado: estado ?? this.estado, + resueltoPor: resueltoPor ?? this.resueltoPor, + notas: notas ?? this.notas, + sincronizado: sincronizado ?? this.sincronizado, + ); +} diff --git a/lib/models/banner_item.dart b/lib/models/banner_item.dart new file mode 100644 index 0000000..745de84 --- /dev/null +++ b/lib/models/banner_item.dart @@ -0,0 +1,39 @@ +class BannerItem { + final int id; + final String badge; + final String titulo; + final String? subtitulo; + final int orden; + final bool activo; + final bool sincronizado; + + const BannerItem({ + required this.id, + required this.badge, + required this.titulo, + this.subtitulo, + this.orden = 0, + this.activo = true, + this.sincronizado = false, + }); + + factory BannerItem.fromMap(Map m) => BannerItem( + id: m['id'] as int, + badge: m['badge'] as String, + titulo: m['titulo'] as String, + subtitulo: m['subtitulo'] as String?, + orden: m['orden'] as int, + activo: (m['activo'] as int) == 1, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'badge': badge, + 'titulo': titulo, + 'subtitulo': subtitulo, + 'orden': orden, + 'activo': activo ? 1 : 0, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/evento.dart b/lib/models/evento.dart new file mode 100644 index 0000000..f71ee30 --- /dev/null +++ b/lib/models/evento.dart @@ -0,0 +1,43 @@ +class Evento { + final int id; + final String tipo; // alerta / noticia / notificacion / general + final String titulo; + final String? descripcion; + final String hora; + final String timestamp; + final bool leido; + final bool sincronizado; + + const Evento({ + required this.id, + required this.tipo, + required this.titulo, + this.descripcion, + required this.hora, + required this.timestamp, + this.leido = false, + this.sincronizado = false, + }); + + factory Evento.fromMap(Map m) => Evento( + id: m['id'] as int, + tipo: m['tipo'] as String, + titulo: m['titulo'] as String, + descripcion: m['descripcion'] as String?, + hora: m['hora'] as String, + timestamp: m['timestamp'] as String, + leido: (m['leido'] as int) == 1, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'tipo': tipo, + 'titulo': titulo, + 'descripcion': descripcion, + 'hora': hora, + 'timestamp': timestamp, + 'leido': leido ? 1 : 0, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/mensaje.dart b/lib/models/mensaje.dart new file mode 100644 index 0000000..3b1b633 --- /dev/null +++ b/lib/models/mensaje.dart @@ -0,0 +1,35 @@ +class Mensaje { + final int? id; + final String texto; + final bool esMio; + final String hora; + final String timestamp; + final bool sincronizado; + + const Mensaje({ + this.id, + required this.texto, + required this.esMio, + required this.hora, + required this.timestamp, + this.sincronizado = false, + }); + + factory Mensaje.fromMap(Map m) => Mensaje( + id: m['id'] as int?, + texto: m['texto'] as String, + esMio: (m['es_mio'] as int) == 1, + hora: m['hora'] as String, + timestamp: m['timestamp'] as String, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + if (id != null) 'id': id, + 'texto': texto, + 'es_mio': esMio ? 1 : 0, + 'hora': hora, + 'timestamp': timestamp, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/nodo.dart b/lib/models/nodo.dart new file mode 100644 index 0000000..44106d4 --- /dev/null +++ b/lib/models/nodo.dart @@ -0,0 +1,39 @@ +class Nodo { + final int id; + final int zonaId; + final String tipo; // camara / sensor_movimiento / sensor_humo / control_acceso + final String nombre; + final bool activo; + final String? ultimaSenal; + final bool sincronizado; + + const Nodo({ + required this.id, + required this.zonaId, + required this.tipo, + required this.nombre, + this.activo = true, + this.ultimaSenal, + this.sincronizado = false, + }); + + factory Nodo.fromMap(Map m) => Nodo( + id: m['id'] as int, + zonaId: m['zona_id'] as int, + tipo: m['tipo'] as String, + nombre: m['nombre'] as String, + activo: (m['activo'] as int) == 1, + ultimaSenal: m['ultima_senal'] as String?, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'zona_id': zonaId, + 'tipo': tipo, + 'nombre': nombre, + 'activo': activo ? 1 : 0, + 'ultima_senal': ultimaSenal, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/puerta.dart b/lib/models/puerta.dart new file mode 100644 index 0000000..aadf788 --- /dev/null +++ b/lib/models/puerta.dart @@ -0,0 +1,44 @@ +class Puerta { + final int id; + final int zonaId; + final String nombre; + final String codigo; + final bool bloqueada; + final bool sincronizado; + + const Puerta({ + required this.id, + required this.zonaId, + required this.nombre, + required this.codigo, + this.bloqueada = true, + this.sincronizado = false, + }); + + factory Puerta.fromMap(Map m) => Puerta( + id: m['id'] as int, + zonaId: m['zona_id'] as int, + nombre: m['nombre'] as String, + codigo: m['codigo'] as String, + bloqueada: (m['bloqueada'] as int) == 1, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'zona_id': zonaId, + 'nombre': nombre, + 'codigo': codigo, + 'bloqueada': bloqueada ? 1 : 0, + 'sincronizado': sincronizado ? 1 : 0, + }; + + Puerta copyWith({bool? bloqueada, bool? sincronizado}) => Puerta( + id: id, + zonaId: zonaId, + nombre: nombre, + codigo: codigo, + bloqueada: bloqueada ?? this.bloqueada, + sincronizado: sincronizado ?? this.sincronizado, + ); +} diff --git a/lib/models/sesion.dart b/lib/models/sesion.dart new file mode 100644 index 0000000..2b8084f --- /dev/null +++ b/lib/models/sesion.dart @@ -0,0 +1,33 @@ +class Sesion { + final int? id; + final int usuarioId; + final String timestampInicio; + final String? timestampFin; + final String? dispositivo; + + const Sesion({ + this.id, + required this.usuarioId, + required this.timestampInicio, + this.timestampFin, + this.dispositivo, + }); + + factory Sesion.fromMap(Map m) => Sesion( + id: m['id'] as int?, + usuarioId: m['usuario_id'] as int, + timestampInicio: m['timestamp_inicio'] as String, + timestampFin: m['timestamp_fin'] as String?, + dispositivo: m['dispositivo'] as String?, + ); + + Map toMap() => { + if (id != null) 'id': id, + 'usuario_id': usuarioId, + 'timestamp_inicio': timestampInicio, + 'timestamp_fin': timestampFin, + 'dispositivo': dispositivo, + }; + + bool get activa => timestampFin == null; +} diff --git a/lib/models/usuario.dart b/lib/models/usuario.dart new file mode 100644 index 0000000..395b978 --- /dev/null +++ b/lib/models/usuario.dart @@ -0,0 +1,51 @@ +class Usuario { + final int id; + final String nombre; + final String iniciales; + final int nivelAcceso; + final String pinHash; + final String? areas; + final String? fechaInicio; + final String? fechaFin; + final bool activo; + final bool sincronizado; + + const Usuario({ + required this.id, + required this.nombre, + required this.iniciales, + required this.nivelAcceso, + required this.pinHash, + this.areas, + this.fechaInicio, + this.fechaFin, + this.activo = true, + this.sincronizado = false, + }); + + factory Usuario.fromMap(Map m) => Usuario( + id: m['id'] as int, + nombre: m['nombre'] as String, + iniciales: m['iniciales'] as String, + nivelAcceso: m['nivel_acceso'] as int, + pinHash: m['pin_hash'] as String, + areas: m['areas'] as String?, + fechaInicio: m['fecha_inicio'] as String?, + fechaFin: m['fecha_fin'] as String?, + activo: (m['activo'] as int) == 1, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'nombre': nombre, + 'iniciales': iniciales, + 'nivel_acceso': nivelAcceso, + 'pin_hash': pinHash, + 'areas': areas, + 'fecha_inicio': fechaInicio, + 'fecha_fin': fechaFin, + 'activo': activo ? 1 : 0, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/models/zona.dart b/lib/models/zona.dart new file mode 100644 index 0000000..a51e9a7 --- /dev/null +++ b/lib/models/zona.dart @@ -0,0 +1,35 @@ +class Zona { + final int id; + final String codigo; + final String nombre; + final String? descripcion; + final String estado; // segura / alerta / inactiva + final bool sincronizado; + + const Zona({ + required this.id, + required this.codigo, + required this.nombre, + this.descripcion, + this.estado = 'segura', + this.sincronizado = false, + }); + + factory Zona.fromMap(Map m) => Zona( + id: m['id'] as int, + codigo: m['codigo'] as String, + nombre: m['nombre'] as String, + descripcion: m['descripcion'] as String?, + estado: m['estado'] as String, + sincronizado: (m['sincronizado'] as int) == 1, + ); + + Map toMap() => { + 'id': id, + 'codigo': codigo, + 'nombre': nombre, + 'descripcion': descripcion, + 'estado': estado, + 'sincronizado': sincronizado ? 1 : 0, + }; +} diff --git a/lib/pages/control_acceso_page.dart b/lib/pages/control_acceso_page.dart index 6180a50..59bc24f 100644 --- a/lib/pages/control_acceso_page.dart +++ b/lib/pages/control_acceso_page.dart @@ -18,6 +18,7 @@ class _ControlAccesoPageState extends State { @override Widget build(BuildContext context) { return SingleChildScrollView( + primary: false, padding: const EdgeInsets.fromLTRB(24, 24, 24, 24), child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/pages/inicio_page.dart b/lib/pages/inicio_page.dart index d931407..ef1ed54 100644 --- a/lib/pages/inicio_page.dart +++ b/lib/pages/inicio_page.dart @@ -156,6 +156,7 @@ class _InicioPageState extends State return Stack( children: [ SingleChildScrollView( + primary: false, padding: const EdgeInsets.fromLTRB(20, 20, 20, 88), child: Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/pages/monitoreo_alarma_page.dart b/lib/pages/monitoreo_alarma_page.dart index 7e6a399..aa3c6d6 100644 --- a/lib/pages/monitoreo_alarma_page.dart +++ b/lib/pages/monitoreo_alarma_page.dart @@ -51,14 +51,13 @@ class _MonitoreoAlarmaPageState extends State @override Widget build(BuildContext context) { return SingleChildScrollView( + primary: false, padding: const EdgeInsets.fromLTRB(24, 24, 24, 24), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ _statusBento(), const SizedBox(height: 32), - _frequencyChart(), - const SizedBox(height: 32), _criticalEvents(), const SizedBox(height: 32), _eventLog(), @@ -149,78 +148,6 @@ class _MonitoreoAlarmaPageState extends State ); // ── Gráfico de frecuencia ─────────────────────────────────────────────────── - Widget _frequencyChart() { - const maxH = 110.0; - final fracciones = [0.40, 0.65, 0.95, 0.55, 0.30, 0.45, 0.20]; - final dias = ['LUN', 'MAR', 'MIÉ', 'JUE', 'VIE', 'SÁB', 'DOM']; - const picoIdx = 2; - - return Container( - padding: const EdgeInsets.all(24), - decoration: BoxDecoration(color: AppColors.surfaceLow, - borderRadius: BorderRadius.circular(12)), - child: Column(children: [ - Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ - Text('FRECUENCIA DE ALARMAS', - style: appHeadline(size: 13, spacing: 1.5)), - Container( - padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4), - decoration: BoxDecoration(color: AppColors.secondaryContainer, - borderRadius: BorderRadius.circular(99)), - child: Text('TENDENCIA SEMANAL', - style: appLabel(size: 10, weight: FontWeight.bold, - color: AppColors.onSecondaryContainer)), - ), - ]), - const SizedBox(height: 24), - SizedBox( - height: maxH + 20, - child: Row( - crossAxisAlignment: CrossAxisAlignment.end, - children: List.generate(fracciones.length, (i) { - final isPico = i == picoIdx; - return Expanded( - child: Padding( - padding: const EdgeInsets.symmetric(horizontal: 3), - child: Column( - mainAxisAlignment: MainAxisAlignment.end, - children: [ - if (isPico) - Padding( - padding: const EdgeInsets.only(bottom: 4), - child: Text('PICO', style: appLabel( - size: 9, weight: FontWeight.bold, - color: AppColors.error)), - ), - Container( - height: maxH * fracciones[i], - decoration: BoxDecoration( - color: isPico - ? AppColors.error.withOpacity(0.4) - : AppColors.primary.withOpacity(0.2), - borderRadius: const BorderRadius.vertical( - top: Radius.circular(4)), - ), - ), - ], - ), - ), - ); - }), - ), - ), - const SizedBox(height: 16), - Row( - mainAxisAlignment: MainAxisAlignment.spaceBetween, - children: List.generate(dias.length, (i) => Text(dias[i], - style: appLabel(size: 10, - weight: i == picoIdx ? FontWeight.bold : FontWeight.normal, - color: i == picoIdx ? AppColors.onSurface : AppColors.onSurfaceVariant))), - ), - ]), - ); - } - // ── Eventos críticos ──────────────────────────────────────────────────────── Widget _criticalEvents() => Column( crossAxisAlignment: CrossAxisAlignment.start, diff --git a/lib/pages/perfil_usuario_page.dart b/lib/pages/perfil_usuario_page.dart index 37cbc98..f8bea8d 100644 --- a/lib/pages/perfil_usuario_page.dart +++ b/lib/pages/perfil_usuario_page.dart @@ -1,6 +1,9 @@ import 'package:flutter/material.dart'; +import 'package:shared_preferences/shared_preferences.dart'; import '../theme.dart'; +import '../main.dart' show LoginPage; import 'settings_page.dart'; +import 'seguridad_page.dart'; class PerfilUsuarioPage extends StatelessWidget { const PerfilUsuarioPage({Key? key}) : super(key: key); @@ -8,6 +11,7 @@ class PerfilUsuarioPage extends StatelessWidget { @override Widget build(BuildContext context) { return SingleChildScrollView( + primary: false, padding: const EdgeInsets.fromLTRB(24, 24, 24, 24), child: Column( crossAxisAlignment: CrossAxisAlignment.start, @@ -139,7 +143,10 @@ class PerfilUsuarioPage extends StatelessWidget { }), const Divider(color: AppColors.outlineVariant, height: 1), _opcionItem(Icons.shield_outlined, 'Seguridad', - 'Cambiar PIN de acceso', () {}), + 'Cambiar PIN de acceso', () { + Navigator.push(context, + MaterialPageRoute(builder: (_) => const SeguridadPage())); + }), const Divider(color: AppColors.outlineVariant, height: 1), _opcionItem(Icons.history, 'Historial de sesiones', 'Últimos accesos al sistema', () {}), @@ -183,9 +190,7 @@ class PerfilUsuarioPage extends StatelessWidget { Widget _botonCerrarSesion(BuildContext context) => SizedBox( width: double.infinity, child: OutlinedButton.icon( - onPressed: () { - Navigator.of(context).popUntil((r) => r.isFirst); - }, + onPressed: () => _cerrarSesion(context), icon: const Icon(Icons.logout, color: AppColors.error, size: 18), label: Text('Cerrar Sesión', style: appLabel(size: 14, weight: FontWeight.bold, @@ -198,4 +203,41 @@ class PerfilUsuarioPage extends StatelessWidget { ), ), ); + + Future _cerrarSesion(BuildContext context) async { + final confirmar = await showDialog( + context: context, + builder: (_) => AlertDialog( + backgroundColor: AppColors.surfaceHigh, + title: Text('Cerrar sesión', + style: appHeadline(size: 16, weight: FontWeight.w700)), + content: Text('¿Seguro que deseas cerrar sesión?', + 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('Cerrar sesión', + style: appLabel(size: 13, weight: FontWeight.bold, + color: AppColors.error)), + ), + ], + ), + ); + + if (confirmar != true) return; + + // Limpia el flag de auto-login si se implementa en el futuro + final prefs = await SharedPreferences.getInstance(); + await prefs.remove('autologin'); + + Navigator.of(context).pushAndRemoveUntil( + MaterialPageRoute(builder: (_) => const LoginPage()), + (_) => false, + ); + } } diff --git a/lib/pages/seguridad_page.dart b/lib/pages/seguridad_page.dart new file mode 100644 index 0000000..44515a6 --- /dev/null +++ b/lib/pages/seguridad_page.dart @@ -0,0 +1,323 @@ +import 'dart:convert'; +import 'package:crypto/crypto.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import '../theme.dart'; + +class SeguridadPage extends StatefulWidget { + const SeguridadPage({Key? key}) : super(key: key); + + @override + State createState() => _SeguridadPageState(); +} + +class _SeguridadPageState extends State { + static const _keyPinHash = 'local_pin_hash'; + static const _defaultPin = '123456'; + static const _pinLen = 6; + + // Campos del PIN + final List _ctrlActual = + List.generate(_pinLen, (_) => TextEditingController()); + final List _ctrlNuevo = + List.generate(_pinLen, (_) => TextEditingController()); + final List _ctrlConfirm = + List.generate(_pinLen, (_) => TextEditingController()); + + final List _focusActual = + List.generate(_pinLen, (_) => FocusNode()); + final List _focusNuevo = + List.generate(_pinLen, (_) => FocusNode()); + final List _focusConfirm = + List.generate(_pinLen, (_) => FocusNode()); + + bool _guardando = false; + + @override + void dispose() { + for (final c in [..._ctrlActual, ..._ctrlNuevo, ..._ctrlConfirm]) { + c.dispose(); + } + for (final f in [..._focusActual, ..._focusNuevo, ..._focusConfirm]) { + f.dispose(); + } + super.dispose(); + } + + String _pinDe(List ctrls) => + ctrls.map((c) => c.text).join(); + + String _hash(String pin) => + sha256.convert(utf8.encode(pin)).toString(); + + void _onDigit(List ctrls, + List focus, int i, String v) { + if (v.isNotEmpty && i < _pinLen - 1) focus[i + 1].requestFocus(); + setState(() {}); + } + + void _onKey(List ctrls, + List focus, int i, RawKeyEvent e) { + if (e is RawKeyDownEvent && + e.logicalKey == LogicalKeyboardKey.backspace && + ctrls[i].text.isEmpty && + i > 0) { + focus[i - 1].requestFocus(); + ctrls[i - 1].clear(); + setState(() {}); + } + } + + void _limpiarTodo() { + for (final c in [..._ctrlActual, ..._ctrlNuevo, ..._ctrlConfirm]) { + c.clear(); + } + _focusActual[0].requestFocus(); + setState(() {}); + } + + Future _guardar() async { + final actual = _pinDe(_ctrlActual); + final nuevo = _pinDe(_ctrlNuevo); + final confirma = _pinDe(_ctrlConfirm); + + if (actual.length < 4 || nuevo.length < 4 || confirma.length < 4) { + _snack('Completa todos los campos (mínimo 4 dígitos)'); + return; + } + if (nuevo != confirma) { + _snack('El nuevo PIN y la confirmación no coinciden'); + return; + } + if (nuevo == actual) { + _snack('El nuevo PIN debe ser diferente al actual'); + return; + } + + setState(() => _guardando = true); + + try { + final prefs = await SharedPreferences.getInstance(); + final hashGuardado = + prefs.getString(_keyPinHash) ?? _hash(_defaultPin); + + if (_hash(actual) != hashGuardado) { + _snack('El PIN actual es incorrecto'); + _ctrlActual.forEach((c) => c.clear()); + _focusActual[0].requestFocus(); + return; + } + + await prefs.setString(_keyPinHash, _hash(nuevo)); + _snack('PIN actualizado correctamente', esError: false); + _limpiarTodo(); + } finally { + if (mounted) setState(() => _guardando = false); + } + } + + void _snack(String msg, {bool esError = true}) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg), + backgroundColor: + esError ? AppColors.error : AppColors.primary, + )); + } + + // ── Build ────────────────────────────────────────────────────────────────── + @override + Widget build(BuildContext context) { + final todosCompletos = _pinDe(_ctrlActual).length >= 4 && + _pinDe(_ctrlNuevo).length >= 4 && + _pinDe(_ctrlConfirm).length >= 4; + + return Scaffold( + backgroundColor: AppColors.surfaceLowest, + appBar: AppBar( + backgroundColor: AppColors.surfaceLow, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, + color: AppColors.onSurface, size: 18), + onPressed: () => Navigator.pop(context), + ), + title: Text('SEGURIDAD', + style: appHeadline(size: 16, weight: FontWeight.w800, + color: AppColors.primary, spacing: 2.0)), + ), + body: SafeArea( + child: SingleChildScrollView( + primary: false, + padding: const EdgeInsets.all(24), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + // ── Info ──────────────────────────────────────────────────── + Container( + width: double.infinity, + padding: const EdgeInsets.all(16), + decoration: BoxDecoration( + color: AppColors.primaryContainer.withOpacity(0.3), + borderRadius: BorderRadius.circular(12), + border: Border.all( + color: AppColors.primary.withOpacity(0.2), width: 1), + ), + child: Row(children: [ + const Icon(Icons.info_outline, + color: AppColors.primary, size: 18), + const SizedBox(width: 12), + Expanded( + child: Text( + 'El PIN es la clave de acceso local a la app. ' + 'Debe tener entre 4 y 6 dígitos.', + style: appLabel(size: 12, color: AppColors.primary), + ), + ), + ]), + ), + const SizedBox(height: 32), + + // ── PIN actual ────────────────────────────────────────────── + _seccionPin( + label: 'PIN ACTUAL', + ctrls: _ctrlActual, + focus: _focusActual, + ), + const SizedBox(height: 28), + + // ── Nuevo PIN ─────────────────────────────────────────────── + _seccionPin( + label: 'NUEVO PIN', + ctrls: _ctrlNuevo, + focus: _focusNuevo, + ), + const SizedBox(height: 28), + + // ── Confirmar PIN ─────────────────────────────────────────── + _seccionPin( + label: 'CONFIRMAR NUEVO PIN', + ctrls: _ctrlConfirm, + focus: _focusConfirm, + ), + const SizedBox(height: 40), + + // ── Botón guardar ─────────────────────────────────────────── + SizedBox( + width: double.infinity, + child: ElevatedButton( + onPressed: (todosCompletos && !_guardando) + ? _guardar + : null, + style: ElevatedButton.styleFrom( + primary: AppColors.primary, + onPrimary: AppColors.primaryContainer, + padding: const EdgeInsets.symmetric(vertical: 16), + shape: RoundedRectangleBorder( + borderRadius: BorderRadius.circular(12)), + elevation: 0, + ), + child: _guardando + ? const SizedBox( + width: 20, height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, + color: AppColors.primaryContainer)) + : Text('GUARDAR NUEVO PIN', + style: appLabel( + size: 13, + weight: FontWeight.bold, + color: todosCompletos + ? AppColors.primaryContainer + : AppColors.onSurfaceVariant, + spacing: 1.5)), + ), + ), + const SizedBox(height: 12), + + // ── Limpiar ───────────────────────────────────────────────── + SizedBox( + width: double.infinity, + child: TextButton.icon( + onPressed: _limpiarTodo, + icon: const Icon(Icons.backspace_outlined, + size: 16, color: AppColors.onSurfaceVariant), + label: Text('Limpiar campos', + style: appLabel( + size: 13, color: AppColors.onSurfaceVariant)), + ), + ), + ], + ), + ), + ), + ); + } + + // ── Sección de cajas PIN ─────────────────────────────────────────────────── + Widget _seccionPin({ + required String label, + required List ctrls, + required List focus, + }) => + Column(crossAxisAlignment: CrossAxisAlignment.start, children: [ + Text(label, + style: appLabel( + size: 10, + weight: FontWeight.bold, + color: AppColors.onSurfaceVariant, + spacing: 2.0)), + const SizedBox(height: 14), + Row( + mainAxisAlignment: MainAxisAlignment.start, + children: List.generate( + _pinLen, + (i) => Padding( + padding: const EdgeInsets.only(right: 10), + child: RawKeyboardListener( + focusNode: FocusNode(), + onKey: (e) => _onKey(ctrls, focus, i, e), + child: SizedBox( + width: 44, + child: TextFormField( + controller: ctrls[i], + focusNode: focus[i], + textAlign: TextAlign.center, + keyboardType: TextInputType.number, + obscureText: true, + maxLength: 1, + inputFormatters: [FilteringTextInputFormatter.digitsOnly], + style: appHeadline( + size: 20, color: AppColors.primary), + decoration: InputDecoration( + counterText: '', + contentPadding: + const EdgeInsets.symmetric(vertical: 14), + enabledBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: BorderSide( + color: ctrls[i].text.isNotEmpty + ? AppColors.primary + : AppColors.outlineVariant, + width: ctrls[i].text.isNotEmpty ? 2 : 1, + ), + ), + focusedBorder: OutlineInputBorder( + borderRadius: BorderRadius.circular(8), + borderSide: const BorderSide( + color: AppColors.primary, width: 2), + ), + filled: true, + fillColor: ctrls[i].text.isNotEmpty + ? AppColors.primaryContainer.withOpacity(0.3) + : AppColors.surfaceHighest, + ), + onChanged: (v) => _onDigit(ctrls, focus, i, v), + ), + ), + ), + ), + ), + ), + ]); +} diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 6fa60e8..ba4d5df 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -1,5 +1,11 @@ +import 'dart:io'; import 'package:flutter/material.dart'; -import '../widgets/app_menu_button.dart'; +import 'package:sqflite/sqflite.dart'; +import 'package:sqflite_common_ffi/sqflite_ffi.dart'; +import 'package:path/path.dart' as p; +import '../theme.dart'; +import '../db/database_helper.dart'; +import '../services/sincronizador.dart'; class SettingsPage extends StatefulWidget { const SettingsPage({Key? key}) : super(key: key); @@ -9,230 +15,251 @@ class SettingsPage extends StatefulWidget { } class _SettingsPageState extends State { - final _formKey = GlobalKey(); + bool _notificaciones = true; + bool _sonido = true; + bool _vibracion = true; - // Notificaciones - bool _soundEnabled = true; - bool _vibrationEnabled = true; - bool _notificationsEnabled = true; - double _volume = 0.8; - - // Alarma - int _snoozeMinutes = 5; - int _repeatTimes = 3; - String _selectedTone = 'Predeterminado'; - final List _tones = [ - 'Predeterminado', - 'Clásico', - 'Digital', - 'Suave', - 'Urgente', - ]; - - // Cuenta - final _nameController = TextEditingController(text: 'Usuario'); - final _emailController = TextEditingController(text: 'usuario@email.com'); - - @override - void dispose() { - _nameController.dispose(); - _emailController.dispose(); - super.dispose(); - } - - void _saveSettings() { - if (_formKey.currentState!.validate()) { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Configuración guardada')), - ); - } - } + bool _iniciandoBd = false; + bool _sincronizando = false; + // ── Build ────────────────────────────────────────────────────────────────── @override Widget build(BuildContext context) { return Scaffold( + backgroundColor: AppColors.surfaceLowest, appBar: AppBar( - title: const Text('Configuración'), - actions: [ - TextButton( - onPressed: _saveSettings, - child: const Text('Guardar', style: TextStyle(color: Colors.white)), - ), - const AppMenuButton(), - ], - ), - body: Form( - key: _formKey, - child: ListView( - children: [ - _buildSectionHeader('Cuenta'), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: TextFormField( - controller: _nameController, - decoration: const InputDecoration( - labelText: 'Nombre', - prefixIcon: Icon(Icons.person), - border: OutlineInputBorder(), - ), - validator: (value) { - if (value == null || value.isEmpty) { - return 'El nombre no puede estar vacío'; - } - return null; - }, - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: TextFormField( - controller: _emailController, - keyboardType: TextInputType.emailAddress, - decoration: const InputDecoration( - labelText: 'Email', - prefixIcon: Icon(Icons.email), - border: OutlineInputBorder(), - ), - validator: (value) { - if (value == null || !value.contains('@')) { - return 'Email no válido'; - } - return null; - }, - ), - ), - _buildSectionHeader('Notificaciones'), - SwitchListTile( - title: const Text('Notificaciones'), - subtitle: const Text('Activar alertas del sistema'), - secondary: const Icon(Icons.notifications), - value: _notificationsEnabled, - onChanged: (val) => setState(() => _notificationsEnabled = val), - ), - SwitchListTile( - title: const Text('Sonido'), - subtitle: const Text('Reproducir sonido al activar alarma'), - secondary: const Icon(Icons.volume_up), - value: _soundEnabled, - onChanged: (val) => setState(() => _soundEnabled = val), - ), - if (_soundEnabled) - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: Row( - children: [ - const Icon(Icons.volume_down, color: Colors.grey), - Expanded( - child: Slider( - value: _volume, - onChanged: (val) => setState(() => _volume = val), - ), - ), - const Icon(Icons.volume_up, color: Colors.grey), - ], - ), - ), - SwitchListTile( - title: const Text('Vibración'), - subtitle: const Text('Vibrar al activar alarma'), - secondary: const Icon(Icons.vibration), - value: _vibrationEnabled, - onChanged: (val) => setState(() => _vibrationEnabled = val), - ), - _buildSectionHeader('Alarma'), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: DropdownButtonFormField( - value: _selectedTone, - decoration: const InputDecoration( - labelText: 'Tono de alarma', - prefixIcon: Icon(Icons.music_note), - border: OutlineInputBorder(), - ), - items: _tones - .map((t) => DropdownMenuItem(value: t, child: Text(t))) - .toList(), - onChanged: (val) => setState(() => _selectedTone = val!), - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - const Icon(Icons.snooze, color: Colors.grey), - const SizedBox(width: 12), - const Text('Posponer (minutos):'), - const Spacer(), - DropdownButton( - value: _snoozeMinutes, - items: [1, 5, 10, 15, 30] - .map((m) => - DropdownMenuItem(value: m, child: Text('$m min'))) - .toList(), - onChanged: (val) => - setState(() => _snoozeMinutes = val!), - ), - ], - ), - ), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8), - child: Row( - children: [ - const Icon(Icons.repeat, color: Colors.grey), - const SizedBox(width: 12), - const Text('Repeticiones:'), - const Spacer(), - DropdownButton( - value: _repeatTimes, - items: [1, 2, 3, 5, 10] - .map((n) => - DropdownMenuItem(value: n, child: Text('$n veces'))) - .toList(), - onChanged: (val) => - setState(() => _repeatTimes = val!), - ), - ], - ), - ), - const SizedBox(height: 16), - Padding( - padding: const EdgeInsets.symmetric(horizontal: 16), - child: OutlinedButton.icon( - onPressed: () { - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Sesión cerrada')), - ); - Navigator.of(context).popUntil((route) => route.isFirst); - }, - icon: const Icon(Icons.logout, color: Colors.red), - label: const Text('Cerrar sesión', - style: TextStyle(color: Colors.red)), - style: OutlinedButton.styleFrom( - side: const BorderSide(color: Colors.red), - minimumSize: const Size(double.infinity, 50), - ), - ), - ), - const SizedBox(height: 24), - ], + backgroundColor: AppColors.surfaceLow, + elevation: 0, + leading: IconButton( + icon: const Icon(Icons.arrow_back_ios_new, + color: AppColors.onSurface, size: 18), + onPressed: () => Navigator.pop(context), ), + title: Text('CONFIGURACIÓN', + style: appHeadline(size: 16, weight: FontWeight.w800, + color: AppColors.primary, spacing: 2.0)), + ), + body: ListView( + padding: const EdgeInsets.symmetric(vertical: 8), + children: [ + // ── Notificaciones ─────────────────────────────────────────────── + _sectionHeader('NOTIFICACIONES'), + _switchItem( + icon: Icons.notifications_active, + titulo: 'Notificaciones', + subtitulo: 'Activar alertas del sistema', + value: _notificaciones, + onChanged: (v) => setState(() => _notificaciones = v), + ), + _divider(), + _switchItem( + icon: Icons.volume_up, + titulo: 'Sonido', + subtitulo: 'Reproducir sonido al activar alarma', + value: _sonido, + onChanged: (v) => setState(() => _sonido = v), + ), + _divider(), + _switchItem( + icon: Icons.vibration, + titulo: 'Vibración', + subtitulo: 'Vibrar al activar alarma', + value: _vibracion, + onChanged: (v) => setState(() => _vibracion = v), + ), + + // ── Sistema ────────────────────────────────────────────────────── + _sectionHeader('SISTEMA'), + _accionItem( + icon: Icons.storage, + iconColor: AppColors.secondary, + titulo: 'Inicializar base de datos', + subtitulo: 'Borra y recrea la BD con datos de seed', + cargando: _iniciandoBd, + onTap: _confirmarInicializarBd, + ), + _divider(), + _accionItem( + icon: Icons.sync, + iconColor: AppColors.primary, + titulo: 'Inicializar sincronización', + subtitulo: 'Sincroniza datos locales con el servidor', + cargando: _sincronizando, + onTap: _iniciarSincronizacion, + ), + + const SizedBox(height: 32), + ], ), ); } - Widget _buildSectionHeader(String title) { - return Padding( - padding: const EdgeInsets.fromLTRB(16, 20, 16, 4), - child: Text( - title.toUpperCase(), - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.bold, - color: Colors.blue.shade700, - letterSpacing: 1.2, + // ── Inicializar BD ───────────────────────────────────────────────────────── + Future _confirmarInicializarBd() async { + final confirmar = await showDialog( + context: context, + builder: (_) => AlertDialog( + backgroundColor: AppColors.surfaceHigh, + title: Text('Inicializar base de datos', + style: appHeadline(size: 16, weight: FontWeight.w700)), + content: Text( + 'Se borrarán todos los datos locales y se recreará la base de datos ' + 'con los datos de seed.\n\nEsta acción no se puede deshacer.', + 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('Inicializar', + style: appLabel(size: 13, + weight: FontWeight.bold, color: AppColors.error)), + ), + ], ), ); + + if (confirmar != true) return; + setState(() => _iniciandoBd = true); + + try { + // Borra la BD existente + if (Platform.isLinux || Platform.isWindows) { + final dbPath = p.join(Directory.current.path, 'sentinel_one.db'); + await databaseFactoryFfi.deleteDatabase(dbPath); + } else { + final dbPath = p.join(await getDatabasesPath(), 'sentinel_one.db'); + await deleteDatabase(dbPath); + } + + // Fuerza la reinicialización en el próximo acceso + DatabaseHelper.instance.resetInstance(); + + // Abre la BD para ejecutar el seed inmediatamente + await DatabaseHelper.instance.db; + + if (!mounted) return; + _snack('Base de datos inicializada correctamente', esError: false); + } catch (e) { + if (!mounted) return; + _snack('Error al inicializar: $e'); + } finally { + if (mounted) setState(() => _iniciandoBd = false); + } } + + // ── Sincronización ───────────────────────────────────────────────────────── + Future _iniciarSincronizacion() async { + setState(() => _sincronizando = true); + try { + await Sincronizador.instance.sincronizar(); + if (!mounted) return; + _snack('Sincronización completada', esError: false); + } catch (e) { + if (!mounted) return; + _snack('Error en sincronización: $e'); + } finally { + if (mounted) setState(() => _sincronizando = false); + } + } + + // ── Helpers de UI ────────────────────────────────────────────────────────── + void _snack(String msg, {bool esError = true}) { + ScaffoldMessenger.of(context).showSnackBar(SnackBar( + content: Text(msg), + backgroundColor: esError ? AppColors.error : AppColors.primary, + )); + } + + Widget _sectionHeader(String label) => Padding( + padding: const EdgeInsets.fromLTRB(24, 24, 24, 8), + child: Text(label, + style: appLabel(size: 10, weight: FontWeight.bold, + color: AppColors.onSurfaceVariant, spacing: 2.0)), + ); + + Widget _divider() => const Divider( + color: AppColors.outlineVariant, height: 1, + indent: 24, endIndent: 24); + + Widget _switchItem({ + required IconData icon, + required String titulo, + required String subtitulo, + required bool value, + required ValueChanged onChanged, + }) => + Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 4), + child: Row(children: [ + Container( + width: 40, height: 40, + decoration: BoxDecoration( + color: AppColors.surfaceHighest, + borderRadius: BorderRadius.circular(10)), + child: Icon(icon, color: AppColors.primary, size: 20), + ), + const SizedBox(width: 16), + Expanded(child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(titulo, style: appHeadline(size: 14)), + Text(subtitulo, style: appLabel(size: 12)), + ], + )), + Switch( + value: value, + onChanged: onChanged, + activeColor: AppColors.primary, + activeTrackColor: AppColors.primaryContainer, + inactiveThumbColor: AppColors.outlineVariant, + inactiveTrackColor: AppColors.surfaceHighest, + ), + ]), + ); + + Widget _accionItem({ + required IconData icon, + required Color iconColor, + required String titulo, + required String subtitulo, + required bool cargando, + required VoidCallback onTap, + }) => + InkWell( + onTap: cargando ? null : onTap, + child: Padding( + padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 14), + child: Row(children: [ + Container( + width: 40, height: 40, + decoration: BoxDecoration( + color: AppColors.surfaceHighest, + borderRadius: BorderRadius.circular(10)), + child: Icon(icon, color: iconColor, size: 20), + ), + const SizedBox(width: 16), + Expanded(child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(titulo, style: appHeadline(size: 14)), + Text(subtitulo, style: appLabel(size: 12)), + ], + )), + if (cargando) + const SizedBox( + width: 20, height: 20, + child: CircularProgressIndicator( + strokeWidth: 2, color: AppColors.primary)) + else + const Icon(Icons.chevron_right, + color: AppColors.outlineVariant, size: 20), + ]), + ), + ); } diff --git a/lib/services/api_auth_service.dart b/lib/services/api_auth_service.dart new file mode 100644 index 0000000..b6427a0 --- /dev/null +++ b/lib/services/api_auth_service.dart @@ -0,0 +1,70 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'package:shared_preferences/shared_preferences.dart'; + +/// Gestiona la autenticación contra la API y el ciclo de vida del token JWT. +/// El token NUNCA se expone a las páginas — solo lo usa [Sincronizador]. +class ApiAuthService { + static const _keyToken = 'api_token'; + static const _keyExpiry = 'api_token_expiry'; + + ApiAuthService._(); + static final ApiAuthService instance = ApiAuthService._(); + + // ── Login ────────────────────────────────────────────────────────────────── + /// Solicita token al servidor. + /// Devuelve `true` si el login fue exitoso. + Future login(String baseUrl, String usuario, String password) async { + try { + final resp = await http.post( + Uri.parse('$baseUrl/auth/login'), + headers: {'Content-Type': 'application/json'}, + body: jsonEncode({'usuario': usuario, 'password': password}), + ).timeout(const Duration(seconds: 10)); + + if (resp.statusCode == 200) { + final body = jsonDecode(resp.body) as Map; + final token = body['token'] as String?; + final expiryStr = body['expiry'] as String?; + if (token == null) return false; + + final prefs = await SharedPreferences.getInstance(); + await prefs.setString(_keyToken, token); + if (expiryStr != null) { + await prefs.setString(_keyExpiry, expiryStr); + } + return true; + } + return false; + } catch (_) { + return false; + } + } + + // ── Logout ───────────────────────────────────────────────────────────────── + Future logout() async { + final prefs = await SharedPreferences.getInstance(); + await prefs.remove(_keyToken); + await prefs.remove(_keyExpiry); + } + + // ── Estado ───────────────────────────────────────────────────────────────── + Future isAuthenticated() async { + final token = await getToken(); + if (token == null || token.isEmpty) return false; + + final prefs = await SharedPreferences.getInstance(); + final expiryStr = prefs.getString(_keyExpiry); + if (expiryStr == null) return true; // Sin expiración = válido + + final expiry = DateTime.tryParse(expiryStr); + if (expiry == null) return true; + return DateTime.now().isBefore(expiry); + } + + // ── Token ────────────────────────────────────────────────────────────────── + Future getToken() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getString(_keyToken); + } +} diff --git a/lib/services/sincronizador.dart b/lib/services/sincronizador.dart new file mode 100644 index 0000000..063a999 --- /dev/null +++ b/lib/services/sincronizador.dart @@ -0,0 +1,246 @@ +import 'dart:convert'; +import 'package:http/http.dart' as http; +import 'api_auth_service.dart'; +import '../db/dao/alarmas_dao.dart'; +import '../db/dao/accesos_dao.dart'; +import '../db/dao/usuarios_dao.dart'; +import '../db/dao/zonas_dao.dart'; +import '../db/dao/mensajes_dao.dart'; +import '../db/dao/banners_dao.dart'; +import '../db/dao/sync_log_dao.dart'; +import '../db/dao/configuracion_dao.dart'; +import '../models/alarma.dart'; +import '../models/acceso.dart'; +import '../models/usuario.dart'; +import '../models/zona.dart'; +import '../models/mensaje.dart'; +import '../models/banner_item.dart'; + +/// Orquesta la sincronización entre la API y SQLite. +/// Las páginas nunca llaman a la API directamente — solo leen SQLite. +class Sincronizador { + Sincronizador._(); + static final Sincronizador instance = Sincronizador._(); + + final _auth = ApiAuthService.instance; + final _syncLog = SyncLogDao(); + final _config = ConfiguracionDao(); + + // ── Punto de entrada principal ───────────────────────────────────────────── + Future sincronizar() async { + final autenticado = await _auth.isAuthenticated(); + if (!autenticado) { + await _syncLog.registrar( + tipo: 'full', + estado: 'error', + detalle: 'Sin token válido — sincronización omitida', + ); + return; + } + + try { + await sincronizarZonas(); + await sincronizarUsuarios(); + await sincronizarAlarmas(); + await sincronizarAccesos(); + await sincronizarMensajes(); + await sincronizarBanners(); + await pushPendientes(); + + await _syncLog.registrar( + tipo: 'full', + estado: 'ok', + detalle: 'Sincronización completa', + ); + } catch (e) { + await _syncLog.registrar( + tipo: 'full', + estado: 'error', + detalle: e.toString(), + ); + } + } + + // ── Métodos específicos ──────────────────────────────────────────────────── + + Future sincronizarZonas() async { + final data = await _get('/zonas'); + if (data == null) return; + final dao = ZonasDao(); + for (final item in data) { + final z = Zona.fromMap({...item, 'sincronizado': 1}); + final existente = await dao.getById(z.id); + if (existente == null) { + await dao.insert(z); + } else { + await dao.update(z); + } + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'zonas: ${data.length} registros'); + } + + Future sincronizarUsuarios() async { + final data = await _get('/usuarios'); + if (data == null) return; + final dao = UsuariosDao(); + for (final item in data) { + final u = Usuario.fromMap({...item, 'sincronizado': 1}); + final existente = await dao.getById(u.id); + if (existente == null) { + await dao.insert(u); + } else { + await dao.update(u); + } + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'usuarios: ${data.length} registros'); + } + + Future sincronizarAlarmas() async { + final data = await _get('/alarmas'); + if (data == null) return; + final dao = AlarmasDao(); + for (final item in data) { + final a = Alarma.fromMap({...item, 'sincronizado': 1}); + final existente = await dao.getById(a.id); + if (existente == null) { + await dao.insert(a); + } else { + await dao.update(a); + } + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'alarmas: ${data.length} registros'); + } + + Future sincronizarAccesos() async { + final data = await _get('/accesos'); + if (data == null) return; + final dao = AccesosDao(); + for (final item in data) { + final a = Acceso.fromMap({...item, 'sincronizado': 1}); + await dao.insert(a); + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'accesos: ${data.length} registros'); + } + + Future sincronizarMensajes() async { + final data = await _get('/mensajes'); + if (data == null) return; + final dao = MensajesDao(); + for (final item in data) { + final m = Mensaje.fromMap({...item, 'sincronizado': 1}); + await dao.insert(m); + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'mensajes: ${data.length} registros'); + } + + Future sincronizarBanners() async { + final data = await _get('/banners'); + if (data == null) return; + final dao = BannersDao(); + for (final item in data) { + final b = BannerItem.fromMap({...item, 'sincronizado': 1}); + final existente = await dao.getById(b.id); + if (existente == null) { + await dao.insert(b); + } else { + await dao.update(b); + } + } + await _syncLog.registrar(tipo: 'parcial', estado: 'ok', + detalle: 'banners: ${data.length} registros'); + } + + // ── Push de pendientes (local → API) ─────────────────────────────────────── + Future pushPendientes() async { + await _pushAlarmasPendientes(); + await _pushAccesosPendientes(); + await _pushMensajesPendientes(); + await _syncLog.registrar(tipo: 'push', estado: 'ok', + detalle: 'Push de pendientes completado'); + } + + Future _pushAlarmasPendientes() async { + final pendientes = await AlarmasDao().getPendientes(); + if (pendientes.isEmpty) return; + final baseUrl = await _config.get('api_base_url') ?? ''; + final token = await _auth.getToken(); + if (baseUrl.isEmpty || token == null) return; + for (final a in pendientes) { + try { + await http.put( + Uri.parse('$baseUrl/alarmas/${a.id}'), + headers: _headers(token), + body: jsonEncode(a.toMap()), + ).timeout(const Duration(seconds: 8)); + } catch (_) { + // Continúa con el siguiente — se reintentará en el próximo ciclo + } + } + } + + Future _pushAccesosPendientes() async { + final pendientes = await AccesosDao().getPendientes(); + if (pendientes.isEmpty) return; + final baseUrl = await _config.get('api_base_url') ?? ''; + final token = await _auth.getToken(); + if (baseUrl.isEmpty || token == null) return; + for (final a in pendientes) { + try { + await http.post( + Uri.parse('$baseUrl/accesos'), + headers: _headers(token), + body: jsonEncode(a.toMap()), + ).timeout(const Duration(seconds: 8)); + } catch (_) {} + } + } + + Future _pushMensajesPendientes() async { + final pendientes = await MensajesDao().getPendientes(); + if (pendientes.isEmpty) return; + final baseUrl = await _config.get('api_base_url') ?? ''; + final token = await _auth.getToken(); + if (baseUrl.isEmpty || token == null) return; + for (final m in pendientes) { + try { + await http.post( + Uri.parse('$baseUrl/mensajes'), + headers: _headers(token), + body: jsonEncode(m.toMap()), + ).timeout(const Duration(seconds: 8)); + } catch (_) {} + } + } + + // ── Helpers ──────────────────────────────────────────────────────────────── + Future>?> _get(String endpoint) async { + final baseUrl = await _config.get('api_base_url') ?? ''; + final token = await _auth.getToken(); + if (baseUrl.isEmpty || token == null) return null; + + try { + final resp = await http.get( + Uri.parse('$baseUrl$endpoint'), + headers: _headers(token), + ).timeout(const Duration(seconds: 10)); + + if (resp.statusCode == 200) { + final body = jsonDecode(resp.body); + if (body is List) return body.cast>(); + } + return null; + } catch (_) { + return null; + } + } + + Map _headers(String token) => { + 'Content-Type': 'application/json', + 'Authorization': 'Bearer $token', + }; +} diff --git a/plan_proyecto.md b/plan_proyecto.md index db7472a..2446eb1 100644 --- a/plan_proyecto.md +++ b/plan_proyecto.md @@ -1,7 +1,7 @@ # SENTINEL ONE — Plan del Proyecto **App:** Sistema de Seguridad Electrónica **Stack:** Flutter · Google Fonts (Manrope + Inter) · Material 3 · Dark Theme -**Última revisión:** 2026-04-14 +**Última revisión:** 2026-04-14 (sesión 3) --- @@ -9,18 +9,24 @@ | Módulo | Archivo | Estado | |--------|---------|--------| -| Login (PIN 6 dígitos) | `main.dart` → `LoginPage` | ✅ Completo | +| Login (PIN local + SharedPreferences) | `main.dart` → `LoginPage` | ✅ Completo | | Layout principal (nav + header) | `main_page.dart` | ✅ Completo | | Inicio (usuario, empresa, banner, log) | `pages/inicio_page.dart` | ✅ Completo | | Monitoreo y Alarmas | `pages/monitoreo_alarma_page.dart` | ✅ Completo | | Control de Acceso | `pages/control_acceso_page.dart` | 🟡 Parcial | | Mensajería (chat WhatsApp) | `pages/mensageria_page.dart` | ✅ Completo | | Perfil de Usuario | `pages/perfil_usuario_page.dart` | ✅ Completo | +| Cambio de PIN | `pages/seguridad_page.dart` | ✅ Completo | | Registro de usuario | `pages/register_page.dart` | 🔴 Sin estilo del sistema | | Configuración | `pages/settings_page.dart` | 🔴 Sin estilo del sistema | | Alarmas (página propia) | `pages/alarmas_page.dart` | 🔴 Vacío | | Tema / Colores | `theme.dart` | ✅ Completo | | Menú global | `widgets/app_menu_button.dart` | ✅ Completo | +| Base de datos SQLite | `db/database_helper.dart` | ✅ Completo | +| Modelos de datos | `models/*.dart` (10 modelos) | ✅ Completo | +| DAOs | `db/dao/*.dart` (12 DAOs) | ✅ Completo | +| ApiAuthService | `services/api_auth_service.dart` | ✅ Estructura lista | +| Sincronizador | `services/sincronizador.dart` | ✅ Estructura lista | --- @@ -31,6 +37,19 @@ - Auto-avance al siguiente campo, retroceso con backspace - Enlace a RegisterPage - Al ingresar navega a `MainPage(initialIndex: 0)` — abre en tab INICIO +- **Autenticación local vía `SharedPreferences`** — el PIN se guarda como hash SHA-256 bajo la clave `local_pin_hash` +- PIN inicial por defecto: `123456` — si no hay hash guardado, se compara contra ese valor +- El login NO depende de SQLite — funciona en todas las plataformas sin plugins nativos +- Spinner de carga mientras valida, mensaje de error visible en snackbar + +### Cambio de PIN (`pages/seguridad_page.dart`) +- Accesible desde Perfil → Seguridad +- 3 secciones de cajas PIN: PIN actual · Nuevo PIN · Confirmar nuevo PIN +- Valida que el PIN actual sea correcto antes de permitir el cambio +- Verifica que nuevo PIN ≠ PIN actual, y que nuevo PIN = confirmación +- Guarda el nuevo hash SHA-256 en `SharedPreferences` (`local_pin_hash`) +- Botón deshabilitado hasta que los 3 campos tengan mínimo 4 dígitos +- Snackbar de éxito (azul) o error (rojo) según resultado ### MainPage (`main_page.dart`) - Header: logo SENTINEL ONE (izq) + título de sección activa + AppMenuButton (der) @@ -75,6 +94,16 @@ - Menú: Configuración, Seguridad, Historial de sesiones, Ayuda y soporte - Botón Cerrar Sesión → LoginPage +### Capa de datos SQLite (`lib/db/` · `lib/models/` · `lib/services/`) +- **`database_helper.dart`** — Singleton, 12 `CREATE TABLE`, seed completo al primer arranque: + - 1 usuario admin (Juan Díaz, nivel 3) + - 6 zonas (Z-01 a Z-06), 3 puertas, 5 alarmas, 4 eventos, 5 mensajes, 3 banners, configuración base +- **10 modelos** con `fromMap()` / `toMap()` — `Usuario`, `Zona`, `Nodo`, `Puerta`, `Alarma`, `Acceso`, `Evento`, `Mensaje`, `BannerItem`, `Sesion` +- **12 DAOs** — operaciones CRUD + `getPendientes()` + métodos específicos por dominio (`resolver`, `silenciar`, `setBloqueada`, `contarActivas`, `marcarLeido`, etc.) +- **`ApiAuthService`** — estructura lista: `login()`, `logout()`, `isAuthenticated()`, `getToken()` — token JWT en SharedPreferences +- **`Sincronizador`** — estructura lista: `sincronizar()`, métodos por tabla, `pushPendientes()` — pendiente de URL de API real +- Compatible con Linux/Windows desktop vía `sqflite_common_ffi` (detección automática de plataforma en `database_helper.dart`) + --- ## Lo que falta hacer @@ -108,64 +137,185 @@ Comentario pendiente en el código: *"agregar un botón para registrar usuarios --- -## Plan de integración SQLite +## Arquitectura de datos — Offline First + Sincronización -### Objetivo -Persistir localmente todos los datos estáticos usando `sqflite`. +### Principio fundamental +La app funciona **completamente de forma independiente**. SQLite es la única fuente de verdad para la UI. El servidor es una fuente externa que alimenta la BD local, nunca se consulta directamente desde las páginas. + +``` +┌─────────────────────────────────────────────────────────┐ +│ APP │ +│ │ +│ Páginas ──────► DAOs ──────► SQLite (local) │ +│ ▲ │ +│ │ │ +│ Sincronizador │ +│ ▲ │ +│ │ │ +│ ApiAuthService │ +│ (token JWT) │ +└─────────────────────────────────────────────────────────┘ + │ + ▼ + API / Servidor +``` + +### Clases de servicio + +#### `ApiAuthService` (`lib/services/api_auth_service.dart`) +Responsabilidad: autenticación contra el servidor y gestión del token. +- `login(usuario, password)` → solicita token al servidor y lo almacena en `configuracion` (clave: `api_token`, `api_token_expiry`) +- `logout()` → elimina el token local +- `isAuthenticated()` → verifica si hay token válido no expirado +- `getToken()` → devuelve el token activo para usarlo en peticiones +- El token **nunca se expone a las páginas** — solo lo usa `Sincronizador` + +#### `Sincronizador` (`lib/services/sincronizador.dart`) +Responsabilidad: mantener SQLite actualizado con los datos del servidor. +- `sincronizar()` → punto de entrada principal, llama a los métodos específicos +- `sincronizarAlarmas()` → descarga alarmas nuevas del servidor → inserta/actualiza en SQLite +- `sincronizarAccesos()` → descarga registros de acceso → SQLite +- `sincronizarUsuarios()` → descarga usuarios autorizados → SQLite +- `sincronizarZonas()` → descarga zonas y nodos → SQLite +- `sincronizarMensajes()` → descarga mensajes nuevos de la central → SQLite +- `sincronizarBanners()` → descarga contenido del slider → SQLite +- `pushPendientes()` → envía al servidor los registros locales marcados como `sincronizado = 0` +- Registra cada sincronización en la tabla `sync_log` + +--- + +## Plan de integración SQLite ### Dependencias a agregar en `pubspec.yaml` ```yaml dependencies: sqflite: ^2.3.0 path: ^1.9.0 + crypto: ^3.0.3 # hash del PIN + shared_preferences: ^2.2.2 # almacenamiento del token (más seguro que SQLite para auth) ``` -### Estructura de tablas +### Tablas completas #### `usuarios` | Campo | Tipo | Descripción | |-------|------|-------------| -| id | INTEGER PK | Auto-incremental | +| id | INTEGER PK | ID del servidor | | nombre | TEXT | Nombre completo | | iniciales | TEXT | Para el avatar (ej. "JD") | | nivel_acceso | INTEGER | 1–5 | -| pin_hash | TEXT | Hash del PIN (no guardar en plano) | -| areas | TEXT | JSON con lista de zonas permitidas | +| pin_hash | TEXT | SHA-256 del PIN | +| areas | TEXT | JSON con lista de IDs de zonas permitidas | | fecha_inicio | TEXT | ISO 8601 | | fecha_fin | TEXT | ISO 8601, null = sin expiración | | activo | INTEGER | 0/1 | +| sincronizado | INTEGER | 0=pendiente, 1=sincronizado | + +#### `zonas` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | ID del servidor | +| codigo | TEXT | Ej. "Z-03" | +| nombre | TEXT | Ej. "Almacén G-4" | +| descripcion | TEXT | Ej. "Bodega · 2 cámaras · 4 sensores" | +| estado | TEXT | segura / alerta / inactiva | +| sincronizado | INTEGER | 0/1 | + +#### `nodos` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | ID del servidor | +| zona_id | INTEGER | FK zonas.id | +| tipo | TEXT | camara / sensor_movimiento / sensor_humo / control_acceso | +| nombre | TEXT | Ej. "CAM_01_LOBBY" | +| activo | INTEGER | 0/1 | +| ultima_senal | TEXT | ISO 8601 | +| sincronizado | INTEGER | 0/1 | + +#### `puertas` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | ID del servidor | +| zona_id | INTEGER | FK zonas.id | +| nombre | TEXT | Ej. "Lobby Principal" | +| codigo | TEXT | Ej. "Entrada 01" | +| bloqueada | INTEGER | 0/1 — persiste entre sesiones | +| sincronizado | INTEGER | 0/1 | #### `alarmas` | Campo | Tipo | Descripción | |-------|------|-------------| -| id | INTEGER PK | Auto-incremental | -| zona | TEXT | Ej. "Z-03" | -| nombre_zona | TEXT | Ej. "Almacén G-4" | +| id | INTEGER PK | ID del servidor | +| zona_id | INTEGER | FK zonas.id | | tipo | TEXT | intrusion / humo / movimiento / acceso | | severidad | INTEGER | 1–5 | | timestamp | TEXT | ISO 8601 | | estado | TEXT | activa / silenciada / resuelta | | resuelto_por | INTEGER | FK usuarios.id, nullable | | notas | TEXT | nullable | +| sincronizado | INTEGER | 0/1 | #### `accesos` | Campo | Tipo | Descripción | |-------|------|-------------| -| id | INTEGER PK | Auto-incremental | +| id | INTEGER PK | ID del servidor | | usuario_id | INTEGER | FK usuarios.id | -| puerta | TEXT | Ej. "Lobby Principal" | +| puerta_id | INTEGER | FK puertas.id | | timestamp | TEXT | ISO 8601 | | autorizado | INTEGER | 0/1 | | metodo | TEXT | pin / remoto / biometrico | +| sincronizado | INTEGER | 0/1 | + +#### `eventos` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | ID del servidor | +| tipo | TEXT | alerta / noticia / notificacion / general | +| titulo | TEXT | Título del evento | +| descripcion | TEXT | Detalle | +| hora | TEXT | HH:MM AM/PM para mostrar | +| timestamp | TEXT | ISO 8601 para ordenar | +| leido | INTEGER | 0/1 | +| sincronizado | INTEGER | 0/1 | #### `mensajes` | Campo | Tipo | Descripción | |-------|------|-------------| -| id | INTEGER PK | Auto-incremental | +| id | INTEGER PK | ID del servidor | | texto | TEXT | Contenido | | es_mio | INTEGER | 0/1 | | hora | TEXT | HH:MM para mostrar | | timestamp | TEXT | ISO 8601 para ordenar | +| sincronizado | INTEGER | 0/1 | + +#### `banners` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | ID del servidor | +| badge | TEXT | Ej. "Premium Access" | +| titulo | TEXT | Título del banner | +| subtitulo | TEXT | Descripción | +| orden | INTEGER | Posición en el slider | +| activo | INTEGER | 0/1 | +| sincronizado | INTEGER | 0/1 | + +#### `sesiones` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | Auto-incremental local | +| usuario_id | INTEGER | FK usuarios.id | +| timestamp_inicio | TEXT | ISO 8601 | +| timestamp_fin | TEXT | ISO 8601, null = sesión activa | +| dispositivo | TEXT | Identificador del dispositivo | + +#### `sync_log` +| Campo | Tipo | Descripción | +|-------|------|-------------| +| id | INTEGER PK | Auto-incremental | +| timestamp | TEXT | ISO 8601 | +| tipo | TEXT | full / parcial / push | +| estado | TEXT | ok / error | +| detalle | TEXT | Mensaje de resultado o error | #### `configuracion` | Campo | Tipo | Descripción | @@ -173,40 +323,65 @@ dependencies: | clave | TEXT PK | Ej. "notificaciones_activas" | | valor | TEXT | Valor serializado | -### Arquitectura sugerida +--- + +### Estructura de archivos ``` lib/ db/ - database_helper.dart ← Singleton, inicializa y migra la BD + database_helper.dart ← Singleton, CREATE TABLE, migraciones, seed dao/ - usuarios_dao.dart ← CRUD de usuarios - alarmas_dao.dart ← CRUD de alarmas - accesos_dao.dart ← CRUD de accesos - mensajes_dao.dart ← CRUD de mensajes - configuracion_dao.dart ← Get/Set de configuración + usuarios_dao.dart + zonas_dao.dart + nodos_dao.dart + puertas_dao.dart + alarmas_dao.dart + accesos_dao.dart + eventos_dao.dart + mensajes_dao.dart + banners_dao.dart + sesiones_dao.dart + sync_log_dao.dart + configuracion_dao.dart models/ usuario.dart + zona.dart + nodo.dart + puerta.dart alarma.dart acceso.dart + evento.dart mensaje.dart + banner.dart + sesion.dart + services/ + api_auth_service.dart ← Login API, gestión de token JWT + sincronizador.dart ← Orquesta la sincronización API → SQLite ``` ### Pasos de implementación (en orden) -1. `database_helper.dart` — Singleton con `openDatabase`, `onCreate` con los `CREATE TABLE` y datos de seed -2. Modelos — clases Dart con `fromMap()` y `toMap()` -3. DAOs — métodos `insert`, `getAll`, `getById`, `update`, `delete` por tabla -4. Conectar páginas: - - `MensajeriaPage` → `MensajesDao` - - `ControlAccesoPage` → `AccesosDao` - - `MonitoreoAlarmaPage` → `AlarmasDao` - - `LoginPage` → `UsuariosDao` (validar PIN) -### Datos de seed (primer arranque) +1. ✅ **`database_helper.dart`** — Singleton, `onCreate` con todos los `CREATE TABLE`, datos de seed +2. ✅ **Modelos** — clases Dart con `fromMap()` / `toMap()` por cada tabla +3. ✅ **DAOs** — `insert`, `getAll`, `getById`, `update`, `delete`, `getPendientes()` por tabla +4. ✅ **`ApiAuthService`** — estructura lista, pendiente URL de API real +5. ✅ **`Sincronizador`** — estructura lista, pendiente URL de API real +6. **Conectar páginas** en orden (pendiente): + - `InicioPage` → `EventosDao`, `BannersDao`, `ZonasDao` + - `MensajeriaPage` → `MensajesDao` + - `ControlAccesoPage` → `PuertasDao`, `AccesosDao` + - `MonitoreoAlarmaPage` → `AlarmasDao`, `EventosDao` + - `PerfilUsuarioPage` → `UsuariosDao`, `SesionesDao` + +### Datos de seed (primer arranque, antes de primera sincronización) - 1 usuario admin: Juan Díaz, nivel 3, PIN 123456 -- 5 alarmas históricas de ejemplo -- 3 registros de acceso de ejemplo -- 5 mensajes de demostración de MensajeriaPage +- 6 zonas (Z-01 a Z-06) con sus estados +- 3 puertas (Lobby, Muelle, Centro de Datos) +- 5 alarmas históricas +- 4 eventos del log de InicioPage +- 5 mensajes del chat de demostración +- 3 banners del slider --- @@ -214,8 +389,11 @@ lib/ - **Tema:** Todo en `theme.dart` — siempre `AppColors`, `appHeadline()`, `appLabel()` - **Navegación:** `IndexedStack` en MainPage — las páginas mantienen estado al cambiar tab -- **Datos:** Actualmente todos estáticos. Próximo paso: SQLite antes de cualquier backend -- **SDK:** `sdk: ">=2.17.0-69.2.beta <3.0.0"` — actualizar a Dart 3.x antes de SQLite +- **Datos:** Offline-first — las páginas solo leen SQLite, nunca la API directamente +- **Sincronización:** `Sincronizador` orquesta la bajada de datos; `ApiAuthService` provee el token +- **Token:** Se guarda en `shared_preferences`, no en SQLite (más seguro para datos de auth) +- **Campo `sincronizado`:** Todas las tablas operacionales lo tienen — permite saber qué enviar al servidor en el próximo `pushPendientes()` +- **SDK:** `sdk: ">=2.17.0-69.2.beta <3.0.0"` — actualizar a Dart 3.x antes de implementar SQLite --- @@ -227,9 +405,42 @@ lib/ - ✅ Mensajería accesible desde FAB de pánico (no en el nav principal) - ✅ Tarjetas Pánico/Soporte viven dentro de MensajeriaPage - ✅ Sección usuario en InicioPage: texto izquierda, avatar derecha, sin tarjeta de fondo +- ✅ Login no usa SQLite — usa SharedPreferences para no depender de plugins nativos +- ✅ Cambio de PIN en página dedicada (`seguridad_page.dart`) accesible desde Perfil +- ✅ Cerrar sesión con diálogo de confirmación — limpia autologin y regresa a LoginPage +- ✅ Fix Linux desktop: `primary: false` en todos los `SingleChildScrollView` del IndexedStack +- ✅ Fix Linux SQLite: detección de plataforma en `database_helper.dart` con `sqflite_common_ffi` + +## Roadmap de autenticación (Login) + +### Estado actual +- PIN local validado contra hash SHA-256 en `SharedPreferences` +- PIN inicial: `123456` (el usuario debe cambiarlo) +- No depende de SQLite ni plugins nativos — funciona en todas las plataformas + +### Próximas mejoras (en orden sugerido) + +#### 1. Cambio de PIN (`pages/seguridad_page.dart`) ✅ IMPLEMENTADO +- Formulario: PIN actual → nuevo PIN → confirmar +- Guarda el nuevo hash en `SharedPreferences` bajo `local_pin_hash` + +#### 2. Auto-login (checkbox en pantalla de login) +- Checkbox "Recordar acceso en este dispositivo" +- Si está marcado: guarda flag `autologin = true` en SharedPreferences +- Al abrir la app: si `autologin = true` → salta directo a `MainPage` + +#### 3. Biometría (futuro — Android/iOS) +- Paquete: `local_auth` (Flutter oficial) +- Flujo: pantalla de login muestra ícono de huella/Face ID además del PIN +- Solo disponible en móvil — en desktop mantiene solo PIN +- Al autenticarse con biometría: mismo flujo que PIN correcto (sin tocar SharedPreferences) +- Activar/desactivar desde `settings_page.dart` + +--- ## Decisiones pendientes - [ ] ¿RegisterPage usa PIN o email+contraseña? (afecta diseño y tabla `usuarios`) - [ ] ¿El registro de usuarios en ControlAcceso es solo para nivel 3+? - [ ] ¿Backend propio o SQLite local permanente? +- [ ] ¿Cuándo activar el checkbox de auto-login? (¿después del primer login exitoso o siempre visible?) diff --git a/pubspec.lock b/pubspec.lock index 74a99d4..0e053fd 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -44,7 +44,7 @@ packages: source: hosted version: "1.15.0" crypto: - dependency: transitive + dependency: "direct main" description: name: crypto url: "https://pub.dartlang.org" @@ -95,6 +95,11 @@ packages: description: flutter source: sdk version: "0.0.0" + flutter_web_plugins: + dependency: transitive + description: flutter + source: sdk + version: "0.0.0" google_fonts: dependency: "direct main" description: @@ -103,7 +108,7 @@ packages: source: hosted version: "3.0.1" http: - dependency: transitive + dependency: "direct main" description: name: http url: "https://pub.dartlang.org" @@ -116,6 +121,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.0.2" + js: + dependency: transitive + description: + name: js + url: "https://pub.dartlang.org" + source: hosted + version: "0.6.4" lints: dependency: transitive description: @@ -145,7 +157,7 @@ packages: source: hosted version: "1.7.0" path: - dependency: transitive + dependency: "direct main" description: name: path url: "https://pub.dartlang.org" @@ -221,6 +233,55 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "4.2.4" + shared_preferences: + dependency: "direct main" + description: + name: shared_preferences + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.17" + shared_preferences_android: + dependency: transitive + description: + name: shared_preferences_android + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.15" + shared_preferences_foundation: + dependency: transitive + description: + name: shared_preferences_foundation + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.2" + shared_preferences_linux: + dependency: transitive + description: + name: shared_preferences_linux + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" + shared_preferences_platform_interface: + dependency: transitive + description: + name: shared_preferences_platform_interface + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.0" + shared_preferences_web: + dependency: transitive + description: + name: shared_preferences_web + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.4" + shared_preferences_windows: + dependency: transitive + description: + name: shared_preferences_windows + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.3" sky_engine: dependency: transitive description: flutter @@ -233,6 +294,34 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.8.1" + sqflite: + dependency: "direct main" + description: + name: sqflite + url: "https://pub.dartlang.org" + source: hosted + version: "2.0.2+1" + sqflite_common: + dependency: transitive + description: + name: sqflite_common + url: "https://pub.dartlang.org" + source: hosted + version: "2.4.0" + sqflite_common_ffi: + dependency: "direct main" + description: + name: sqflite_common_ffi + url: "https://pub.dartlang.org" + source: hosted + version: "2.1.1+1" + sqlite3: + dependency: transitive + description: + name: sqlite3 + url: "https://pub.dartlang.org" + source: hosted + version: "1.7.0" stack_trace: dependency: transitive description: @@ -254,6 +343,13 @@ packages: url: "https://pub.dartlang.org" source: hosted version: "1.1.0" + synchronized: + dependency: transitive + description: + name: synchronized + url: "https://pub.dartlang.org" + source: hosted + version: "3.0.0+3" term_glyph: dependency: transitive description: diff --git a/pubspec.yaml b/pubspec.yaml index 4826397..cbaef34 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -32,6 +32,12 @@ dependencies: cupertino_icons: ^1.0.2 google_fonts: ^3.0.1 + sqflite: ^2.0.0 + sqflite_common_ffi: ^2.0.0 + path: ^1.8.1 + crypto: ^3.0.2 + shared_preferences: ^2.0.0 + http: ^0.13.4 dev_dependencies: flutter_test: