docs: nuevas páginas, plan y documentación sesión 10
- alarmas_page.dart, registrar_usuario_page.dart: páginas nuevas - plan_proyecto.md: actualizado a sesión 10 - solicituda_backend.md, agents.md: documentación de endpoints y agentes Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 4.6
parent
efa4a792f4
commit
d150d7dc9f
@@ -0,0 +1,649 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../theme.dart';
|
||||
import '../db/dao/alarmas_dao.dart';
|
||||
|
||||
class AlarmasPage extends StatefulWidget {
|
||||
const AlarmasPage({Key? key}) : super(key: key);
|
||||
|
||||
@override
|
||||
State<AlarmasPage> createState() => _AlarmasPageState();
|
||||
}
|
||||
|
||||
class _AlarmasPageState extends State<AlarmasPage>
|
||||
with SingleTickerProviderStateMixin {
|
||||
final _dao = AlarmasDao();
|
||||
late final TabController _tab;
|
||||
|
||||
List<Map<String, dynamic>> _activas = [];
|
||||
List<Map<String, dynamic>> _historial = [];
|
||||
bool _cargando = true;
|
||||
String? _filtroTipo; // null = todos
|
||||
|
||||
static const _tipos = ['intrusion', 'humo', 'movimiento', 'acceso'];
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_tab = TabController(length: 2, vsync: this);
|
||||
_cargar();
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_tab.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
Future<void> _cargar() async {
|
||||
setState(() => _cargando = true);
|
||||
try {
|
||||
final activas = await _dao.getActivasConZona();
|
||||
final historial = await _dao.getHistorialConZona();
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_activas = activas;
|
||||
_historial = historial;
|
||||
});
|
||||
} catch (_) {}
|
||||
if (mounted) setState(() => _cargando = false);
|
||||
}
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
List<Map<String, dynamic>> get _activasFiltradas {
|
||||
if (_filtroTipo == null) return _activas;
|
||||
return _activas.where((a) => a['tipo'] == _filtroTipo).toList();
|
||||
}
|
||||
|
||||
Color _sevColor(int sev) {
|
||||
if (sev >= 5) return AppColors.error;
|
||||
if (sev >= 4) return AppColors.tertiary;
|
||||
if (sev >= 3) return AppColors.secondary;
|
||||
if (sev >= 2) return AppColors.onSecondaryContainer;
|
||||
return AppColors.outline;
|
||||
}
|
||||
|
||||
IconData _tipoIcon(String tipo) {
|
||||
switch (tipo) {
|
||||
case 'intrusion': return Icons.warning_amber_rounded;
|
||||
case 'humo': return Icons.local_fire_department;
|
||||
case 'movimiento': return Icons.directions_run;
|
||||
case 'acceso': return Icons.lock_open;
|
||||
default: return Icons.notifications;
|
||||
}
|
||||
}
|
||||
|
||||
String _tipoLabel(String tipo) {
|
||||
switch (tipo) {
|
||||
case 'intrusion': return 'INTRUSIÓN';
|
||||
case 'humo': return 'HUMO';
|
||||
case 'movimiento': return 'MOVIMIENTO';
|
||||
case 'acceso': return 'ACCESO';
|
||||
default: return tipo.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
String _formatTs(String iso) {
|
||||
try {
|
||||
final dt = DateTime.parse(iso).toLocal();
|
||||
final d = dt.day.toString().padLeft(2, '0');
|
||||
final mo = dt.month.toString().padLeft(2, '0');
|
||||
final h = dt.hour.toString().padLeft(2, '0');
|
||||
final m = dt.minute.toString().padLeft(2, '0');
|
||||
return '$d/$mo $h:$m';
|
||||
} catch (_) {
|
||||
return iso;
|
||||
}
|
||||
}
|
||||
|
||||
Color _estadoColor(String estado) {
|
||||
switch (estado) {
|
||||
case 'resuelta': return AppColors.primary;
|
||||
case 'silenciada': return AppColors.outline;
|
||||
default: return AppColors.error;
|
||||
}
|
||||
}
|
||||
|
||||
String _estadoLabel(String estado) {
|
||||
switch (estado) {
|
||||
case 'resuelta': return 'RESUELTA';
|
||||
case 'silenciada': return 'SILENCIADA';
|
||||
default: return estado.toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Acciones ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Future<void> _responder(Map<String, dynamic> a) async {
|
||||
final notasCtrl = TextEditingController();
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Responder alarma',
|
||||
style: appHeadline(size: 16)),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? 'Sin zona'}',
|
||||
style: appLabel(size: 12),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: notasCtrl,
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
maxLines: 3,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Notas de resolución (opcional)',
|
||||
hintStyle: appLabel(size: 12),
|
||||
filled: true,
|
||||
fillColor: AppColors.surfaceLowest,
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
borderSide: BorderSide.none,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.primary,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: Text('Confirmar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||
color: AppColors.surfaceLowest)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true && mounted) {
|
||||
await _dao.resolver(a['id'] as int, 1, notas: notasCtrl.text.trim().isEmpty
|
||||
? null : notasCtrl.text.trim());
|
||||
_cargar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('Alarma resuelta', style: appLabel(size: 13, color: AppColors.surfaceLowest)),
|
||||
backgroundColor: AppColors.primary,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _silenciar(Map<String, dynamic> a) async {
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Silenciar alarma', style: appHeadline(size: 16)),
|
||||
content: Text(
|
||||
'La alarma se marcará como silenciada.\n${_tipoLabel(a['tipo'] as String)} · ${a['zona_nombre'] ?? ''}',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.onSurfaceVariant,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: Text('Silenciar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||
color: AppColors.surfaceLowest)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true && mounted) {
|
||||
await _dao.silenciar(a['id'] as int);
|
||||
_cargar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('Alarma silenciada', style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||
backgroundColor: AppColors.surfaceHighest,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _escalar(Map<String, dynamic> a) async {
|
||||
final sevActual = a['severidad'] as int;
|
||||
if (sevActual >= 5) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('Ya está en nivel máximo (5)',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface)),
|
||||
backgroundColor: AppColors.surfaceHighest,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
));
|
||||
return;
|
||||
}
|
||||
final ok = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (_) => AlertDialog(
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
title: Text('Escalar alarma', style: appHeadline(size: 16)),
|
||||
content: Text(
|
||||
'La severidad subirá de NIVEL $sevActual → NIVEL ${sevActual + 1}.\n'
|
||||
'Se notificará a la central cuando se sincronice.',
|
||||
style: appLabel(size: 13, color: AppColors.onSurface),
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(context, false),
|
||||
child: Text('Cancelar', style: appLabel(size: 13, color: AppColors.outline)),
|
||||
),
|
||||
ElevatedButton(
|
||||
onPressed: () => Navigator.pop(context, true),
|
||||
style: ElevatedButton.styleFrom(
|
||||
primary: AppColors.tertiary,
|
||||
onPrimary: AppColors.surfaceLowest,
|
||||
elevation: 0,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8)),
|
||||
),
|
||||
child: Text('Escalar', style: appLabel(size: 13, weight: FontWeight.bold,
|
||||
color: AppColors.surfaceLowest)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
if (ok == true && mounted) {
|
||||
await _dao.escalar(a['id'] as int);
|
||||
_cargar();
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
|
||||
content: Text('Alarma escalada a nivel ${sevActual + 1}',
|
||||
style: appLabel(size: 13, color: AppColors.surfaceLowest)),
|
||||
backgroundColor: AppColors.tertiary,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
// ── Build ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.surfaceLowest,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.surfaceLow,
|
||||
elevation: 0,
|
||||
leading: IconButton(
|
||||
icon: const Icon(Icons.arrow_back_ios_new, size: 18,
|
||||
color: AppColors.onSurface),
|
||||
onPressed: () => Navigator.pop(context),
|
||||
),
|
||||
title: Text('ALARMAS', style: appHeadline(size: 14, spacing: 2.0)),
|
||||
bottom: TabBar(
|
||||
controller: _tab,
|
||||
labelStyle: appLabel(size: 12, weight: FontWeight.bold, spacing: 1.5),
|
||||
unselectedLabelStyle: appLabel(size: 12, spacing: 1.5),
|
||||
labelColor: AppColors.primary,
|
||||
unselectedLabelColor: AppColors.outline,
|
||||
indicatorColor: AppColors.primary,
|
||||
indicatorWeight: 2,
|
||||
tabs: const [
|
||||
Tab(text: 'ACTIVAS'),
|
||||
Tab(text: 'HISTORIAL'),
|
||||
],
|
||||
),
|
||||
),
|
||||
body: TabBarView(
|
||||
controller: _tab,
|
||||
children: [
|
||||
_tabActivas(),
|
||||
_tabHistorial(),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Tab Activas ───────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _tabActivas() {
|
||||
final lista = _activasFiltradas;
|
||||
return RefreshIndicator(
|
||||
onRefresh: _cargar,
|
||||
color: AppColors.primary,
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
child: CustomScrollView(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
primary: false,
|
||||
slivers: [
|
||||
SliverToBoxAdapter(child: _filtroChips()),
|
||||
if (_cargando)
|
||||
const SliverFillRemaining(
|
||||
child: Center(child: CircularProgressIndicator(
|
||||
strokeWidth: 2, color: AppColors.primary)),
|
||||
)
|
||||
else if (lista.isEmpty)
|
||||
SliverFillRemaining(child: _emptyState(
|
||||
icon: Icons.shield_outlined,
|
||||
titulo: 'Sin alarmas activas',
|
||||
sub: 'Todos los sectores en estado normal',
|
||||
color: AppColors.primary,
|
||||
))
|
||||
else ...[
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(20, 4, 20, 12),
|
||||
child: Text(
|
||||
'${lista.length} alarma${lista.length == 1 ? '' : 's'} activa${lista.length == 1 ? '' : 's'}',
|
||||
style: appLabel(size: 12, color: AppColors.outline),
|
||||
),
|
||||
),
|
||||
),
|
||||
SliverList(
|
||||
delegate: SliverChildBuilderDelegate(
|
||||
(_, i) => Padding(
|
||||
padding: EdgeInsets.fromLTRB(16, 0, 16,
|
||||
i == lista.length - 1 ? 24 : 12),
|
||||
child: _alarmaCard(lista[i]),
|
||||
),
|
||||
childCount: lista.length,
|
||||
),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _filtroChips() {
|
||||
return SingleChildScrollView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 8),
|
||||
child: Row(
|
||||
children: [
|
||||
_chip('Todos', null),
|
||||
..._tipos.map((t) => _chip(_tipoLabel(t), t)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _chip(String label, String? tipo) {
|
||||
final selected = _filtroTipo == tipo;
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: GestureDetector(
|
||||
onTap: () => setState(() => _filtroTipo = tipo),
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 7),
|
||||
decoration: BoxDecoration(
|
||||
color: selected ? AppColors.primaryContainer : AppColors.surfaceHigh,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(
|
||||
color: selected ? AppColors.primary : AppColors.outlineVariant,
|
||||
width: 1,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: appLabel(
|
||||
size: 11,
|
||||
weight: selected ? FontWeight.bold : FontWeight.normal,
|
||||
color: selected ? AppColors.primary : AppColors.onSurfaceVariant,
|
||||
spacing: 1.0,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _alarmaCard(Map<String, dynamic> a) {
|
||||
final sev = a['severidad'] as int;
|
||||
final tipo = a['tipo'] as String;
|
||||
final zona = a['zona_nombre'] as String? ?? 'Zona desconocida';
|
||||
final codigo = a['zona_codigo'] as String? ?? '';
|
||||
final ts = _formatTs(a['timestamp'] as String);
|
||||
final color = _sevColor(sev);
|
||||
|
||||
return ClipRRect(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
child: IntrinsicHeight(
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Container(width: 5, color: color),
|
||||
Expanded(
|
||||
child: Container(
|
||||
color: AppColors.surfaceHigh,
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Cabecera
|
||||
Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Container(
|
||||
padding: const EdgeInsets.all(8),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Icon(_tipoIcon(tipo), color: color, size: 18),
|
||||
),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
_tipoLabel(tipo),
|
||||
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||
color: color, spacing: 1.5),
|
||||
),
|
||||
const SizedBox(height: 2),
|
||||
Text(zona,
|
||||
style: appHeadline(size: 15)),
|
||||
if (codigo.isNotEmpty)
|
||||
Text(codigo,
|
||||
style: appLabel(size: 11)),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Badge severidad
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 10, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Text(
|
||||
'N$sev',
|
||||
style: appLabel(size: 12, weight: FontWeight.bold,
|
||||
color: color, spacing: 0.5),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
// Timestamp
|
||||
Row(children: [
|
||||
const Icon(Icons.schedule, size: 13,
|
||||
color: AppColors.outline),
|
||||
const SizedBox(width: 5),
|
||||
Text(ts, style: appLabel(size: 11)),
|
||||
]),
|
||||
const SizedBox(height: 14),
|
||||
// Botones de acción
|
||||
Row(children: [
|
||||
_accionBtn('RESPONDER', AppColors.primary,
|
||||
() => _responder(a)),
|
||||
const SizedBox(width: 8),
|
||||
_accionBtn('SILENCIAR', AppColors.onSurfaceVariant,
|
||||
() => _silenciar(a)),
|
||||
const SizedBox(width: 8),
|
||||
_accionBtn('ESCALAR', sev >= 5
|
||||
? AppColors.outlineVariant : AppColors.tertiary,
|
||||
sev >= 5 ? null : () => _escalar(a)),
|
||||
]),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _accionBtn(String label, Color color, VoidCallback? onTap) =>
|
||||
Expanded(
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: onTap != null ? color.withOpacity(0.12) : AppColors.surfaceLowest,
|
||||
borderRadius: BorderRadius.circular(7),
|
||||
border: Border.all(
|
||||
color: onTap != null ? color.withOpacity(0.3) : AppColors.outlineVariant,
|
||||
),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
textAlign: TextAlign.center,
|
||||
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||
color: onTap != null ? color : AppColors.outlineVariant,
|
||||
spacing: 1.0),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
// ── Tab Historial ─────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _tabHistorial() {
|
||||
return RefreshIndicator(
|
||||
onRefresh: _cargar,
|
||||
color: AppColors.primary,
|
||||
backgroundColor: AppColors.surfaceHigh,
|
||||
child: _cargando
|
||||
? const Center(child: CircularProgressIndicator(
|
||||
strokeWidth: 2, color: AppColors.primary))
|
||||
: _historial.isEmpty
|
||||
? _emptyState(
|
||||
icon: Icons.history,
|
||||
titulo: 'Sin historial',
|
||||
sub: 'Las alarmas resueltas y silenciadas aparecerán aquí',
|
||||
color: AppColors.outline,
|
||||
)
|
||||
: ListView.separated(
|
||||
physics: const AlwaysScrollableScrollPhysics(),
|
||||
primary: false,
|
||||
padding: const EdgeInsets.fromLTRB(16, 16, 16, 24),
|
||||
itemCount: _historial.length,
|
||||
separatorBuilder: (_, __) => const SizedBox(height: 8),
|
||||
itemBuilder: (_, i) => _historialItem(_historial[i]),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _historialItem(Map<String, dynamic> a) {
|
||||
final sev = a['severidad'] as int;
|
||||
final tipo = a['tipo'] as String;
|
||||
final zona = a['zona_nombre'] as String? ?? 'Zona desconocida';
|
||||
final ts = _formatTs(a['timestamp'] as String);
|
||||
final estado = a['estado'] as String;
|
||||
final notas = a['notas'] as String?;
|
||||
final sevColor = _sevColor(sev);
|
||||
final estadoC = _estadoColor(estado);
|
||||
|
||||
return Container(
|
||||
padding: const EdgeInsets.all(14),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.surfaceLow,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(_tipoIcon(tipo), color: sevColor, size: 18),
|
||||
const SizedBox(width: 12),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(children: [
|
||||
Text(_tipoLabel(tipo),
|
||||
style: appLabel(size: 10, weight: FontWeight.bold,
|
||||
color: sevColor, spacing: 1.0)),
|
||||
const SizedBox(width: 6),
|
||||
Text('·', style: appLabel(size: 10, color: AppColors.outlineVariant)),
|
||||
const SizedBox(width: 6),
|
||||
Text('N$sev', style: appLabel(size: 10, color: sevColor)),
|
||||
]),
|
||||
const SizedBox(height: 2),
|
||||
Text(zona, style: appHeadline(size: 13)),
|
||||
if (notas != null && notas.isNotEmpty)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(top: 2),
|
||||
child: Text(notas,
|
||||
style: appLabel(size: 11),
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(ts, style: appLabel(size: 11, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
||||
decoration: BoxDecoration(
|
||||
color: estadoC.withOpacity(0.12),
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
),
|
||||
child: Text(_estadoLabel(estado),
|
||||
style: appLabel(size: 9, weight: FontWeight.bold,
|
||||
color: estadoC, spacing: 0.8)),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ── Empty state ───────────────────────────────────────────────────────────────
|
||||
|
||||
Widget _emptyState({
|
||||
required IconData icon,
|
||||
required String titulo,
|
||||
required String sub,
|
||||
required Color color,
|
||||
}) =>
|
||||
Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(40),
|
||||
child: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, color: color, size: 36),
|
||||
const SizedBox(height: 12),
|
||||
Text(titulo, style: appHeadline(size: 15, color: color)),
|
||||
const SizedBox(height: 6),
|
||||
Text(sub,
|
||||
textAlign: TextAlign.center,
|
||||
style: appLabel(size: 12, color: AppColors.outline)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,462 @@
|
||||
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';
|
||||
|
||||
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();
|
||||
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();
|
||||
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(',');
|
||||
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(),
|
||||
);
|
||||
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: 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;
|
||||
},
|
||||
);
|
||||
|
||||
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),
|
||||
]),
|
||||
),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user