499 lines
17 KiB
Dart
499 lines
17 KiB
Dart
import 'dart:convert';
|
||
import 'package:crypto/crypto.dart';
|
||
import 'package:flutter/material.dart';
|
||
import 'package:flutter/services.dart';
|
||
import '../theme.dart';
|
||
import '../db/dao/usuarios_dao.dart';
|
||
import '../db/dao/zonas_dao.dart';
|
||
import '../models/zona.dart';
|
||
import '../services/whatsapp_alert_service.dart';
|
||
|
||
class RegistrarUsuarioPage extends StatefulWidget {
|
||
const RegistrarUsuarioPage({Key? key}) : super(key: key);
|
||
|
||
@override
|
||
State<RegistrarUsuarioPage> createState() => _RegistrarUsuarioPageState();
|
||
}
|
||
|
||
class _RegistrarUsuarioPageState extends State<RegistrarUsuarioPage> {
|
||
final _formKey = GlobalKey<FormState>();
|
||
final _nombreCtrl = TextEditingController();
|
||
final _pinCtrl = TextEditingController();
|
||
// Controlador para el número de teléfono con código de país para alertas WhatsApp
|
||
final _telefonoCtrl = TextEditingController();
|
||
final _dao = UsuariosDao();
|
||
final _zonasDao = ZonasDao();
|
||
|
||
int _nivelAcceso = 1;
|
||
final Set<int> _zonasSeleccionadas = {};
|
||
List<Zona> _zonas = [];
|
||
DateTime _fechaInicio = DateTime.now();
|
||
DateTime? _fechaFin;
|
||
bool _guardando = false;
|
||
bool _pinVisible = false;
|
||
|
||
static const _nivelesId = [1, 2, 3, 4, 5];
|
||
static const _nivelesLabel = ['Visitante', 'Empleado', 'Supervisor', 'Admin', 'Super Admin'];
|
||
static const _nivelesColor = [
|
||
AppColors.outline,
|
||
AppColors.secondary,
|
||
AppColors.primary,
|
||
AppColors.tertiary,
|
||
AppColors.error,
|
||
];
|
||
|
||
@override
|
||
void initState() {
|
||
super.initState();
|
||
_cargarZonas();
|
||
}
|
||
|
||
Future<void> _cargarZonas() async {
|
||
final z = await _zonasDao.getAll();
|
||
if (!mounted) return;
|
||
setState(() => _zonas = z);
|
||
}
|
||
|
||
@override
|
||
void dispose() {
|
||
_nombreCtrl.dispose();
|
||
_pinCtrl.dispose();
|
||
_telefonoCtrl.dispose();
|
||
super.dispose();
|
||
}
|
||
|
||
String _calcularIniciales(String nombre) {
|
||
final partes = nombre.trim().split(RegExp(r'\s+'));
|
||
if (partes.length >= 2) {
|
||
return '${partes.first[0]}${partes.last[0]}'.toUpperCase();
|
||
}
|
||
return nombre.isNotEmpty ? nombre[0].toUpperCase() : '?';
|
||
}
|
||
|
||
String _hashPin(String pin) =>
|
||
sha256.convert(utf8.encode(pin)).toString();
|
||
|
||
String _formatFecha(DateTime dt) =>
|
||
'${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')}/${dt.year}';
|
||
|
||
Future<void> _seleccionarFecha({required bool esFin}) async {
|
||
final inicial = esFin ? (_fechaFin ?? _fechaInicio) : _fechaInicio;
|
||
final picked = await showDatePicker(
|
||
context: context,
|
||
initialDate: inicial,
|
||
firstDate: esFin ? _fechaInicio : DateTime(2020),
|
||
lastDate: DateTime(2035),
|
||
builder: (ctx, child) => Theme(
|
||
data: Theme.of(ctx).copyWith(
|
||
colorScheme: const ColorScheme.dark(
|
||
primary: AppColors.primary,
|
||
onPrimary: AppColors.primaryContainer,
|
||
surface: AppColors.surfaceHigh,
|
||
onSurface: AppColors.onSurface,
|
||
),
|
||
),
|
||
child: child!,
|
||
),
|
||
);
|
||
if (picked == null) return;
|
||
setState(() {
|
||
if (esFin) {
|
||
_fechaFin = picked;
|
||
} else {
|
||
_fechaInicio = picked;
|
||
if (_fechaFin != null && _fechaFin!.isBefore(_fechaInicio)) {
|
||
_fechaFin = null;
|
||
}
|
||
}
|
||
});
|
||
}
|
||
|
||
Future<void> _guardar() async {
|
||
if (!_formKey.currentState!.validate()) return;
|
||
setState(() => _guardando = true);
|
||
try {
|
||
final areas = _zonasSeleccionadas.isEmpty
|
||
? null
|
||
: _zonas
|
||
.where((z) => _zonasSeleccionadas.contains(z.id))
|
||
.map((z) => z.codigo)
|
||
.join(',');
|
||
// Normaliza y valida el teléfono según estándar E.164
|
||
final telRaw = _telefonoCtrl.text.trim();
|
||
final telefonoNormalizado = telRaw.isEmpty
|
||
? null
|
||
: WhatsAppAlertService.normalizarTelefono(telRaw);
|
||
|
||
await _dao.registrar(
|
||
nombre: _nombreCtrl.text.trim(),
|
||
iniciales: _calcularIniciales(_nombreCtrl.text),
|
||
nivelAcceso: _nivelAcceso,
|
||
pinHash: _hashPin(_pinCtrl.text.trim()),
|
||
areas: areas,
|
||
fechaInicio: _fechaInicio.toIso8601String(),
|
||
fechaFin: _fechaFin?.toIso8601String(),
|
||
telefono: telefonoNormalizado,
|
||
);
|
||
if (!mounted) return;
|
||
Navigator.pop(context, true);
|
||
} catch (e) {
|
||
if (!mounted) return;
|
||
ScaffoldMessenger.of(context).showSnackBar(
|
||
SnackBar(
|
||
backgroundColor: AppColors.error,
|
||
content: Text('Error al guardar: $e',
|
||
style: appLabel(color: Colors.white)),
|
||
),
|
||
);
|
||
} finally {
|
||
if (mounted) setState(() => _guardando = false);
|
||
}
|
||
}
|
||
|
||
@override
|
||
Widget build(BuildContext context) {
|
||
return Scaffold(
|
||
backgroundColor: AppColors.surfaceLowest,
|
||
appBar: AppBar(
|
||
backgroundColor: AppColors.surfaceLow,
|
||
elevation: 0,
|
||
leading: IconButton(
|
||
icon: const Icon(Icons.close,
|
||
color: AppColors.onSurface, size: 22),
|
||
onPressed: () => Navigator.pop(context),
|
||
),
|
||
title: Text('Registrar Usuario',
|
||
style: appHeadline(size: 17, weight: FontWeight.w700)),
|
||
actions: [
|
||
if (_guardando)
|
||
const Padding(
|
||
padding: EdgeInsets.all(16),
|
||
child: SizedBox(
|
||
width: 20,
|
||
height: 20,
|
||
child: CircularProgressIndicator(
|
||
strokeWidth: 2, color: AppColors.primary)),
|
||
)
|
||
else
|
||
TextButton(
|
||
onPressed: _guardar,
|
||
child: Text('GUARDAR',
|
||
style: appLabel(
|
||
weight: FontWeight.bold, color: AppColors.primary)),
|
||
),
|
||
],
|
||
),
|
||
body: Form(
|
||
key: _formKey,
|
||
child: SingleChildScrollView(
|
||
primary: false,
|
||
padding: const EdgeInsets.fromLTRB(20, 24, 20, 40),
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
_seccion('Datos personales'),
|
||
const SizedBox(height: 12),
|
||
_campoNombre(),
|
||
const SizedBox(height: 16),
|
||
_campoPin(),
|
||
const SizedBox(height: 16),
|
||
// Campo para asociar el WhatsApp del usuario con validación Regex de país
|
||
_campoTelefono(),
|
||
const SizedBox(height: 28),
|
||
_seccion('Nivel de acceso'),
|
||
const SizedBox(height: 12),
|
||
_selectorNivel(),
|
||
const SizedBox(height: 28),
|
||
_seccion('Áreas permitidas'),
|
||
const SizedBox(height: 4),
|
||
Text(
|
||
_zonas.isEmpty
|
||
? 'Sin zonas en el sistema — carga datos de demo primero'
|
||
: 'Sin selección = acceso a todas las áreas',
|
||
style: appLabel(
|
||
size: 11, color: AppColors.onSurfaceVariant),
|
||
),
|
||
const SizedBox(height: 12),
|
||
if (_zonas.isNotEmpty) _selectorAreas(),
|
||
const SizedBox(height: 28),
|
||
_seccion('Vigencia'),
|
||
const SizedBox(height: 12),
|
||
_selectorFechas(),
|
||
],
|
||
),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
|
||
Widget _seccion(String titulo) => Text(titulo,
|
||
style: appHeadline(
|
||
size: 13,
|
||
weight: FontWeight.w700,
|
||
color: AppColors.onSurfaceVariant,
|
||
spacing: 1.0));
|
||
|
||
// ── Campo nombre ──────────────────────────────────────────────────────────
|
||
Widget _campoNombre() => TextFormField(
|
||
controller: _nombreCtrl,
|
||
style: appLabel(size: 15, color: AppColors.onSurface),
|
||
textCapitalization: TextCapitalization.words,
|
||
decoration: _inputDeco(
|
||
label: 'Nombre completo',
|
||
icon: Icons.person_outline,
|
||
),
|
||
validator: (v) {
|
||
if (v == null || v.trim().isEmpty) return 'Campo requerido';
|
||
if (v.trim().length < 3) return 'Mínimo 3 caracteres';
|
||
return null;
|
||
},
|
||
);
|
||
|
||
// ── Campo PIN ─────────────────────────────────────────────────────────────
|
||
Widget _campoPin() => TextFormField(
|
||
controller: _pinCtrl,
|
||
style: appLabel(size: 15, color: AppColors.onSurface),
|
||
obscureText: !_pinVisible,
|
||
keyboardType: TextInputType.number,
|
||
inputFormatters: [
|
||
FilteringTextInputFormatter.digitsOnly,
|
||
LengthLimitingTextInputFormatter(6),
|
||
],
|
||
decoration: _inputDeco(
|
||
label: 'PIN de acceso (4–6 dígitos)',
|
||
icon: Icons.lock_outline,
|
||
suffix: IconButton(
|
||
icon: Icon(
|
||
_pinVisible ? Icons.visibility_off : Icons.visibility,
|
||
color: AppColors.outline,
|
||
size: 20,
|
||
),
|
||
onPressed: () => setState(() => _pinVisible = !_pinVisible),
|
||
),
|
||
),
|
||
validator: (v) {
|
||
if (v == null || v.isEmpty) return 'Campo requerido';
|
||
if (v.length < 4) return 'Mínimo 4 dígitos';
|
||
return null;
|
||
},
|
||
);
|
||
|
||
// ── Campo Teléfono WhatsApp (opcional con validación estricta E.164) ──────
|
||
Widget _campoTelefono() => TextFormField(
|
||
controller: _telefonoCtrl,
|
||
style: appLabel(size: 15, color: AppColors.onSurface),
|
||
keyboardType: TextInputType.phone,
|
||
decoration: _inputDeco(
|
||
label: 'WhatsApp alertas (ej. +5939XXXXXXXX)',
|
||
icon: Icons.phone_android,
|
||
),
|
||
validator: (v) {
|
||
if (v == null || v.trim().isEmpty) return null;
|
||
final limpio = WhatsAppAlertService.normalizarTelefono(v);
|
||
if (limpio.startsWith('0')) {
|
||
return 'No debe iniciar con 0. Incluye código país (ej. +593...)';
|
||
}
|
||
if (!WhatsAppAlertService.esNumeroValido(limpio)) {
|
||
return 'Código de país obligatorio (ej. +5939XXXXXXXX)';
|
||
}
|
||
return null;
|
||
},
|
||
);
|
||
|
||
InputDecoration _inputDeco({
|
||
required String label,
|
||
required IconData icon,
|
||
Widget? suffix,
|
||
}) =>
|
||
InputDecoration(
|
||
labelText: label,
|
||
labelStyle: appLabel(color: AppColors.outline),
|
||
prefixIcon: Icon(icon, color: AppColors.outline, size: 20),
|
||
suffixIcon: suffix,
|
||
filled: true,
|
||
fillColor: AppColors.surfaceHigh,
|
||
border: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(10),
|
||
borderSide: BorderSide.none,
|
||
),
|
||
focusedBorder: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(10),
|
||
borderSide: const BorderSide(color: AppColors.primary, width: 1.5),
|
||
),
|
||
errorBorder: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(10),
|
||
borderSide: const BorderSide(color: AppColors.error, width: 1.5),
|
||
),
|
||
focusedErrorBorder: OutlineInputBorder(
|
||
borderRadius: BorderRadius.circular(10),
|
||
borderSide: const BorderSide(color: AppColors.error, width: 1.5),
|
||
),
|
||
errorStyle: appLabel(size: 11, color: AppColors.error),
|
||
);
|
||
|
||
// ── Selector de nivel ─────────────────────────────────────────────────────
|
||
Widget _selectorNivel() {
|
||
final chips = <Widget>[];
|
||
for (var i = 0; i < _nivelesId.length; i++) {
|
||
final nId = _nivelesId[i];
|
||
final nLabel = _nivelesLabel[i];
|
||
final nColor = _nivelesColor[i];
|
||
final sel = _nivelAcceso == nId;
|
||
chips.add(
|
||
GestureDetector(
|
||
onTap: () => setState(() => _nivelAcceso = nId),
|
||
child: AnimatedContainer(
|
||
duration: const Duration(milliseconds: 180),
|
||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 9),
|
||
decoration: BoxDecoration(
|
||
color: sel ? nColor.withOpacity(0.15) : AppColors.surfaceHigh,
|
||
borderRadius: BorderRadius.circular(8),
|
||
border: Border.all(
|
||
color: sel ? nColor : AppColors.surfaceHighest,
|
||
width: sel ? 1.5 : 1,
|
||
),
|
||
),
|
||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||
if (sel) ...[
|
||
Icon(Icons.check_circle, size: 14, color: nColor),
|
||
const SizedBox(width: 6),
|
||
],
|
||
Text(
|
||
'N$nId · $nLabel',
|
||
style: appLabel(
|
||
size: 12,
|
||
weight: sel ? FontWeight.bold : FontWeight.normal,
|
||
color: sel ? nColor : AppColors.onSurfaceVariant,
|
||
),
|
||
),
|
||
]),
|
||
),
|
||
),
|
||
);
|
||
}
|
||
return Wrap(spacing: 8, runSpacing: 8, children: chips);
|
||
}
|
||
|
||
// ── Selector de áreas ─────────────────────────────────────────────────────
|
||
Widget _selectorAreas() => Wrap(
|
||
spacing: 8,
|
||
runSpacing: 8,
|
||
children: _zonas.map((z) {
|
||
final sel = _zonasSeleccionadas.contains(z.id);
|
||
return GestureDetector(
|
||
onTap: () => setState(() {
|
||
if (sel) {
|
||
_zonasSeleccionadas.remove(z.id);
|
||
} else {
|
||
_zonasSeleccionadas.add(z.id);
|
||
}
|
||
}),
|
||
child: AnimatedContainer(
|
||
duration: const Duration(milliseconds: 160),
|
||
padding:
|
||
const EdgeInsets.symmetric(horizontal: 12, vertical: 7),
|
||
decoration: BoxDecoration(
|
||
color: sel
|
||
? AppColors.primaryContainer
|
||
: AppColors.surfaceHigh,
|
||
borderRadius: BorderRadius.circular(8),
|
||
border: Border.all(
|
||
color: sel
|
||
? AppColors.primary.withOpacity(0.5)
|
||
: AppColors.surfaceHighest,
|
||
),
|
||
),
|
||
child: Row(mainAxisSize: MainAxisSize.min, children: [
|
||
if (sel) ...[
|
||
const Icon(Icons.check, size: 13, color: AppColors.primary),
|
||
const SizedBox(width: 5),
|
||
],
|
||
Text(
|
||
'${z.codigo} · ${z.nombre}',
|
||
style: appLabel(
|
||
size: 12,
|
||
weight: sel ? FontWeight.w600 : FontWeight.normal,
|
||
color: sel
|
||
? AppColors.primary
|
||
: AppColors.onSurfaceVariant,
|
||
),
|
||
),
|
||
]),
|
||
),
|
||
);
|
||
}).toList(),
|
||
);
|
||
|
||
// ── Selector de fechas ────────────────────────────────────────────────────
|
||
Widget _selectorFechas() => Column(
|
||
children: [
|
||
_fechaRow(
|
||
label: 'Inicio de vigencia',
|
||
valor: _formatFecha(_fechaInicio),
|
||
onTap: () => _seleccionarFecha(esFin: false),
|
||
),
|
||
const SizedBox(height: 10),
|
||
_fechaRow(
|
||
label: 'Fin de vigencia',
|
||
valor: _fechaFin != null
|
||
? _formatFecha(_fechaFin!)
|
||
: 'Sin vencimiento',
|
||
valorColor: _fechaFin != null
|
||
? AppColors.onSurface
|
||
: AppColors.onSurfaceVariant,
|
||
onTap: () => _seleccionarFecha(esFin: true),
|
||
trailing: _fechaFin != null
|
||
? IconButton(
|
||
icon: const Icon(Icons.close,
|
||
color: AppColors.outline, size: 18),
|
||
onPressed: () => setState(() => _fechaFin = null),
|
||
padding: EdgeInsets.zero,
|
||
constraints: const BoxConstraints(),
|
||
)
|
||
: null,
|
||
),
|
||
],
|
||
);
|
||
|
||
Widget _fechaRow({
|
||
required String label,
|
||
required String valor,
|
||
Color? valorColor,
|
||
required VoidCallback onTap,
|
||
Widget? trailing,
|
||
}) =>
|
||
GestureDetector(
|
||
onTap: onTap,
|
||
child: Container(
|
||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 14),
|
||
decoration: BoxDecoration(
|
||
color: AppColors.surfaceHigh,
|
||
borderRadius: BorderRadius.circular(10),
|
||
),
|
||
child: Row(children: [
|
||
const Icon(Icons.calendar_today,
|
||
color: AppColors.outline, size: 18),
|
||
const SizedBox(width: 12),
|
||
Expanded(
|
||
child: Column(
|
||
crossAxisAlignment: CrossAxisAlignment.start,
|
||
children: [
|
||
Text(label,
|
||
style: appLabel(
|
||
size: 11, color: AppColors.onSurfaceVariant)),
|
||
const SizedBox(height: 2),
|
||
Text(valor,
|
||
style: appLabel(
|
||
size: 14,
|
||
weight: FontWeight.w600,
|
||
color: valorColor ?? AppColors.onSurface)),
|
||
]),
|
||
),
|
||
trailing ??
|
||
const Icon(Icons.chevron_right,
|
||
color: AppColors.outline, size: 20),
|
||
]),
|
||
),
|
||
);
|
||
}
|