- file_picker ^4.6.1 — abre galería/archivos (en Android incluye cámara) - BD v3: columna foto_path en usuarios, migración onUpgrade - Usuario modelo: campo fotoPath + copyWith - UsuariosDao: método updateFoto(id, path) - PerfilUsuarioPage: · Avatar muestra foto si hay, iniciales si no · Toque en avatar o ícono cámara → FilePicker → guarda ruta en BD · Ícono editar nombre movido junto al texto del nombre Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
412 lines
14 KiB
Dart
412 lines
14 KiB
Dart
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 = 3;
|
|
|
|
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 String dbDir;
|
|
if (Platform.isLinux) {
|
|
final home = Platform.environment['HOME'] ?? Directory.current.path;
|
|
final dir = Directory(join(home, '.local', 'share', 'sentinel_one'));
|
|
if (!dir.existsSync()) dir.createSync(recursive: true);
|
|
dbDir = dir.path;
|
|
} else {
|
|
// Windows: junto al ejecutable
|
|
dbDir = Directory.current.path;
|
|
}
|
|
return databaseFactoryFfi.openDatabase(
|
|
join(dbDir, _dbName),
|
|
options: OpenDatabaseOptions(
|
|
version: _dbVersion,
|
|
onCreate: _onCreate,
|
|
onUpgrade: _onUpgrade,
|
|
),
|
|
);
|
|
}
|
|
final path = join(await getDatabasesPath(), _dbName);
|
|
return openDatabase(
|
|
path,
|
|
version: _dbVersion,
|
|
onCreate: _onCreate,
|
|
onUpgrade: _onUpgrade,
|
|
);
|
|
}
|
|
|
|
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,
|
|
foto_path TEXT
|
|
)
|
|
''');
|
|
|
|
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 _createTablesV2(db);
|
|
await _seedData(db);
|
|
}
|
|
|
|
Future<void> _onUpgrade(Database db, int oldVersion, int newVersion) async {
|
|
if (oldVersion < 2) {
|
|
await _createTablesV2(db);
|
|
await _seedDataV2(db);
|
|
}
|
|
if (oldVersion < 3) {
|
|
await db.execute(
|
|
'ALTER TABLE usuarios ADD COLUMN foto_path TEXT');
|
|
}
|
|
}
|
|
|
|
Future<void> _createTablesV2(Database db) async {
|
|
await db.execute('''
|
|
CREATE TABLE IF NOT EXISTS clientes (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
nombre TEXT NOT NULL,
|
|
telefono TEXT,
|
|
email TEXT,
|
|
direccion TEXT,
|
|
sincronizado INTEGER NOT NULL DEFAULT 0
|
|
)
|
|
''');
|
|
|
|
await db.execute('''
|
|
CREATE TABLE IF NOT EXISTS suscripciones (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
cliente_id INTEGER NOT NULL,
|
|
nombre_servicio TEXT NOT NULL,
|
|
tipo TEXT NOT NULL DEFAULT 'hogar',
|
|
plan TEXT NOT NULL DEFAULT 'basico',
|
|
estado TEXT NOT NULL DEFAULT 'activa',
|
|
fecha_inicio TEXT NOT NULL,
|
|
fecha_vencimiento TEXT NOT NULL,
|
|
monto REAL NOT NULL DEFAULT 0.0,
|
|
moneda TEXT NOT NULL DEFAULT 'USD',
|
|
notas TEXT,
|
|
sincronizado INTEGER NOT NULL DEFAULT 0,
|
|
FOREIGN KEY (cliente_id) REFERENCES clientes(id)
|
|
)
|
|
''');
|
|
}
|
|
|
|
Future<void> _seedDataV2(Database db) async {
|
|
await _seedClientes(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': 'Usuario Sistema',
|
|
'iniciales': 'US',
|
|
'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,
|
|
});
|
|
|
|
// ── Banners ──
|
|
// Nota: alarmas, accesos, eventos, mensajes y sesiones NO se insertan en seed.
|
|
// Se cargan vía DemoDataService (datos de prueba) o Sincronizador (datos reales).
|
|
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);
|
|
}
|
|
|
|
await _seedClientes(db);
|
|
}
|
|
|
|
Future<void> _seedClientes(Database db) async {
|
|
final hoy = DateTime.now();
|
|
|
|
// ── Clientes de ejemplo ──
|
|
final clientes = [
|
|
{'id': 1, 'nombre': 'Pedro García', 'telefono': '5551-0001',
|
|
'email': 'pedro@email.com', 'direccion': 'Zona 10, Ciudad'},
|
|
{'id': 2, 'nombre': 'Empresa XYZ S.A.', 'telefono': '5552-0002',
|
|
'email': 'admin@xyz.com', 'direccion': 'Zona 4, Ciudad'},
|
|
{'id': 3, 'nombre': 'María López', 'telefono': '5553-0003',
|
|
'email': 'maria@email.com', 'direccion': 'Zona 15, Ciudad'},
|
|
];
|
|
for (final c in clientes) {
|
|
await db.insert('clientes', {...c, 'sincronizado': 1});
|
|
}
|
|
|
|
// ── Suscripciones de ejemplo ──
|
|
final suscripciones = [
|
|
// Pedro García — Casa activa, Negocio próximo a vencer
|
|
{
|
|
'cliente_id': 1, 'nombre_servicio': 'Casa Principal',
|
|
'tipo': 'hogar', 'plan': 'premium', 'estado': 'activa',
|
|
'fecha_inicio': hoy.subtract(const Duration(days: 180)).toIso8601String().substring(0, 10),
|
|
'fecha_vencimiento': hoy.add(const Duration(days: 30)).toIso8601String().substring(0, 10),
|
|
'monto': 49.99, 'moneda': 'USD', 'notas': null,
|
|
},
|
|
{
|
|
'cliente_id': 1, 'nombre_servicio': 'Negocio Centro',
|
|
'tipo': 'comercial', 'plan': 'estandar', 'estado': 'activa',
|
|
'fecha_inicio': hoy.subtract(const Duration(days: 90)).toIso8601String().substring(0, 10),
|
|
'fecha_vencimiento': hoy.add(const Duration(days: 5)).toIso8601String().substring(0, 10),
|
|
'monto': 35.00, 'moneda': 'USD', 'notas': 'Próximo a vencer',
|
|
},
|
|
// Empresa XYZ — Activa y suspendida
|
|
{
|
|
'cliente_id': 2, 'nombre_servicio': 'Oficinas Principales',
|
|
'tipo': 'comercial', 'plan': 'premium', 'estado': 'activa',
|
|
'fecha_inicio': hoy.subtract(const Duration(days: 365)).toIso8601String().substring(0, 10),
|
|
'fecha_vencimiento': hoy.add(const Duration(days: 60)).toIso8601String().substring(0, 10),
|
|
'monto': 120.00, 'moneda': 'USD', 'notas': null,
|
|
},
|
|
{
|
|
'cliente_id': 2, 'nombre_servicio': 'Bodega Norte',
|
|
'tipo': 'industrial', 'plan': 'basico', 'estado': 'suspendida',
|
|
'fecha_inicio': hoy.subtract(const Duration(days: 200)).toIso8601String().substring(0, 10),
|
|
'fecha_vencimiento': hoy.subtract(const Duration(days: 10)).toIso8601String().substring(0, 10),
|
|
'monto': 20.00, 'moneda': 'USD', 'notas': 'Suspendida por falta de pago',
|
|
},
|
|
// María López — Vencida
|
|
{
|
|
'cliente_id': 3, 'nombre_servicio': 'Residencia',
|
|
'tipo': 'hogar', 'plan': 'basico', 'estado': 'vencida',
|
|
'fecha_inicio': hoy.subtract(const Duration(days: 400)).toIso8601String().substring(0, 10),
|
|
'fecha_vencimiento': hoy.subtract(const Duration(days: 30)).toIso8601String().substring(0, 10),
|
|
'monto': 15.00, 'moneda': 'USD', 'notas': null,
|
|
},
|
|
];
|
|
for (final s in suscripciones) {
|
|
await db.insert('suscripciones', {...s, 'sincronizado': 1});
|
|
}
|
|
}
|
|
}
|