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
+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),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user