feat: add SQLite data layer, local auth and security settings
- Add offline-first SQLite architecture with DatabaseHelper singleton, 12 CREATE TABLE statements and full seed data on first launch - Add 10 models (fromMap/toMap) and 12 DAOs with CRUD + getPendientes() - Add ApiAuthService (JWT via SharedPreferences) and Sincronizador skeleton - Move login auth from SQLite to SharedPreferences with SHA-256 PIN hash; default PIN 123456, platform-independent (no native plugin required) - Add seguridad_page.dart: change PIN form (current → new → confirm) - Add Cerrar Sesión with confirmation dialog and full stack clear - Redesign settings_page.dart with AppColors dark theme; add Sistema section with "Inicializar base de datos" and "Inicializar sincronización" - Fix Linux desktop: sqflite_common_ffi with platform detection in DatabaseHelper - Fix ScrollController conflict on Linux: primary: false on all IndexedStack pages - Update plan_proyecto.md with session 2–3 progress and auth roadmap Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
8f13d57839
commit
1184ab5fe2
@@ -0,0 +1,49 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/acceso.dart';
|
||||
|
||||
class AccesosDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Acceso>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('accesos', orderBy: 'timestamp DESC');
|
||||
return rows.map(Acceso.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Acceso>> getRecientes({int limit = 20}) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'accesos',
|
||||
orderBy: 'timestamp DESC',
|
||||
limit: limit,
|
||||
);
|
||||
return rows.map(Acceso.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Acceso>> getByPuerta(int puertaId) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'accesos',
|
||||
where: 'puerta_id = ?',
|
||||
whereArgs: [puertaId],
|
||||
orderBy: 'timestamp DESC',
|
||||
);
|
||||
return rows.map(Acceso.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<int> insert(Acceso a) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('accesos', a.toMap());
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('accesos', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Acceso>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('accesos', where: 'sincronizado = 0');
|
||||
return rows.map(Acceso.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/alarma.dart';
|
||||
|
||||
class AlarmasDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Alarma>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('alarmas', orderBy: 'timestamp DESC');
|
||||
return rows.map(Alarma.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Alarma>> getActivas() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'alarmas',
|
||||
where: 'estado = ?',
|
||||
whereArgs: ['activa'],
|
||||
orderBy: 'severidad DESC, timestamp DESC',
|
||||
);
|
||||
return rows.map(Alarma.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Alarma>> getByZona(int zonaId) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'alarmas',
|
||||
where: 'zona_id = ?',
|
||||
whereArgs: [zonaId],
|
||||
orderBy: 'timestamp DESC',
|
||||
);
|
||||
return rows.map(Alarma.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Alarma?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('alarmas', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Alarma.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Alarma a) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('alarmas', a.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(Alarma a) async {
|
||||
final db = await _db.db;
|
||||
return db.update('alarmas', a.toMap(), where: 'id = ?', whereArgs: [a.id]);
|
||||
}
|
||||
|
||||
Future<int> resolver(int id, int usuarioId, {String? notas}) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'alarmas',
|
||||
{
|
||||
'estado': 'resuelta',
|
||||
'resuelto_por': usuarioId,
|
||||
'notas': notas,
|
||||
'sincronizado': 0,
|
||||
},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> silenciar(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'alarmas',
|
||||
{'estado': 'silenciada', 'sincronizado': 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('alarmas', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Alarma>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('alarmas', where: 'sincronizado = 0');
|
||||
return rows.map(Alarma.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<int> contarActivas() async {
|
||||
final db = await _db.db;
|
||||
final result = await db.rawQuery(
|
||||
"SELECT COUNT(*) as c FROM alarmas WHERE estado = 'activa'",
|
||||
);
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/banner_item.dart';
|
||||
|
||||
class BannersDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<BannerItem>> getActivos() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'banners',
|
||||
where: 'activo = 1',
|
||||
orderBy: 'orden ASC',
|
||||
);
|
||||
return rows.map(BannerItem.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<BannerItem?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('banners', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : BannerItem.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(BannerItem b) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('banners', b.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(BannerItem b) async {
|
||||
final db = await _db.db;
|
||||
return db.update('banners', b.toMap(), where: 'id = ?', whereArgs: [b.id]);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('banners', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<BannerItem>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('banners', where: 'sincronizado = 0');
|
||||
return rows.map(BannerItem.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import '../database_helper.dart';
|
||||
|
||||
class ConfiguracionDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<String?> get(String clave) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'configuracion',
|
||||
where: 'clave = ?',
|
||||
whereArgs: [clave],
|
||||
);
|
||||
return rows.isEmpty ? null : rows.first['valor'] as String?;
|
||||
}
|
||||
|
||||
Future<void> set(String clave, String valor) async {
|
||||
final db = await _db.db;
|
||||
await db.insert(
|
||||
'configuracion',
|
||||
{'clave': clave, 'valor': valor},
|
||||
conflictAlgorithm: ConflictAlgorithm.replace,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> delete(String clave) async {
|
||||
final db = await _db.db;
|
||||
await db.delete('configuracion', where: 'clave = ?', whereArgs: [clave]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/evento.dart';
|
||||
|
||||
class EventosDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Evento>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('eventos', orderBy: 'timestamp DESC');
|
||||
return rows.map(Evento.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Evento>> getRecientes({int limit = 10}) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'eventos',
|
||||
orderBy: 'timestamp DESC',
|
||||
limit: limit,
|
||||
);
|
||||
return rows.map(Evento.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Evento?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('eventos', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Evento.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Evento e) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('eventos', e.toMap());
|
||||
}
|
||||
|
||||
Future<int> marcarLeido(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'eventos',
|
||||
{'leido': 1, 'sincronizado': 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('eventos', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Evento>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('eventos', where: 'sincronizado = 0');
|
||||
return rows.map(Evento.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<int> contarNoLeidos() async {
|
||||
final db = await _db.db;
|
||||
final result = await db.rawQuery(
|
||||
'SELECT COUNT(*) as c FROM eventos WHERE leido = 0',
|
||||
);
|
||||
return result.first['c'] as int;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/mensaje.dart';
|
||||
|
||||
class MensajesDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Mensaje>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('mensajes', orderBy: 'timestamp ASC');
|
||||
return rows.map(Mensaje.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<int> insert(Mensaje m) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('mensajes', m.toMap());
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('mensajes', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Mensaje>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('mensajes', where: 'sincronizado = 0');
|
||||
return rows.map(Mensaje.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/nodo.dart';
|
||||
|
||||
class NodosDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Nodo>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('nodos', orderBy: 'nombre ASC');
|
||||
return rows.map(Nodo.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<List<Nodo>> getByZona(int zonaId) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('nodos', where: 'zona_id = ?', whereArgs: [zonaId]);
|
||||
return rows.map(Nodo.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Nodo?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('nodos', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Nodo.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Nodo n) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('nodos', n.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(Nodo n) async {
|
||||
final db = await _db.db;
|
||||
return db.update('nodos', n.toMap(), where: 'id = ?', whereArgs: [n.id]);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('nodos', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Nodo>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('nodos', where: 'sincronizado = 0');
|
||||
return rows.map(Nodo.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/puerta.dart';
|
||||
|
||||
class PuertasDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Puerta>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('puertas', orderBy: 'nombre ASC');
|
||||
return rows.map(Puerta.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Puerta?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('puertas', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Puerta.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Puerta p) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('puertas', p.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(Puerta p) async {
|
||||
final db = await _db.db;
|
||||
return db.update('puertas', p.toMap(), where: 'id = ?', whereArgs: [p.id]);
|
||||
}
|
||||
|
||||
Future<int> setBloqueada(int id, bool bloqueada) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'puertas',
|
||||
{'bloqueada': bloqueada ? 1 : 0, 'sincronizado': 0},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('puertas', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Puerta>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('puertas', where: 'sincronizado = 0');
|
||||
return rows.map(Puerta.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/sesion.dart';
|
||||
|
||||
class SesionesDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Sesion>> getByUsuario(int usuarioId) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'sesiones',
|
||||
where: 'usuario_id = ?',
|
||||
whereArgs: [usuarioId],
|
||||
orderBy: 'timestamp_inicio DESC',
|
||||
);
|
||||
return rows.map(Sesion.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Sesion?> getSesionActiva(int usuarioId) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'sesiones',
|
||||
where: 'usuario_id = ? AND timestamp_fin IS NULL',
|
||||
whereArgs: [usuarioId],
|
||||
limit: 1,
|
||||
);
|
||||
return rows.isEmpty ? null : Sesion.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> iniciar(int usuarioId, {String? dispositivo}) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('sesiones', {
|
||||
'usuario_id': usuarioId,
|
||||
'timestamp_inicio': DateTime.now().toIso8601String(),
|
||||
'dispositivo': dispositivo,
|
||||
});
|
||||
}
|
||||
|
||||
Future<int> cerrar(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.update(
|
||||
'sesiones',
|
||||
{'timestamp_fin': DateTime.now().toIso8601String()},
|
||||
where: 'id = ?',
|
||||
whereArgs: [id],
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import '../database_helper.dart';
|
||||
|
||||
class SyncLogDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<int> registrar({
|
||||
required String tipo,
|
||||
required String estado,
|
||||
String? detalle,
|
||||
}) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('sync_log', {
|
||||
'timestamp': DateTime.now().toIso8601String(),
|
||||
'tipo': tipo,
|
||||
'estado': estado,
|
||||
'detalle': detalle,
|
||||
});
|
||||
}
|
||||
|
||||
Future<List<Map<String, dynamic>>> getRecientes({int limit = 20}) async {
|
||||
final db = await _db.db;
|
||||
return db.query(
|
||||
'sync_log',
|
||||
orderBy: 'timestamp DESC',
|
||||
limit: limit,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/usuario.dart';
|
||||
|
||||
class UsuariosDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Usuario>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('usuarios', orderBy: 'nombre ASC');
|
||||
return rows.map(Usuario.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Usuario?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('usuarios', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Usuario.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<Usuario?> getByPinHash(String pinHash) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query(
|
||||
'usuarios',
|
||||
where: 'pin_hash = ? AND activo = 1',
|
||||
whereArgs: [pinHash],
|
||||
);
|
||||
return rows.isEmpty ? null : Usuario.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Usuario u) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('usuarios', u.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(Usuario u) async {
|
||||
final db = await _db.db;
|
||||
return db.update('usuarios', u.toMap(), where: 'id = ?', whereArgs: [u.id]);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('usuarios', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Usuario>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('usuarios', where: 'sincronizado = 0');
|
||||
return rows.map(Usuario.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import '../database_helper.dart';
|
||||
import '../../models/zona.dart';
|
||||
|
||||
class ZonasDao {
|
||||
final _db = DatabaseHelper.instance;
|
||||
|
||||
Future<List<Zona>> getAll() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('zonas', orderBy: 'codigo ASC');
|
||||
return rows.map(Zona.fromMap).toList();
|
||||
}
|
||||
|
||||
Future<Zona?> getById(int id) async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('zonas', where: 'id = ?', whereArgs: [id]);
|
||||
return rows.isEmpty ? null : Zona.fromMap(rows.first);
|
||||
}
|
||||
|
||||
Future<int> insert(Zona z) async {
|
||||
final db = await _db.db;
|
||||
return db.insert('zonas', z.toMap());
|
||||
}
|
||||
|
||||
Future<int> update(Zona z) async {
|
||||
final db = await _db.db;
|
||||
return db.update('zonas', z.toMap(), where: 'id = ?', whereArgs: [z.id]);
|
||||
}
|
||||
|
||||
Future<int> delete(int id) async {
|
||||
final db = await _db.db;
|
||||
return db.delete('zonas', where: 'id = ?', whereArgs: [id]);
|
||||
}
|
||||
|
||||
Future<List<Zona>> getPendientes() async {
|
||||
final db = await _db.db;
|
||||
final rows = await db.query('zonas', where: 'sincronizado = 0');
|
||||
return rows.map(Zona.fromMap).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,412 @@
|
||||
import 'dart:io';
|
||||
import 'package:sqflite/sqflite.dart';
|
||||
import 'package:sqflite_common_ffi/sqflite_ffi.dart';
|
||||
import 'package:path/path.dart';
|
||||
|
||||
class DatabaseHelper {
|
||||
static const _dbName = 'sentinel_one.db';
|
||||
static const _dbVersion = 1;
|
||||
|
||||
DatabaseHelper._();
|
||||
static final DatabaseHelper instance = DatabaseHelper._();
|
||||
|
||||
Database? _db;
|
||||
|
||||
Future<Database> get db async {
|
||||
_db ??= await _initDb();
|
||||
return _db!;
|
||||
}
|
||||
|
||||
/// Cierra la BD y la marca para reinicialización.
|
||||
/// Llamar antes de borrar el archivo de la BD.
|
||||
void resetInstance() {
|
||||
_db?.close();
|
||||
_db = null;
|
||||
}
|
||||
|
||||
Future<Database> _initDb() async {
|
||||
if (Platform.isLinux || Platform.isWindows) {
|
||||
sqfliteFfiInit();
|
||||
final dbPath = join(Directory.current.path, _dbName);
|
||||
return databaseFactoryFfi.openDatabase(
|
||||
dbPath,
|
||||
options: OpenDatabaseOptions(
|
||||
version: _dbVersion,
|
||||
onCreate: _onCreate,
|
||||
),
|
||||
);
|
||||
}
|
||||
final path = join(await getDatabasesPath(), _dbName);
|
||||
return openDatabase(
|
||||
path,
|
||||
version: _dbVersion,
|
||||
onCreate: _onCreate,
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _onCreate(Database db, int version) async {
|
||||
await db.execute('''
|
||||
CREATE TABLE usuarios (
|
||||
id INTEGER PRIMARY KEY,
|
||||
nombre TEXT NOT NULL,
|
||||
iniciales TEXT NOT NULL,
|
||||
nivel_acceso INTEGER NOT NULL DEFAULT 1,
|
||||
pin_hash TEXT NOT NULL,
|
||||
areas TEXT,
|
||||
fecha_inicio TEXT,
|
||||
fecha_fin TEXT,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE zonas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
codigo TEXT NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
descripcion TEXT,
|
||||
estado TEXT NOT NULL DEFAULT 'segura',
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE nodos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
ultima_senal TEXT,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE puertas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
nombre TEXT NOT NULL,
|
||||
codigo TEXT NOT NULL,
|
||||
bloqueada INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE alarmas (
|
||||
id INTEGER PRIMARY KEY,
|
||||
zona_id INTEGER NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
severidad INTEGER NOT NULL DEFAULT 1,
|
||||
timestamp TEXT NOT NULL,
|
||||
estado TEXT NOT NULL DEFAULT 'activa',
|
||||
resuelto_por INTEGER,
|
||||
notas TEXT,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (zona_id) REFERENCES zonas(id),
|
||||
FOREIGN KEY (resuelto_por) REFERENCES usuarios(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE accesos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
usuario_id INTEGER NOT NULL,
|
||||
puerta_id INTEGER NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
autorizado INTEGER NOT NULL DEFAULT 0,
|
||||
metodo TEXT NOT NULL DEFAULT 'pin',
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (usuario_id) REFERENCES usuarios(id),
|
||||
FOREIGN KEY (puerta_id) REFERENCES puertas(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE eventos (
|
||||
id INTEGER PRIMARY KEY,
|
||||
tipo TEXT NOT NULL,
|
||||
titulo TEXT NOT NULL,
|
||||
descripcion TEXT,
|
||||
hora TEXT NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
leido INTEGER NOT NULL DEFAULT 0,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE mensajes (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
texto TEXT NOT NULL,
|
||||
es_mio INTEGER NOT NULL DEFAULT 1,
|
||||
hora TEXT NOT NULL,
|
||||
timestamp TEXT NOT NULL,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE banners (
|
||||
id INTEGER PRIMARY KEY,
|
||||
badge TEXT NOT NULL,
|
||||
titulo TEXT NOT NULL,
|
||||
subtitulo TEXT,
|
||||
orden INTEGER NOT NULL DEFAULT 0,
|
||||
activo INTEGER NOT NULL DEFAULT 1,
|
||||
sincronizado INTEGER NOT NULL DEFAULT 0
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sesiones (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
usuario_id INTEGER NOT NULL,
|
||||
timestamp_inicio TEXT NOT NULL,
|
||||
timestamp_fin TEXT,
|
||||
dispositivo TEXT,
|
||||
FOREIGN KEY (usuario_id) REFERENCES usuarios(id)
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE sync_log (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp TEXT NOT NULL,
|
||||
tipo TEXT NOT NULL,
|
||||
estado TEXT NOT NULL,
|
||||
detalle TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await db.execute('''
|
||||
CREATE TABLE configuracion (
|
||||
clave TEXT PRIMARY KEY,
|
||||
valor TEXT
|
||||
)
|
||||
''');
|
||||
|
||||
await _seedData(db);
|
||||
}
|
||||
|
||||
// ─── Datos iniciales ──────────────────────────────────────────────────────
|
||||
// PIN de seed: 123456 → SHA-256 hash real generado externamente
|
||||
// echo -n "123456" | sha256sum → 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
|
||||
static const _pinSeed =
|
||||
'8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92';
|
||||
|
||||
Future<void> _seedData(Database db) async {
|
||||
// ── Zonas ──
|
||||
final zonas = [
|
||||
{'id': 1, 'codigo': 'Z-01', 'nombre': 'Lobby Principal',
|
||||
'descripcion': 'Entrada · 3 cámaras · 2 sensores', 'estado': 'segura'},
|
||||
{'id': 2, 'codigo': 'Z-02', 'nombre': 'Muelle de Carga',
|
||||
'descripcion': 'Carga/descarga · 2 cámaras · 1 sensor', 'estado': 'segura'},
|
||||
{'id': 3, 'codigo': 'Z-03', 'nombre': 'Centro de Datos',
|
||||
'descripcion': 'Sala servidores · 4 cámaras · 3 sensores', 'estado': 'segura'},
|
||||
{'id': 4, 'codigo': 'Z-04', 'nombre': 'Almacén G-4',
|
||||
'descripcion': 'Bodega · 2 cámaras · 4 sensores', 'estado': 'alerta'},
|
||||
{'id': 5, 'codigo': 'Z-05', 'nombre': 'Perímetro Norte',
|
||||
'descripcion': 'Cerca · 4 cámaras', 'estado': 'segura'},
|
||||
{'id': 6, 'codigo': 'Z-06', 'nombre': 'Sala de Servidores A',
|
||||
'descripcion': 'TI · 1 cámara · 2 sensores humo', 'estado': 'segura'},
|
||||
];
|
||||
for (final z in zonas) {
|
||||
await db.insert('zonas', {...z, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Puertas ──
|
||||
final puertas = [
|
||||
{'id': 1, 'zona_id': 1, 'nombre': 'Lobby Principal',
|
||||
'codigo': 'Entrada 01', 'bloqueada': 0},
|
||||
{'id': 2, 'zona_id': 2, 'nombre': 'Muelle de Carga',
|
||||
'codigo': 'Carga 02', 'bloqueada': 0},
|
||||
{'id': 3, 'zona_id': 3, 'nombre': 'Centro de Datos',
|
||||
'codigo': 'Datos 03', 'bloqueada': 1},
|
||||
];
|
||||
for (final p in puertas) {
|
||||
await db.insert('puertas', {...p, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Usuarios ──
|
||||
await db.insert('usuarios', {
|
||||
'id': 1,
|
||||
'nombre': 'Juan Díaz',
|
||||
'iniciales': 'JD',
|
||||
'nivel_acceso': 3,
|
||||
'pin_hash': _pinSeed,
|
||||
'areas': '[1,2,3,4,5,6]',
|
||||
'fecha_inicio': '2026-01-01T00:00:00',
|
||||
'fecha_fin': null,
|
||||
'activo': 1,
|
||||
'sincronizado': 1,
|
||||
});
|
||||
|
||||
// ── Alarmas históricas ──
|
||||
final ahora = DateTime.now();
|
||||
final alarmas = [
|
||||
{
|
||||
'id': 1, 'zona_id': 4, 'tipo': 'intrusion', 'severidad': 5,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||
'estado': 'activa', 'resuelto_por': null, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 2, 'zona_id': 6, 'tipo': 'humo', 'severidad': 3,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': 'Sensor calibrado',
|
||||
},
|
||||
{
|
||||
'id': 3, 'zona_id': 5, 'tipo': 'movimiento', 'severidad': 2,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3, minutes: 20)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 4, 'zona_id': 2, 'tipo': 'acceso', 'severidad': 1,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 5)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
{
|
||||
'id': 5, 'zona_id': 1, 'tipo': 'intrusion', 'severidad': 2,
|
||||
'timestamp': ahora.subtract(const Duration(days: 1)).toIso8601String(),
|
||||
'estado': 'resuelta', 'resuelto_por': 1, 'notas': null,
|
||||
},
|
||||
];
|
||||
for (final a in alarmas) {
|
||||
await db.insert('alarmas', {...a, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Accesos ──
|
||||
final accesos = [
|
||||
{
|
||||
'id': 1, 'usuario_id': 1, 'puerta_id': 2,
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 95)).toIso8601String(),
|
||||
'autorizado': 1, 'metodo': 'remoto',
|
||||
},
|
||||
{
|
||||
'id': 2, 'usuario_id': 1, 'puerta_id': 1,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2, minutes: 30)).toIso8601String(),
|
||||
'autorizado': 0, 'metodo': 'pin',
|
||||
},
|
||||
{
|
||||
'id': 3, 'usuario_id': 1, 'puerta_id': 3,
|
||||
'timestamp': ahora.subtract(const Duration(hours: 4)).toIso8601String(),
|
||||
'autorizado': 1, 'metodo': 'pin',
|
||||
},
|
||||
];
|
||||
for (final a in accesos) {
|
||||
await db.insert('accesos', {...a, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Eventos del log de InicioPage ──
|
||||
final eventos = [
|
||||
{
|
||||
'id': 1, 'tipo': 'alerta',
|
||||
'titulo': 'Alerta Crítica',
|
||||
'descripcion': 'Zona G-4: Sensor de movimiento activado.',
|
||||
'hora': '09:41 AM',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 30)).toIso8601String(),
|
||||
'leido': 0,
|
||||
},
|
||||
{
|
||||
'id': 2, 'tipo': 'noticia',
|
||||
'titulo': 'Noticia',
|
||||
'descripcion': 'Actualización de firmware en nodos de la Zona Z-03.',
|
||||
'hora': '08:15 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 2)).toIso8601String(),
|
||||
'leido': 1,
|
||||
},
|
||||
{
|
||||
'id': 3, 'tipo': 'notificacion',
|
||||
'titulo': 'Notificación',
|
||||
'descripcion': 'Turno nocturno confirmado para el Sector Norte.',
|
||||
'hora': '07:00 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 3)).toIso8601String(),
|
||||
'leido': 1,
|
||||
},
|
||||
{
|
||||
'id': 4, 'tipo': 'general',
|
||||
'titulo': 'Evento General',
|
||||
'descripcion': 'Backup del sistema completado correctamente.',
|
||||
'hora': '02:00 AM',
|
||||
'timestamp': ahora.subtract(const Duration(hours: 8)).toIso8601String(),
|
||||
'leido': 1,
|
||||
},
|
||||
];
|
||||
for (final e in eventos) {
|
||||
await db.insert('eventos', {...e, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Mensajes del chat ──
|
||||
final mensajes = [
|
||||
{
|
||||
'texto': 'Central de monitoreo en línea. ¿En qué podemos ayudarle?',
|
||||
'es_mio': 0, 'hora': '09:30',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 45)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Todo en orden por el momento. Revisando sector norte.',
|
||||
'es_mio': 1, 'hora': '09:32',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 43)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Recibido. Se detectó movimiento en zona G-4, ¿confirma?',
|
||||
'es_mio': 0, 'hora': '09:38',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 37)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Afirmativo. Voy a verificar en persona.',
|
||||
'es_mio': 1, 'hora': '09:39',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 36)).toIso8601String(),
|
||||
},
|
||||
{
|
||||
'texto': 'Entendido. Enviamos unidad de respaldo. ETA: 8 minutos.',
|
||||
'es_mio': 0, 'hora': '09:40',
|
||||
'timestamp': ahora.subtract(const Duration(minutes: 35)).toIso8601String(),
|
||||
},
|
||||
];
|
||||
for (final m in mensajes) {
|
||||
await db.insert('mensajes', {...m, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Banners ──
|
||||
final banners = [
|
||||
{
|
||||
'id': 1, 'badge': 'Premium Access',
|
||||
'titulo': 'Sector Norte Asegurado',
|
||||
'subtitulo': 'Patrullaje nocturno completado · Sin incidencias',
|
||||
'orden': 0, 'activo': 1,
|
||||
},
|
||||
{
|
||||
'id': 2, 'badge': 'Alerta Activa',
|
||||
'titulo': 'Zona G-4 en Revisión',
|
||||
'subtitulo': 'Movimiento detectado · Unidad en camino',
|
||||
'orden': 1, 'activo': 1,
|
||||
},
|
||||
{
|
||||
'id': 3, 'badge': 'Sistema OK',
|
||||
'titulo': '24 Nodos en Línea',
|
||||
'subtitulo': 'Todos los sectores operativos',
|
||||
'orden': 2, 'activo': 1,
|
||||
},
|
||||
];
|
||||
for (final b in banners) {
|
||||
await db.insert('banners', {...b, 'sincronizado': 1});
|
||||
}
|
||||
|
||||
// ── Configuración inicial ──
|
||||
final config = [
|
||||
{'clave': 'usuario_activo_id', 'valor': '1'},
|
||||
{'clave': 'notificaciones_activas', 'valor': 'true'},
|
||||
{'clave': 'api_base_url', 'valor': ''},
|
||||
{'clave': 'api_token', 'valor': ''},
|
||||
{'clave': 'api_token_expiry', 'valor': ''},
|
||||
];
|
||||
for (final c in config) {
|
||||
await db.insert('configuracion', c);
|
||||
}
|
||||
}
|
||||
}
|
||||
+63
-17
@@ -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<LoginPage> {
|
||||
final List<FocusNode> _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<LoginPage> {
|
||||
}
|
||||
}
|
||||
|
||||
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<void> _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<LoginPage> {
|
||||
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<LoginPage> {
|
||||
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),
|
||||
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'usuario_id': usuarioId,
|
||||
'puerta_id': puertaId,
|
||||
'timestamp': timestamp,
|
||||
'autorizado': autorizado ? 1 : 0,
|
||||
'metodo': metodo,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> 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,
|
||||
);
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'badge': badge,
|
||||
'titulo': titulo,
|
||||
'subtitulo': subtitulo,
|
||||
'orden': orden,
|
||||
'activo': activo ? 1 : 0,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'tipo': tipo,
|
||||
'titulo': titulo,
|
||||
'descripcion': descripcion,
|
||||
'hora': hora,
|
||||
'timestamp': timestamp,
|
||||
'leido': leido ? 1 : 0,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
if (id != null) 'id': id,
|
||||
'texto': texto,
|
||||
'es_mio': esMio ? 1 : 0,
|
||||
'hora': hora,
|
||||
'timestamp': timestamp,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'zona_id': zonaId,
|
||||
'tipo': tipo,
|
||||
'nombre': nombre,
|
||||
'activo': activo ? 1 : 0,
|
||||
'ultima_senal': ultimaSenal,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> 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,
|
||||
);
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
if (id != null) 'id': id,
|
||||
'usuario_id': usuarioId,
|
||||
'timestamp_inicio': timestampInicio,
|
||||
'timestamp_fin': timestampFin,
|
||||
'dispositivo': dispositivo,
|
||||
};
|
||||
|
||||
bool get activa => timestampFin == null;
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> 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,
|
||||
};
|
||||
}
|
||||
@@ -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<String, dynamic> 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<String, dynamic> toMap() => {
|
||||
'id': id,
|
||||
'codigo': codigo,
|
||||
'nombre': nombre,
|
||||
'descripcion': descripcion,
|
||||
'estado': estado,
|
||||
'sincronizado': sincronizado ? 1 : 0,
|
||||
};
|
||||
}
|
||||
@@ -18,6 +18,7 @@ class _ControlAccesoPageState extends State<ControlAccesoPage> {
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
@@ -156,6 +156,7 @@ class _InicioPageState extends State<InicioPage>
|
||||
return Stack(
|
||||
children: [
|
||||
SingleChildScrollView(
|
||||
primary: false,
|
||||
padding: const EdgeInsets.fromLTRB(20, 20, 20, 88),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
|
||||
@@ -51,14 +51,13 @@ class _MonitoreoAlarmaPageState extends State<MonitoreoAlarmaPage>
|
||||
@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<MonitoreoAlarmaPage>
|
||||
);
|
||||
|
||||
// ── 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,
|
||||
|
||||
@@ -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<void> _cerrarSesion(BuildContext context) async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<SeguridadPage> createState() => _SeguridadPageState();
|
||||
}
|
||||
|
||||
class _SeguridadPageState extends State<SeguridadPage> {
|
||||
static const _keyPinHash = 'local_pin_hash';
|
||||
static const _defaultPin = '123456';
|
||||
static const _pinLen = 6;
|
||||
|
||||
// Campos del PIN
|
||||
final List<TextEditingController> _ctrlActual =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
final List<TextEditingController> _ctrlNuevo =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
final List<TextEditingController> _ctrlConfirm =
|
||||
List.generate(_pinLen, (_) => TextEditingController());
|
||||
|
||||
final List<FocusNode> _focusActual =
|
||||
List.generate(_pinLen, (_) => FocusNode());
|
||||
final List<FocusNode> _focusNuevo =
|
||||
List.generate(_pinLen, (_) => FocusNode());
|
||||
final List<FocusNode> _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<TextEditingController> ctrls) =>
|
||||
ctrls.map((c) => c.text).join();
|
||||
|
||||
String _hash(String pin) =>
|
||||
sha256.convert(utf8.encode(pin)).toString();
|
||||
|
||||
void _onDigit(List<TextEditingController> ctrls,
|
||||
List<FocusNode> focus, int i, String v) {
|
||||
if (v.isNotEmpty && i < _pinLen - 1) focus[i + 1].requestFocus();
|
||||
setState(() {});
|
||||
}
|
||||
|
||||
void _onKey(List<TextEditingController> ctrls,
|
||||
List<FocusNode> 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<void> _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<TextEditingController> ctrls,
|
||||
required List<FocusNode> 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),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
]);
|
||||
}
|
||||
+239
-212
@@ -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<SettingsPage> {
|
||||
final _formKey = GlobalKey<FormState>();
|
||||
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<String> _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<String>(
|
||||
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<int>(
|
||||
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<int>(
|
||||
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<void> _confirmarInicializarBd() async {
|
||||
final confirmar = await showDialog<bool>(
|
||||
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<void> _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<bool> 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),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -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<bool> 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<String, dynamic>;
|
||||
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<void> logout() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove(_keyToken);
|
||||
await prefs.remove(_keyExpiry);
|
||||
}
|
||||
|
||||
// ── Estado ─────────────────────────────────────────────────────────────────
|
||||
Future<bool> 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<String?> getToken() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
return prefs.getString(_keyToken);
|
||||
}
|
||||
}
|
||||
@@ -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<void> 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<void> 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<void> 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<void> 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<void> 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<void> 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<void> 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<void> pushPendientes() async {
|
||||
await _pushAlarmasPendientes();
|
||||
await _pushAccesosPendientes();
|
||||
await _pushMensajesPendientes();
|
||||
await _syncLog.registrar(tipo: 'push', estado: 'ok',
|
||||
detalle: 'Push de pendientes completado');
|
||||
}
|
||||
|
||||
Future<void> _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<void> _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<void> _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<List<Map<String, dynamic>>?> _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<Map<String, dynamic>>();
|
||||
}
|
||||
return null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, String> _headers(String token) => {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': 'Bearer $token',
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user