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