- 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>
408 lines
16 KiB
Dart
408 lines
16 KiB
Dart
import 'dart:io';
|
|
import 'package:flutter/material.dart';
|
|
import 'package:shared_preferences/shared_preferences.dart';
|
|
import 'package:file_picker/file_picker.dart';
|
|
import '../theme.dart';
|
|
import '../models/usuario.dart';
|
|
import '../db/dao/usuarios_dao.dart';
|
|
import '../main.dart' show LoginPage;
|
|
import 'settings_page.dart';
|
|
import 'seguridad_page.dart';
|
|
import 'mensageria_page.dart';
|
|
import 'historial_sesiones_page.dart';
|
|
|
|
class PerfilUsuarioPage extends StatefulWidget {
|
|
const PerfilUsuarioPage({Key? key}) : super(key: key);
|
|
|
|
@override
|
|
State<PerfilUsuarioPage> createState() => _PerfilUsuarioPageState();
|
|
}
|
|
|
|
class _PerfilUsuarioPageState extends State<PerfilUsuarioPage> {
|
|
final _dao = UsuariosDao();
|
|
Usuario? _usuario;
|
|
bool _cargando = true;
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_cargar();
|
|
}
|
|
|
|
Future<void> _cargar() async {
|
|
try {
|
|
final u = await _dao.getById(1);
|
|
if (mounted) setState(() { _usuario = u; _cargando = false; });
|
|
} catch (_) {
|
|
if (mounted) setState(() => _cargando = false);
|
|
}
|
|
}
|
|
|
|
// ── Calcular iniciales desde el nombre ────────────────────────────────────
|
|
String _calcularIniciales(String nombre) {
|
|
final partes = nombre.trim().split(RegExp(r'\s+'));
|
|
if (partes.length == 1) return partes[0][0].toUpperCase();
|
|
return (partes.first[0] + partes.last[0]).toUpperCase();
|
|
}
|
|
|
|
// ── Editar nombre ─────────────────────────────────────────────────────────
|
|
Future<void> _editarNombre() async {
|
|
if (_usuario == null) return;
|
|
final ctrl = TextEditingController(text: _usuario!.nombre);
|
|
|
|
final nuevoNombre = await showDialog<String>(
|
|
context: context,
|
|
builder: (_) => AlertDialog(
|
|
backgroundColor: AppColors.surfaceHigh,
|
|
title: Text('Editar nombre',
|
|
style: appHeadline(size: 16, weight: FontWeight.w700)),
|
|
content: TextField(
|
|
controller: ctrl,
|
|
autofocus: true,
|
|
style: appHeadline(size: 14),
|
|
decoration: InputDecoration(
|
|
hintText: 'Nombre completo',
|
|
hintStyle: appLabel(size: 13, color: AppColors.outline),
|
|
enabledBorder: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(8),
|
|
borderSide: const BorderSide(color: AppColors.outlineVariant),
|
|
),
|
|
focusedBorder: OutlineInputBorder(
|
|
borderRadius: BorderRadius.circular(8),
|
|
borderSide: const BorderSide(color: AppColors.primary, width: 2),
|
|
),
|
|
filled: true,
|
|
fillColor: AppColors.surfaceHighest,
|
|
contentPadding: const EdgeInsets.symmetric(
|
|
horizontal: 14, vertical: 12),
|
|
),
|
|
textCapitalization: TextCapitalization.words,
|
|
onSubmitted: (v) => Navigator.pop(context, v.trim()),
|
|
),
|
|
actions: [
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context),
|
|
child: Text('Cancelar',
|
|
style: appLabel(size: 13,
|
|
color: AppColors.onSurfaceVariant)),
|
|
),
|
|
TextButton(
|
|
onPressed: () => Navigator.pop(context, ctrl.text.trim()),
|
|
child: Text('Guardar',
|
|
style: appLabel(size: 13,
|
|
weight: FontWeight.bold, color: AppColors.primary)),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
|
|
ctrl.dispose();
|
|
if (nuevoNombre == null || nuevoNombre.isEmpty) return;
|
|
|
|
final actualizado = _usuario!.copyWith(
|
|
nombre: nuevoNombre,
|
|
iniciales: _calcularIniciales(nuevoNombre),
|
|
sincronizado: false,
|
|
);
|
|
|
|
await _dao.update(actualizado);
|
|
if (mounted) setState(() => _usuario = actualizado);
|
|
}
|
|
|
|
// ── Seleccionar foto de perfil ────────────────────────────────────────────
|
|
Future<void> _seleccionarFoto() async {
|
|
final result = await FilePicker.platform.pickFiles(
|
|
type: FileType.image,
|
|
allowMultiple: false,
|
|
);
|
|
if (result == null || result.files.isEmpty) return;
|
|
final path = result.files.first.path;
|
|
if (path == null || _usuario == null) return;
|
|
|
|
await _dao.updateFoto(_usuario!.id, path);
|
|
if (mounted) setState(() => _usuario = _usuario!.copyWith(fotoPath: path));
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
if (_cargando) {
|
|
return const Center(
|
|
child: CircularProgressIndicator(color: AppColors.primary));
|
|
}
|
|
|
|
final nombre = _usuario?.nombre ?? 'Sin nombre';
|
|
final iniciales = _usuario?.iniciales ?? '?';
|
|
final nivel = _usuario?.nivelAcceso ?? 1;
|
|
final nivelLabel = nivel >= 3 ? 'ACCESO TOTAL' : 'ACCESO NIVEL $nivel';
|
|
|
|
return SingleChildScrollView(
|
|
primary: false,
|
|
padding: const EdgeInsets.fromLTRB(24, 24, 24, 24),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
_avatarCard(nombre, iniciales, nivel, nivelLabel),
|
|
const SizedBox(height: 24),
|
|
_statsGrid(),
|
|
const SizedBox(height: 32),
|
|
_seccionOpciones(context),
|
|
const SizedBox(height: 32),
|
|
_botonCerrarSesion(context),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// ── Avatar + info ──────────────────────────────────────────────────────────
|
|
Widget _avatarCard(String nombre, String iniciales, int nivel,
|
|
String nivelLabel) =>
|
|
Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(24),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceHigh,
|
|
borderRadius: BorderRadius.circular(12)),
|
|
child: Column(children: [
|
|
Stack(clipBehavior: Clip.none, children: [
|
|
// ── Círculo avatar ───────────────────────────────────────────
|
|
GestureDetector(
|
|
onTap: _seleccionarFoto,
|
|
child: Container(
|
|
width: 80, height: 80,
|
|
decoration: BoxDecoration(
|
|
shape: BoxShape.circle,
|
|
gradient: _usuario?.fotoPath == null
|
|
? const LinearGradient(
|
|
colors: [AppColors.primary, AppColors.primaryContainer],
|
|
begin: Alignment.topLeft,
|
|
end: Alignment.bottomRight,
|
|
)
|
|
: null,
|
|
boxShadow: [BoxShadow(
|
|
color: AppColors.primary.withOpacity(0.3),
|
|
blurRadius: 20, spreadRadius: 2,
|
|
)],
|
|
),
|
|
child: ClipOval(
|
|
child: _usuario?.fotoPath != null
|
|
? Image.file(
|
|
File(_usuario!.fotoPath!),
|
|
width: 80, height: 80,
|
|
fit: BoxFit.cover,
|
|
errorBuilder: (_, __, ___) => _avatarIniciales(iniciales),
|
|
)
|
|
: _avatarIniciales(iniciales),
|
|
),
|
|
),
|
|
),
|
|
// ── Botón cámara ─────────────────────────────────────────────
|
|
Positioned(
|
|
bottom: 0, right: 0,
|
|
child: GestureDetector(
|
|
onTap: _seleccionarFoto,
|
|
child: Container(
|
|
width: 26, height: 26,
|
|
decoration: BoxDecoration(
|
|
color: AppColors.primary,
|
|
shape: BoxShape.circle,
|
|
border: Border.all(
|
|
color: AppColors.surfaceHigh, width: 2),
|
|
),
|
|
child: const Icon(Icons.camera_alt,
|
|
size: 13, color: AppColors.primaryContainer),
|
|
),
|
|
),
|
|
),
|
|
]),
|
|
const SizedBox(height: 16),
|
|
// ── Nombre con botón editar ──────────────────────────────────
|
|
Row(mainAxisAlignment: MainAxisAlignment.center, children: [
|
|
Text(nombre,
|
|
style: appHeadline(size: 20, weight: FontWeight.w800)),
|
|
const SizedBox(width: 8),
|
|
GestureDetector(
|
|
onTap: _editarNombre,
|
|
child: const Icon(Icons.edit,
|
|
size: 15, color: AppColors.primary),
|
|
),
|
|
]),
|
|
const SizedBox(height: 4),
|
|
Text('Operador de Seguridad', style: appLabel(size: 13)),
|
|
const SizedBox(height: 12),
|
|
Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.primaryContainer,
|
|
borderRadius: BorderRadius.circular(99)),
|
|
child: Text('NIVEL $nivel · $nivelLabel',
|
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
|
color: AppColors.primary, spacing: 1.5)),
|
|
),
|
|
]),
|
|
);
|
|
|
|
Widget _avatarIniciales(String iniciales) => Center(
|
|
child: Text(iniciales,
|
|
style: appHeadline(
|
|
size: 28,
|
|
weight: FontWeight.w800,
|
|
color: AppColors.primaryContainer)),
|
|
);
|
|
|
|
// ── Estadísticas ───────────────────────────────────────────────────────────
|
|
Widget _statsGrid() => Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('ESTADÍSTICAS DEL TURNO',
|
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
|
color: AppColors.onSurfaceVariant, spacing: 2.0)),
|
|
const SizedBox(height: 12),
|
|
Row(children: [
|
|
Expanded(child: _statItem('142', 'Alarmas\ngestionadas',
|
|
Icons.notifications_active, AppColors.primary)),
|
|
const SizedBox(width: 12),
|
|
Expanded(child: _statItem('38', 'Accesos\nautorizados',
|
|
Icons.lock_open, AppColors.secondary)),
|
|
const SizedBox(width: 12),
|
|
Expanded(child: _statItem('03', 'Alertas\nactivas',
|
|
Icons.warning, AppColors.error)),
|
|
]),
|
|
],
|
|
);
|
|
|
|
Widget _statItem(String valor, String label, IconData icon, Color color) =>
|
|
Container(
|
|
padding: const EdgeInsets.all(14),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceLow,
|
|
borderRadius: BorderRadius.circular(12)),
|
|
child: Column(children: [
|
|
Icon(icon, color: color, size: 20),
|
|
const SizedBox(height: 8),
|
|
Text(valor, style: appHeadline(size: 22, color: color)),
|
|
const SizedBox(height: 4),
|
|
Text(label, style: appLabel(size: 10), textAlign: TextAlign.center),
|
|
]),
|
|
);
|
|
|
|
// ── Opciones ───────────────────────────────────────────────────────────────
|
|
Widget _seccionOpciones(BuildContext context) => Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('CUENTA',
|
|
style: appLabel(size: 10, weight: FontWeight.bold,
|
|
color: AppColors.onSurfaceVariant, spacing: 2.0)),
|
|
const SizedBox(height: 12),
|
|
_opcionItem(Icons.settings, 'Configuración',
|
|
'Notificaciones, sonido y alarmas', () {
|
|
Navigator.push(context,
|
|
MaterialPageRoute(builder: (_) => const SettingsPage()));
|
|
}),
|
|
const Divider(color: AppColors.outlineVariant, height: 1),
|
|
_opcionItem(Icons.shield_outlined, 'Seguridad',
|
|
'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', () {
|
|
Navigator.push(context,
|
|
MaterialPageRoute(
|
|
builder: (_) => const HistorialSesionesPage()));
|
|
}),
|
|
const Divider(color: AppColors.outlineVariant, height: 1),
|
|
_opcionItem(Icons.help_outline, 'Ayuda y soporte',
|
|
'Contactar con soporte técnico', () {
|
|
Navigator.push(context,
|
|
MaterialPageRoute(builder: (_) => const MensajeriaPage()));
|
|
}),
|
|
],
|
|
);
|
|
|
|
Widget _opcionItem(IconData icon, String titulo, String subtitulo,
|
|
VoidCallback onTap) =>
|
|
InkWell(
|
|
onTap: onTap,
|
|
borderRadius: BorderRadius.circular(8),
|
|
child: Padding(
|
|
padding: const EdgeInsets.symmetric(vertical: 14),
|
|
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)),
|
|
const SizedBox(height: 2),
|
|
Text(subtitulo, style: appLabel(size: 12)),
|
|
],
|
|
)),
|
|
const Icon(Icons.chevron_right,
|
|
color: AppColors.outlineVariant, size: 20),
|
|
]),
|
|
),
|
|
);
|
|
|
|
// ── Cerrar sesión ──────────────────────────────────────────────────────────
|
|
Widget _botonCerrarSesion(BuildContext context) => SizedBox(
|
|
width: double.infinity,
|
|
child: OutlinedButton.icon(
|
|
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,
|
|
color: AppColors.error)),
|
|
style: OutlinedButton.styleFrom(
|
|
side: const BorderSide(color: AppColors.error, width: 1),
|
|
padding: const EdgeInsets.symmetric(vertical: 14),
|
|
shape: RoundedRectangleBorder(
|
|
borderRadius: BorderRadius.circular(12)),
|
|
),
|
|
),
|
|
);
|
|
|
|
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;
|
|
|
|
final prefs = await SharedPreferences.getInstance();
|
|
await prefs.remove('autologin');
|
|
|
|
Navigator.of(context).pushAndRemoveUntil(
|
|
MaterialPageRoute(builder: (_) => const LoginPage()),
|
|
(_) => false,
|
|
);
|
|
}
|
|
}
|