558 lines
21 KiB
Dart
558 lines
21 KiB
Dart
import 'package:flutter/material.dart';
|
|
import '../theme.dart';
|
|
import '../db/dao/incidentes_dao.dart';
|
|
import '../db/dao/cache_clientes_dao.dart';
|
|
import '../db/dao/operadores_dao.dart';
|
|
|
|
// Comentario explicativo: Pantalla de Reportes y Auditoría conectada a IncidentesDao, CacheClientesDao y OperadoresDao.
|
|
// Proporciona indicadores KPI del centro de control, filtros dinámicos por cliente, operador, período y estado,
|
|
// y una bitácora detallada con capacidad de exportación para la revisión de tienda y auditoría técnica.
|
|
class ReportesPage extends StatefulWidget {
|
|
const ReportesPage({Key? key}) : super(key: key);
|
|
|
|
@override
|
|
State<ReportesPage> createState() => _ReportesPageState();
|
|
}
|
|
|
|
class _ReportesPageState extends State<ReportesPage> {
|
|
final _incidentesDao = IncidentesDao();
|
|
final _clientesDao = CacheClientesDao();
|
|
final _operadoresDao = OperadoresDao();
|
|
|
|
bool _cargando = true;
|
|
List<Map<String, dynamic>> _incidentes = [];
|
|
List<Map<String, dynamic>> _clientes = [];
|
|
List<Map<String, dynamic>> _operadores = [];
|
|
Map<String, int> _stats = {'total': 0, 'resueltos': 0, 'pendientes': 0, 'falsas': 0};
|
|
|
|
// Filtros seleccionados
|
|
String _filtroCliente = 'todos';
|
|
String _filtroOperador = 'todos';
|
|
String _filtroPeriodo = 'todos'; // todos | hoy | 7d | 30d
|
|
String _filtroEstado = 'todos'; // todos | resuelto | pendiente
|
|
|
|
@override
|
|
void initState() {
|
|
super.initState();
|
|
_cargarTodo();
|
|
}
|
|
|
|
// Comentario explicativo: Carga los catálogos para los dropdowns y ejecuta la consulta filtrada de incidentes y KPIs
|
|
Future<void> _cargarTodo() async {
|
|
setState(() => _cargando = true);
|
|
|
|
final clientes = await _clientesDao.getTodos();
|
|
final operadores = await _operadoresDao.getTodos();
|
|
final stats = await _incidentesDao.getEstadisticas();
|
|
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_clientes = clientes;
|
|
_operadores = operadores;
|
|
_stats = stats;
|
|
});
|
|
|
|
await _aplicarFiltros();
|
|
}
|
|
|
|
// Comentario explicativo: Aplica los filtros de cliente, operador, período y estado en la base SQLite
|
|
Future<void> _aplicarFiltros() async {
|
|
DateTime? desde;
|
|
final now = DateTime.now();
|
|
if (_filtroPeriodo == 'hoy') {
|
|
desde = DateTime(now.year, now.month, now.day);
|
|
} else if (_filtroPeriodo == '7d') {
|
|
desde = now.subtract(const Duration(days: 7));
|
|
} else if (_filtroPeriodo == '30d') {
|
|
desde = now.subtract(const Duration(days: 30));
|
|
}
|
|
|
|
int? resuelto;
|
|
if (_filtroEstado == 'resuelto') resuelto = 1;
|
|
if (_filtroEstado == 'pendiente') resuelto = 0;
|
|
|
|
final lista = await _incidentesDao.getFiltrados(
|
|
clienteNombre: _filtroCliente == 'todos' ? null : _filtroCliente,
|
|
operador: _filtroOperador == 'todos' ? null : _filtroOperador,
|
|
resuelto: resuelto,
|
|
desde: desde,
|
|
);
|
|
|
|
if (!mounted) return;
|
|
setState(() {
|
|
_incidentes = lista;
|
|
_cargando = false;
|
|
});
|
|
}
|
|
|
|
// Comentario explicativo: Muestra diálogo de exportación simulada de reporte para auditoría interna
|
|
void _exportarReporte() {
|
|
final cantidad = _incidentes.length;
|
|
ScaffoldMessenger.of(context).showSnackBar(
|
|
SnackBar(
|
|
backgroundColor: AppColors.surfaceHigh,
|
|
content: Row(
|
|
children: [
|
|
const Icon(Icons.check_circle, color: AppColors.clienteOk, size: 20),
|
|
const SizedBox(width: 10),
|
|
Expanded(
|
|
child: Text(
|
|
'Reporte generado: $cantidad registros consolidados para auditoría interna.',
|
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
duration: const Duration(seconds: 4),
|
|
),
|
|
);
|
|
}
|
|
|
|
@override
|
|
Widget build(BuildContext context) {
|
|
final total = _stats['total'] ?? 0;
|
|
final resueltos = _stats['resueltos'] ?? 0;
|
|
final pendientes = _stats['pendientes'] ?? 0;
|
|
final falsas = _stats['falsas'] ?? 0;
|
|
final tasaEfectividad = total > 0 ? ((resueltos / total) * 100).toStringAsFixed(1) : '100';
|
|
|
|
return SingleChildScrollView(
|
|
primary: false,
|
|
padding: const EdgeInsets.all(24),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
// Cabecera principal
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text('Reportes y Auditoría',
|
|
style: appHeadline(size: 24, weight: FontWeight.w800, color: AppColors.onSurface)),
|
|
const SizedBox(height: 4),
|
|
Text('Métricas operativas de la central y bitácora de intervenciones',
|
|
style: appLabel(size: 13, color: AppColors.outline)),
|
|
],
|
|
),
|
|
Row(
|
|
children: [
|
|
OutlinedButton.icon(
|
|
style: OutlinedButton.styleFrom(
|
|
side: const BorderSide(color: AppColors.outlineVariant),
|
|
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
|
|
),
|
|
icon: const Icon(Icons.download_outlined, size: 18, color: AppColors.primary),
|
|
label: Text('Exportar', style: appLabel(size: 13, color: AppColors.primary, weight: FontWeight.bold)),
|
|
onPressed: _exportarReporte,
|
|
),
|
|
const SizedBox(width: 8),
|
|
IconButton(
|
|
icon: const Icon(Icons.refresh, color: AppColors.outline),
|
|
tooltip: 'Recargar estadísticas',
|
|
onPressed: _cargarTodo,
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 24),
|
|
|
|
// Tarjetas KPI de resumen
|
|
LayoutBuilder(
|
|
builder: (context, constraints) {
|
|
final isDesktop = constraints.maxWidth > 700;
|
|
return Wrap(
|
|
spacing: 12,
|
|
runSpacing: 12,
|
|
children: [
|
|
_buildStatCard(
|
|
title: 'Total Incidentes',
|
|
valor: '$total',
|
|
icono: Icons.analytics_outlined,
|
|
color: AppColors.primary,
|
|
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
|
),
|
|
_buildStatCard(
|
|
title: 'Resueltos ($tasaEfectividad%)',
|
|
valor: '$resueltos',
|
|
icono: Icons.task_alt,
|
|
color: AppColors.clienteOk,
|
|
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
|
),
|
|
_buildStatCard(
|
|
title: 'En Atención / Pendientes',
|
|
valor: '$pendientes',
|
|
icono: Icons.warning_amber_rounded,
|
|
color: pendientes > 0 ? AppColors.alarmaActiva : AppColors.outline,
|
|
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
|
),
|
|
_buildStatCard(
|
|
title: 'Falsas Alarmas',
|
|
valor: '$falsas',
|
|
icono: Icons.verified_user_outlined,
|
|
color: AppColors.secondary,
|
|
width: isDesktop ? (constraints.maxWidth - 36) / 4 : (constraints.maxWidth - 12) / 2,
|
|
),
|
|
],
|
|
);
|
|
},
|
|
),
|
|
const SizedBox(height: 24),
|
|
|
|
// Barra de Filtros
|
|
Container(
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceLow,
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: AppColors.outlineVariant),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
const Icon(Icons.filter_list, size: 18, color: AppColors.primary),
|
|
const SizedBox(width: 8),
|
|
Text('Filtros de Auditoría', style: appHeadline(size: 14, color: AppColors.onSurface)),
|
|
const Spacer(),
|
|
if (_filtroCliente != 'todos' || _filtroOperador != 'todos' || _filtroPeriodo != 'todos' || _filtroEstado != 'todos')
|
|
TextButton(
|
|
onPressed: () {
|
|
setState(() {
|
|
_filtroCliente = 'todos';
|
|
_filtroOperador = 'todos';
|
|
_filtroPeriodo = 'todos';
|
|
_filtroEstado = 'todos';
|
|
});
|
|
_aplicarFiltros();
|
|
},
|
|
child: Text('Limpiar filtros', style: appLabel(size: 12, color: AppColors.primary)),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 14),
|
|
Wrap(
|
|
spacing: 16,
|
|
runSpacing: 12,
|
|
children: [
|
|
// Filtro Cliente
|
|
_buildFilterDropdown(
|
|
label: 'Cliente:',
|
|
value: _filtroCliente,
|
|
items: [
|
|
const DropdownMenuItem(value: 'todos', child: Text('Todos los clientes')),
|
|
..._clientes.map((c) {
|
|
final nombre = c['nombre'] as String? ?? 'Cliente';
|
|
return DropdownMenuItem(value: nombre, child: Text(nombre));
|
|
}).toList(),
|
|
],
|
|
onChanged: (val) {
|
|
if (val == null) return;
|
|
setState(() => _filtroCliente = val);
|
|
_aplicarFiltros();
|
|
},
|
|
),
|
|
|
|
// Filtro Operador
|
|
_buildFilterDropdown(
|
|
label: 'Operador:',
|
|
value: _filtroOperador,
|
|
items: [
|
|
const DropdownMenuItem(value: 'todos', child: Text('Todos los operadores')),
|
|
..._operadores.map((o) {
|
|
final nombre = o['nombre'] as String? ?? 'Operador';
|
|
return DropdownMenuItem(value: nombre, child: Text(nombre));
|
|
}).toList(),
|
|
],
|
|
onChanged: (val) {
|
|
if (val == null) return;
|
|
setState(() => _filtroOperador = val);
|
|
_aplicarFiltros();
|
|
},
|
|
),
|
|
|
|
// Filtro Período
|
|
_buildFilterDropdown(
|
|
label: 'Período:',
|
|
value: _filtroPeriodo,
|
|
items: const [
|
|
DropdownMenuItem(value: 'todos', child: Text('Todo el historial')),
|
|
DropdownMenuItem(value: 'hoy', child: Text('Hoy')),
|
|
DropdownMenuItem(value: '7d', child: Text('Últimos 7 días')),
|
|
DropdownMenuItem(value: '30d', child: Text('Últimos 30 días')),
|
|
],
|
|
onChanged: (val) {
|
|
if (val == null) return;
|
|
setState(() => _filtroPeriodo = val);
|
|
_aplicarFiltros();
|
|
},
|
|
),
|
|
|
|
// Filtro Estado
|
|
_buildFilterDropdown(
|
|
label: 'Estado:',
|
|
value: _filtroEstado,
|
|
items: const [
|
|
DropdownMenuItem(value: 'todos', child: Text('Todos los estados')),
|
|
DropdownMenuItem(value: 'resuelto', child: Text('Solo Resueltos')),
|
|
DropdownMenuItem(value: 'pendiente', child: Text('Solo Pendientes')),
|
|
],
|
|
onChanged: (val) {
|
|
if (val == null) return;
|
|
setState(() => _filtroEstado = val);
|
|
_aplicarFiltros();
|
|
},
|
|
),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
),
|
|
const SizedBox(height: 24),
|
|
|
|
// Listado de Resultados
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Text(
|
|
'Resultados de la búsqueda (${_incidentes.length})',
|
|
style: appHeadline(size: 16, weight: FontWeight.bold, color: AppColors.onSurface),
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 12),
|
|
|
|
if (_cargando)
|
|
const Center(child: Padding(padding: EdgeInsets.all(32), child: CircularProgressIndicator()))
|
|
else if (_incidentes.isEmpty)
|
|
Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(40),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceLow,
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: AppColors.outlineVariant),
|
|
),
|
|
child: Column(
|
|
children: [
|
|
const Icon(Icons.search_off, size: 48, color: AppColors.outline),
|
|
const SizedBox(height: 12),
|
|
Text('No se encontraron incidentes con los criterios seleccionados.',
|
|
style: appLabel(size: 14, color: AppColors.outline)),
|
|
],
|
|
),
|
|
)
|
|
else
|
|
ListView.separated(
|
|
shrinkWrap: true,
|
|
physics: const NeverScrollableScrollPhysics(),
|
|
itemCount: _incidentes.length,
|
|
separatorBuilder: (_, __) => const SizedBox(height: 10),
|
|
itemBuilder: (_, index) {
|
|
final inc = _incidentes[index];
|
|
return _buildIncidentCard(inc);
|
|
},
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// Comentario explicativo: Widget auxiliar para renderizar cada tarjeta KPI estadística
|
|
Widget _buildStatCard({
|
|
required String title,
|
|
required String valor,
|
|
required IconData icono,
|
|
required Color color,
|
|
required double width,
|
|
}) {
|
|
return Container(
|
|
width: width,
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceLow,
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(color: AppColors.outlineVariant),
|
|
),
|
|
child: Row(
|
|
children: [
|
|
Container(
|
|
padding: const EdgeInsets.all(10),
|
|
decoration: BoxDecoration(
|
|
color: color.withAlpha(30),
|
|
borderRadius: BorderRadius.circular(10),
|
|
),
|
|
child: Icon(icono, color: color, size: 22),
|
|
),
|
|
const SizedBox(width: 14),
|
|
Expanded(
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(title, style: appLabel(size: 11, color: AppColors.outline)),
|
|
const SizedBox(height: 4),
|
|
Text(valor, style: appHeadline(size: 20, weight: FontWeight.w800, color: AppColors.onSurface)),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
|
|
// Comentario explicativo: Widget auxiliar para los selectores dropdown de filtrado con estilo dark
|
|
Widget _buildFilterDropdown({
|
|
required String label,
|
|
required String value,
|
|
required List<DropdownMenuItem<String>> items,
|
|
required ValueChanged<String?> onChanged,
|
|
}) {
|
|
return Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Text(label, style: appLabel(size: 11, color: AppColors.outline)),
|
|
const SizedBox(height: 4),
|
|
Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 12),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceHigh,
|
|
borderRadius: BorderRadius.circular(8),
|
|
border: Border.all(color: AppColors.outlineVariant),
|
|
),
|
|
child: DropdownButtonHideUnderline(
|
|
child: DropdownButton<String>(
|
|
value: value,
|
|
dropdownColor: AppColors.surfaceHigh,
|
|
style: appLabel(size: 13, color: AppColors.onSurface),
|
|
items: items,
|
|
onChanged: onChanged,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
);
|
|
}
|
|
|
|
// Comentario explicativo: Renderiza la tarjeta de detalle de cada incidente en la lista de reportes
|
|
Widget _buildIncidentCard(Map<String, dynamic> inc) {
|
|
final resuelto = (inc['resuelto'] as int? ?? 0) == 1;
|
|
final tipo = inc['tipo'] as String? ?? 'Incidente';
|
|
final cliente = inc['cliente_nombre'] as String? ?? 'Cliente';
|
|
final operador = inc['operador'] as String? ?? 'Operador';
|
|
final notas = inc['notas'] as String? ?? 'Sin notas registradas';
|
|
final timestamp = inc['timestamp'] as String? ?? '';
|
|
|
|
String fechaHora = timestamp;
|
|
try {
|
|
final dt = DateTime.parse(timestamp);
|
|
fechaHora = '${dt.day.toString().padLeft(2, '0')}/${dt.month.toString().padLeft(2, '0')} ${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
|
|
} catch (_) {}
|
|
|
|
final bool esFalsaAlarma = tipo.toLowerCase().contains('falsa');
|
|
|
|
return Container(
|
|
padding: const EdgeInsets.all(16),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surfaceLow,
|
|
borderRadius: BorderRadius.circular(12),
|
|
border: Border.all(
|
|
color: resuelto ? AppColors.clienteOk.withAlpha(60) : AppColors.alarmaActiva.withAlpha(80),
|
|
),
|
|
),
|
|
child: Column(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
Row(
|
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
|
children: [
|
|
Row(
|
|
children: [
|
|
Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
decoration: BoxDecoration(
|
|
color: esFalsaAlarma
|
|
? AppColors.secondaryContainer
|
|
: (resuelto ? const Color(0xFF1B382B) : const Color(0xFF381B1B)),
|
|
borderRadius: BorderRadius.circular(6),
|
|
),
|
|
child: Text(
|
|
tipo.toUpperCase().replaceAll('_', ' '),
|
|
style: appHeadline(
|
|
size: 10,
|
|
weight: FontWeight.bold,
|
|
color: esFalsaAlarma
|
|
? AppColors.onSecondaryContainer
|
|
: (resuelto ? AppColors.clienteOk : AppColors.alarmaActiva),
|
|
),
|
|
),
|
|
),
|
|
const SizedBox(width: 8),
|
|
Container(
|
|
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
|
|
decoration: BoxDecoration(
|
|
color: resuelto ? AppColors.clienteOk.withAlpha(30) : AppColors.alarmaActiva.withAlpha(30),
|
|
borderRadius: BorderRadius.circular(6),
|
|
),
|
|
child: Text(
|
|
resuelto ? 'RESUELTO' : 'EN ATENCIÓN',
|
|
style: appLabel(
|
|
size: 10,
|
|
weight: FontWeight.bold,
|
|
color: resuelto ? AppColors.clienteOk : AppColors.alarmaActiva,
|
|
),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
Row(
|
|
children: [
|
|
const Icon(Icons.access_time, size: 13, color: AppColors.outline),
|
|
const SizedBox(width: 4),
|
|
Text(fechaHora, style: appLabel(size: 11, color: AppColors.outline)),
|
|
],
|
|
),
|
|
],
|
|
),
|
|
const SizedBox(height: 10),
|
|
Row(
|
|
children: [
|
|
const Icon(Icons.business_outlined, size: 16, color: AppColors.primary),
|
|
const SizedBox(width: 6),
|
|
Text(cliente, style: appHeadline(size: 14, weight: FontWeight.w700, color: AppColors.onSurface)),
|
|
const Spacer(),
|
|
const Icon(Icons.person_pin_outlined, size: 15, color: AppColors.secondary),
|
|
const SizedBox(width: 4),
|
|
Text(operador, style: appLabel(size: 12, color: AppColors.secondary)),
|
|
],
|
|
),
|
|
const SizedBox(height: 8),
|
|
Container(
|
|
width: double.infinity,
|
|
padding: const EdgeInsets.all(10),
|
|
decoration: BoxDecoration(
|
|
color: AppColors.surface,
|
|
borderRadius: BorderRadius.circular(8),
|
|
),
|
|
child: Row(
|
|
crossAxisAlignment: CrossAxisAlignment.start,
|
|
children: [
|
|
const Icon(Icons.notes, size: 14, color: AppColors.outline),
|
|
const SizedBox(width: 6),
|
|
Expanded(
|
|
child: Text(
|
|
notas,
|
|
style: appLabel(size: 12, color: AppColors.onSurfaceVariant),
|
|
),
|
|
),
|
|
],
|
|
),
|
|
),
|
|
],
|
|
),
|
|
);
|
|
}
|
|
}
|