Funcionalidades implementadas:
This commit is contained in:
@@ -19,6 +19,8 @@ import 'screens/login_screen.dart';
|
||||
import 'screens/home_screen.dart';
|
||||
import 'screens/route_list_screen.dart';
|
||||
import 'firebase_options.dart'; // Opcional si usas FlutterFire CLI para generar opciones
|
||||
import 'screens/info_screen.dart';
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// HANDLER DE MENSAJES EN BACKGROUND
|
||||
//
|
||||
@@ -97,6 +99,7 @@ class ResiduosApp extends StatelessWidget {
|
||||
'/': (context) => const LoginScreen(),
|
||||
'/home': (context) => const HomeScreen(),
|
||||
'/routes': (context) => const RouteListScreen(),
|
||||
'/info': (context) => const InfoScreen(),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
689
aplicacion_hack/lib/screens/info_screen.dart
Normal file
689
aplicacion_hack/lib/screens/info_screen.dart
Normal file
@@ -0,0 +1,689 @@
|
||||
// ================================================================
|
||||
// lib/screens/info_screen.dart
|
||||
// Pantalla de Información Relevante sobre Manejo de Residuos
|
||||
// ================================================================
|
||||
//
|
||||
// PROPÓSITO:
|
||||
// Educar al usuario sobre separación, reciclaje y manejo
|
||||
// correcto de residuos. Contenido cargado desde el backend
|
||||
// con fallback local si no hay conexión.
|
||||
//
|
||||
// FLUJO:
|
||||
// 1. Lista de tarjetas por categoría (vista principal)
|
||||
// 2. Tap en tarjeta → detalle del artículo
|
||||
// 3. Cada artículo tiene secciones + consejo rápido destacado
|
||||
//
|
||||
// NAVEGACIÓN:
|
||||
// Agregar en main.dart:
|
||||
// '/info': (context) => const InfoScreen(),
|
||||
// Y en home_screen.dart el botón:
|
||||
// Navigator.pushNamed(context, '/info')
|
||||
// ================================================================
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MODELOS
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
class Subseccion {
|
||||
final String subtitulo;
|
||||
final String texto;
|
||||
|
||||
Subseccion({required this.subtitulo, required this.texto});
|
||||
|
||||
factory Subseccion.fromJson(Map<String, dynamic> json) =>
|
||||
Subseccion(subtitulo: json['subtitulo'], texto: json['texto']);
|
||||
}
|
||||
|
||||
class Articulo {
|
||||
final String id;
|
||||
final String categoria;
|
||||
final String emoji;
|
||||
final String titulo;
|
||||
final String resumen;
|
||||
final List<Subseccion> contenido;
|
||||
final String consejoRapido;
|
||||
|
||||
Articulo({
|
||||
required this.id,
|
||||
required this.categoria,
|
||||
required this.emoji,
|
||||
required this.titulo,
|
||||
required this.resumen,
|
||||
required this.contenido,
|
||||
required this.consejoRapido,
|
||||
});
|
||||
|
||||
factory Articulo.fromJson(Map<String, dynamic> json) => Articulo(
|
||||
id: json['id'],
|
||||
categoria: json['categoria'],
|
||||
emoji: json['emoji'],
|
||||
titulo: json['titulo'],
|
||||
resumen: json['resumen'],
|
||||
contenido: (json['contenido'] as List)
|
||||
.map((s) => Subseccion.fromJson(s))
|
||||
.toList(),
|
||||
consejoRapido: json['consejo_rapido'],
|
||||
);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// DATOS LOCALES DE FALLBACK
|
||||
// Se usan si el backend no está disponible.
|
||||
// ----------------------------------------------------------------
|
||||
const _articulosFallback = [
|
||||
{
|
||||
"id": "separacion-basica",
|
||||
"categoria": "Separación",
|
||||
"emoji": "♻️",
|
||||
"titulo": "Cómo separar correctamente tu basura",
|
||||
"resumen": "La separación correcta es el primer paso para reciclar y reducir el impacto ambiental.",
|
||||
"contenido": [
|
||||
{"subtitulo": "Residuos Orgánicos 🟤", "texto": "Restos de comida, cáscaras, posos de café. Bolsa oscura. Se convierten en composta."},
|
||||
{"subtitulo": "Inorgánicos Reciclables 🟡", "texto": "PET, cartón limpio, vidrio, latas. Bolsa transparente. Deben estar limpios y secos."},
|
||||
{"subtitulo": "No Reciclables 🔴", "texto": "Papel higiénico usado, pañales, colillas. Bolsa negra."},
|
||||
{"subtitulo": "Residuos Especiales ⚠️", "texto": "Pilas, medicamentos, electrónicos. NUNCA con basura regular. Lleva a puntos de acopio."},
|
||||
],
|
||||
"consejo_rapido": "Si vino de la naturaleza y se pudre → orgánico. Si es artificial y limpio → reciclable.",
|
||||
},
|
||||
{
|
||||
"id": "cuando-sacar",
|
||||
"categoria": "Horarios",
|
||||
"emoji": "⏰",
|
||||
"titulo": "¿Cuándo sacar tu basura?",
|
||||
"resumen": "Sacar la basura en el momento correcto evita plagas, malos olores y que el camión se la pierda.",
|
||||
"contenido": [
|
||||
{"subtitulo": "El momento ideal", "texto": "Saca cuando recibas la alerta de 'Camión Cercano' en la app. El camión está a menos de 15 minutos."},
|
||||
{"subtitulo": "¿Por qué no de noche?", "texto": "Atrae fauna que rompe bolsas y dispersa residuos. El plástico se deteriora con la humedad."},
|
||||
{"subtitulo": "¿Si me lo pierdo?", "texto": "Guarda la basura hasta el siguiente día. Nunca dejes bolsas en la vía pública fuera del horario."},
|
||||
],
|
||||
"consejo_rapido": "Espera la alerta de la app antes de salir con tus bolsas.",
|
||||
},
|
||||
{
|
||||
"id": "plasticos-guia",
|
||||
"categoria": "Reciclaje",
|
||||
"emoji": "🧴",
|
||||
"titulo": "Guía de plásticos: cuáles sí y cuáles no",
|
||||
"resumen": "No todos los plásticos son iguales. Aprende a leer el número en el triángulo de reciclaje.",
|
||||
"contenido": [
|
||||
{"subtitulo": "✅ #1 PET", "texto": "Botellas de agua y refresco. El más reciclado. Aplástalo y quita la tapa."},
|
||||
{"subtitulo": "✅ #2 HDPE", "texto": "Garrafones, botellas de leche, shampú. Enjuágalo antes."},
|
||||
{"subtitulo": "✅ #5 PP", "texto": "Tapas, envases de yogur. Sí se recicla pero menos centros lo aceptan."},
|
||||
{"subtitulo": "❌ #3, #6, #7", "texto": "PVC, unicel, policarbonato. Difíciles de reciclar. Van a basura general."},
|
||||
{"subtitulo": "❌ Bolsas de plástico", "texto": "No al reciclaje de casa. Lleva a centros de acopio en supermercados."},
|
||||
],
|
||||
"consejo_rapido": "Busca el número en el triángulo en el fondo del envase. #1 y #2 siempre al reciclaje.",
|
||||
},
|
||||
{
|
||||
"id": "residuos-peligrosos",
|
||||
"categoria": "Residuos Especiales",
|
||||
"emoji": "⚠️",
|
||||
"titulo": "Residuos peligrosos: cómo deshacerte de ellos",
|
||||
"resumen": "Pilas, medicamentos y electrónicos requieren manejo especial para no contaminar.",
|
||||
"contenido": [
|
||||
{"subtitulo": "Pilas y baterías", "texto": "Una pila AA puede contaminar 600,000 litros de agua. Lleva a Walmart, Soriana o OXXO."},
|
||||
{"subtitulo": "Medicamentos caducados", "texto": "No al drenaje. Farmacias del Ahorro y Benavides tienen contenedores REPARED."},
|
||||
{"subtitulo": "Electrónicos (RAEE)", "texto": "Celulares, cables, focos LED. Contienen plomo y mercurio. Lleva a Best Buy o Liverpool."},
|
||||
{"subtitulo": "Aceite de cocina", "texto": "Un litro contamina 1,000 litros de agua. Guárdalo en botella PET y lleva a acopio."},
|
||||
],
|
||||
"consejo_rapido": "Guarda una caja en casa solo para residuos peligrosos. Cuando esté llena, busca el punto de acopio.",
|
||||
},
|
||||
{
|
||||
"id": "composta",
|
||||
"categoria": "Compostaje",
|
||||
"emoji": "🌱",
|
||||
"titulo": "Haz composta en casa",
|
||||
"resumen": "Convierte tus residuos orgánicos en abono natural. Es más fácil de lo que crees.",
|
||||
"contenido": [
|
||||
{"subtitulo": "¿Qué necesitas?", "texto": "Un contenedor con tapa, residuos orgánicos, tierra o hojarasca y paciencia."},
|
||||
{"subtitulo": "¿Qué puedes compostar?", "texto": "Cáscaras de frutas, restos sin carne, posos de café, cáscaras de huevo, hojas secas."},
|
||||
{"subtitulo": "¿Qué NO?", "texto": "Carnes, lácteos, aceites (atraen plagas), excrementos de mascotas, plásticos."},
|
||||
{"subtitulo": "El proceso", "texto": "Alterna capas húmedas con secas. Voltea cada semana. En 2-3 meses tienes composta lista."},
|
||||
],
|
||||
"consejo_rapido": "La composta lista huele a tierra mojada, no a podrido. Si huele mal, agrega material seco.",
|
||||
},
|
||||
{
|
||||
"id": "impacto-ambiental",
|
||||
"categoria": "Medio Ambiente",
|
||||
"emoji": "🌍",
|
||||
"titulo": "El impacto real de reciclar",
|
||||
"resumen": "Números concretos para entender por qué vale la pena separar tu basura cada día.",
|
||||
"contenido": [
|
||||
{"subtitulo": "Papel y cartón", "texto": "1 tonelada reciclada salva 17 árboles y ahorra 26,000 litros de agua."},
|
||||
{"subtitulo": "Aluminio", "texto": "Reciclar una lata ahorra energía para un foco LED por 20 horas. Se recicla infinitas veces."},
|
||||
{"subtitulo": "Vidrio", "texto": "Tarda 4,000 años en degradarse. Reciclarlo reduce 20% las emisiones de su producción."},
|
||||
{"subtitulo": "Residuos en México", "texto": "México genera 120,000 toneladas de basura al día. Solo el 9% se recicla. Podemos hacer más."},
|
||||
],
|
||||
"consejo_rapido": "Cada lata de aluminio reciclada ahorra energía equivalente a medio litro de gasolina. Sí importa.",
|
||||
},
|
||||
];
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// COLORES POR CATEGORÍA
|
||||
// ----------------------------------------------------------------
|
||||
Color _colorCategoria(String categoria) {
|
||||
switch (categoria) {
|
||||
case 'Separación': return const Color(0xFF2E7D32);
|
||||
case 'Horarios': return const Color(0xFF1565C0);
|
||||
case 'Reciclaje': return const Color(0xFF00838F);
|
||||
case 'Compostaje': return const Color(0xFF558B2F);
|
||||
case 'Residuos Especiales': return const Color(0xFFE65100);
|
||||
case 'Medio Ambiente': return const Color(0xFF4527A0);
|
||||
default: return const Color(0xFF37474F);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// PANTALLA PRINCIPAL: Lista de artículos
|
||||
// ================================================================
|
||||
class InfoScreen extends StatefulWidget {
|
||||
const InfoScreen({super.key});
|
||||
|
||||
@override
|
||||
State<InfoScreen> createState() => _InfoScreenState();
|
||||
}
|
||||
|
||||
class _InfoScreenState extends State<InfoScreen> {
|
||||
List<Articulo> _articulos = [];
|
||||
bool _cargando = true;
|
||||
String? _categoriaSeleccionada;
|
||||
|
||||
static const String _baseUrl = 'http://192.168.198.224:8000';
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarArticulos();
|
||||
}
|
||||
|
||||
Future<void> _cargarArticulos() async {
|
||||
try {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/info'))
|
||||
.timeout(const Duration(seconds: 8));
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final data = json.decode(response.body);
|
||||
// El endpoint de lista no trae contenido completo,
|
||||
// así que cargamos desde fallback y enriquecemos con backend
|
||||
final ids = (data['articulos'] as List).map((a) => a['id'] as String).toList();
|
||||
final articulos = <Articulo>[];
|
||||
for (final fallback in _articulosFallback) {
|
||||
if (ids.contains(fallback['id'])) {
|
||||
articulos.add(Articulo.fromJson(fallback as Map<String, dynamic>));
|
||||
}
|
||||
}
|
||||
if (mounted) setState(() { _articulos = articulos; _cargando = false; });
|
||||
return;
|
||||
}
|
||||
} catch (_) {
|
||||
// Fallback silencioso
|
||||
}
|
||||
|
||||
// Carga local si el backend no responde
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_articulos = _articulosFallback
|
||||
.map((a) => Articulo.fromJson(a as Map<String, dynamic>))
|
||||
.toList();
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
List<String> get _categorias =>
|
||||
_articulos.map((a) => a.categoria).toSet().toList();
|
||||
|
||||
List<Articulo> get _articulosFiltrados => _categoriaSeleccionada == null
|
||||
? _articulos
|
||||
: _articulos.where((a) => a.categoria == _categoriaSeleccionada).toList();
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF5F7F5),
|
||||
appBar: AppBar(
|
||||
title: const Text('Información relevante'),
|
||||
backgroundColor: const Color(0xFF2E7D32),
|
||||
foregroundColor: Colors.white,
|
||||
elevation: 0,
|
||||
),
|
||||
body: _cargando
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: Column(
|
||||
children: [
|
||||
// ── HEADER VERDE ─────────────────────────────────
|
||||
Container(
|
||||
width: double.infinity,
|
||||
color: const Color(0xFF2E7D32),
|
||||
padding: const EdgeInsets.fromLTRB(20, 0, 20, 20),
|
||||
child: const Text(
|
||||
'Aprende a manejar tus residuos de forma responsable y reduce tu impacto ambiental.',
|
||||
style: TextStyle(color: Colors.white70, fontSize: 14),
|
||||
),
|
||||
),
|
||||
|
||||
// ── FILTROS POR CATEGORÍA ─────────────────────────
|
||||
if (_categorias.isNotEmpty)
|
||||
SizedBox(
|
||||
height: 48,
|
||||
child: ListView(
|
||||
scrollDirection: Axis.horizontal,
|
||||
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
|
||||
children: [
|
||||
_FiltroChip(
|
||||
label: 'Todos',
|
||||
seleccionado: _categoriaSeleccionada == null,
|
||||
color: const Color(0xFF2E7D32),
|
||||
onTap: () => setState(() => _categoriaSeleccionada = null),
|
||||
),
|
||||
...(_categorias.map((cat) => _FiltroChip(
|
||||
label: cat,
|
||||
seleccionado: _categoriaSeleccionada == cat,
|
||||
color: _colorCategoria(cat),
|
||||
onTap: () => setState(() => _categoriaSeleccionada = cat),
|
||||
))),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
// ── LISTA DE ARTÍCULOS ────────────────────────────
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
padding: const EdgeInsets.fromLTRB(16, 8, 16, 24),
|
||||
itemCount: _articulosFiltrados.length,
|
||||
itemBuilder: (context, index) {
|
||||
final articulo = _articulosFiltrados[index];
|
||||
return _TarjetaArticulo(
|
||||
articulo: articulo,
|
||||
onTap: () => Navigator.push(
|
||||
context,
|
||||
MaterialPageRoute(
|
||||
builder: (_) => _DetalleArticuloScreen(articulo: articulo),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// WIDGET: Chip de filtro por categoría
|
||||
// ================================================================
|
||||
class _FiltroChip extends StatelessWidget {
|
||||
final String label;
|
||||
final bool seleccionado;
|
||||
final Color color;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _FiltroChip({
|
||||
required this.label,
|
||||
required this.seleccionado,
|
||||
required this.color,
|
||||
required this.onTap,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 8),
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: AnimatedContainer(
|
||||
duration: const Duration(milliseconds: 200),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 6),
|
||||
decoration: BoxDecoration(
|
||||
color: seleccionado ? color : Colors.white,
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
border: Border.all(color: color, width: 1.5),
|
||||
),
|
||||
child: Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
color: seleccionado ? Colors.white : color,
|
||||
fontWeight: FontWeight.w600,
|
||||
fontSize: 13,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// WIDGET: Tarjeta de artículo en la lista
|
||||
// ================================================================
|
||||
class _TarjetaArticulo extends StatelessWidget {
|
||||
final Articulo articulo;
|
||||
final VoidCallback onTap;
|
||||
|
||||
const _TarjetaArticulo({required this.articulo, required this.onTap});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _colorCategoria(articulo.categoria);
|
||||
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(bottom: 12),
|
||||
child: GestureDetector(
|
||||
onTap: onTap,
|
||||
child: Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.06),
|
||||
blurRadius: 8,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Barra de color superior
|
||||
Container(
|
||||
height: 6,
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
|
||||
),
|
||||
),
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Emoji grande
|
||||
Container(
|
||||
width: 52,
|
||||
height: 52,
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(articulo.emoji, style: const TextStyle(fontSize: 28)),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 14),
|
||||
Expanded(
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Badge de categoría
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
articulo.categoria,
|
||||
style: TextStyle(
|
||||
color: color,
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w700,
|
||||
letterSpacing: 0.5,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
articulo.titulo,
|
||||
style: const TextStyle(
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Color(0xFF1A1A1A),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
articulo.resumen,
|
||||
style: TextStyle(
|
||||
fontSize: 13,
|
||||
color: Colors.grey.shade600,
|
||||
height: 1.4,
|
||||
),
|
||||
maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey.shade400),
|
||||
],
|
||||
),
|
||||
),
|
||||
// Consejo rápido al pie
|
||||
Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.fromLTRB(16, 0, 16, 16),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.07),
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text('💡', style: TextStyle(fontSize: 14, color: color)),
|
||||
const SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
articulo.consejoRapido,
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: color,
|
||||
fontWeight: FontWeight.w500,
|
||||
height: 1.4,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// PANTALLA DE DETALLE DE ARTÍCULO
|
||||
// ================================================================
|
||||
class _DetalleArticuloScreen extends StatelessWidget {
|
||||
final Articulo articulo;
|
||||
|
||||
const _DetalleArticuloScreen({required this.articulo});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final color = _colorCategoria(articulo.categoria);
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: const Color(0xFFF5F7F5),
|
||||
body: CustomScrollView(
|
||||
slivers: [
|
||||
// ── APP BAR CON COLOR DE CATEGORÍA ───────────────────
|
||||
SliverAppBar(
|
||||
expandedHeight: 160,
|
||||
pinned: true,
|
||||
backgroundColor: color,
|
||||
foregroundColor: Colors.white,
|
||||
flexibleSpace: FlexibleSpaceBar(
|
||||
title: Text(
|
||||
articulo.titulo,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
background: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [color, color.withValues(alpha: 0.7)],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(articulo.emoji, style: const TextStyle(fontSize: 64)),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
SliverToBoxAdapter(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(20),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
// Badge categoría
|
||||
Container(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 5),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withValues(alpha: 0.12),
|
||||
borderRadius: BorderRadius.circular(20),
|
||||
),
|
||||
child: Text(
|
||||
articulo.categoria,
|
||||
style: TextStyle(color: color, fontWeight: FontWeight.w700, fontSize: 13),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Resumen
|
||||
Text(
|
||||
articulo.resumen,
|
||||
style: const TextStyle(
|
||||
fontSize: 16,
|
||||
color: Color(0xFF333333),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// ── SECCIONES DE CONTENIDO ───────────────────
|
||||
...articulo.contenido.map((seccion) => _SeccionCard(
|
||||
seccion: seccion,
|
||||
color: color,
|
||||
)),
|
||||
|
||||
const SizedBox(height: 8),
|
||||
|
||||
// ── CONSEJO RÁPIDO DESTACADO ─────────────────
|
||||
Container(
|
||||
width: double.infinity,
|
||||
padding: const EdgeInsets.all(20),
|
||||
decoration: BoxDecoration(
|
||||
color: color,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Row(
|
||||
children: [
|
||||
Text('💡', style: TextStyle(fontSize: 20)),
|
||||
SizedBox(width: 8),
|
||||
Text(
|
||||
'Consejo rápido',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontWeight: FontWeight.bold,
|
||||
fontSize: 16,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
const SizedBox(height: 10),
|
||||
Text(
|
||||
articulo.consejoRapido,
|
||||
style: const TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 15,
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 32),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// WIDGET: Tarjeta de una sección dentro del detalle
|
||||
// ================================================================
|
||||
class _SeccionCard extends StatelessWidget {
|
||||
final Subseccion seccion;
|
||||
final Color color;
|
||||
|
||||
const _SeccionCard({required this.seccion, required this.color});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
margin: const EdgeInsets.only(bottom: 12),
|
||||
padding: const EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
border: Border(left: BorderSide(color: color, width: 4)),
|
||||
boxShadow: [
|
||||
BoxShadow(
|
||||
color: Colors.black.withValues(alpha: 0.04),
|
||||
blurRadius: 6,
|
||||
offset: const Offset(0, 2),
|
||||
),
|
||||
],
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
seccion.subtitulo,
|
||||
style: TextStyle(
|
||||
fontSize: 14,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 6),
|
||||
Text(
|
||||
seccion.texto,
|
||||
style: const TextStyle(
|
||||
fontSize: 14,
|
||||
color: Color(0xFF444444),
|
||||
height: 1.5,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,20 +1,11 @@
|
||||
// ================================================================
|
||||
// lib/screens/login_screen.dart
|
||||
// Pantalla de Login Mockeada — Hackathon MVP
|
||||
// lib/screens/login_screen.dart (v2)
|
||||
// ================================================================
|
||||
//
|
||||
// PROPÓSITO:
|
||||
// Simular la selección de identidad de usuario para la demo.
|
||||
// En producción aquí iría: Google Sign-In, OTP por SMS, etc.
|
||||
//
|
||||
// FLUJO:
|
||||
// 1. Usuario ingresa un ID numérico (1-4 para los seed data)
|
||||
// 2. Selecciona su colonia en un Dropdown
|
||||
// 3. Presiona "Entrar" -> navega a HomeScreen con el usuario_id
|
||||
//
|
||||
// ATAJO DE HACKATHON:
|
||||
// El "ID de usuario" es manual para evitar un sistema de auth
|
||||
// completo. Para la demo, los IDs 1-4 son los del seed.
|
||||
// CAMBIOS v2:
|
||||
// - loginConCorreo ahora devuelve también el nombre del usuario
|
||||
// - El nombre se guarda en SharedPreferences para mostrarlo en home
|
||||
// - Mensaje de error más específico (viene del backend)
|
||||
// ================================================================
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
@@ -29,40 +20,21 @@ class LoginScreen extends StatefulWidget {
|
||||
}
|
||||
|
||||
class _LoginScreenState extends State<LoginScreen> {
|
||||
// ----------------------------------------------------------------
|
||||
// ESTADO LOCAL
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
// Controladores para los campos de email/registro
|
||||
final TextEditingController _emailController = TextEditingController();
|
||||
final TextEditingController _passwordController = TextEditingController();
|
||||
final TextEditingController _nameController = TextEditingController();
|
||||
final TextEditingController _direccionController = TextEditingController();
|
||||
|
||||
// Colonia seleccionada en el Dropdown (null = no seleccionada aún)
|
||||
String? _coloniaSeleccionada;
|
||||
|
||||
// Lista de colonias cargadas desde el backend
|
||||
List<String> _colonias = [];
|
||||
|
||||
// Indica si estamos en modo registro o en modo login
|
||||
bool _esRegistro = false;
|
||||
|
||||
// Estado de carga: mostramos spinner mientras cargamos colonias
|
||||
bool _cargandoColonias = true;
|
||||
|
||||
// Estado de error al cargar colonias
|
||||
String? _errorColonias;
|
||||
|
||||
// Estado del botón de login: evita doble tap
|
||||
bool _logueando = false;
|
||||
bool _mostrarPassword = false;
|
||||
|
||||
// Servicio de API (instancia local, sin inyección para el hackathon)
|
||||
final ApiService _apiService = ApiService();
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// LIFECYCLE
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
@@ -72,40 +44,24 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Siempre liberar controllers para evitar memory leaks
|
||||
_emailController.dispose();
|
||||
_passwordController.dispose();
|
||||
_nameController.dispose();
|
||||
_direccionController.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// VERIFICAR SESIÓN EXISTENTE
|
||||
//
|
||||
// Si el usuario ya se logueó antes (guardado en shared_preferences),
|
||||
// lo mandamos directo al home sin pasar por el login.
|
||||
// ATAJO: Esto simula "recordar sesión". No es auth real.
|
||||
// Si ya hay sesión guardada, saltamos el login directamente.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _verificarSesionExistente() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final usuarioIdGuardado = prefs.getInt('usuario_id');
|
||||
|
||||
if (usuarioIdGuardado != null && mounted) {
|
||||
// Ya hay sesión, ir al home directamente
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/home',
|
||||
arguments: usuarioIdGuardado,
|
||||
);
|
||||
final usuarioId = prefs.getInt('usuario_id');
|
||||
if (usuarioId != null && mounted) {
|
||||
Navigator.pushReplacementNamed(context, '/home', arguments: usuarioId);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CARGAR COLONIAS DESDE EL BACKEND
|
||||
//
|
||||
// Intenta cargar desde la API. Si falla (backend apagado),
|
||||
// usa una lista de fallback hardcodeada para no bloquear la demo.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _cargarColonias() async {
|
||||
try {
|
||||
final colonias = await _apiService.obtenerColonias();
|
||||
@@ -116,18 +72,11 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
// FALLBACK: Lista hardcodeada por si el backend no está corriendo
|
||||
// Útil para desarrollar el frontend en paralelo al backend
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_colonias = [
|
||||
'Zona Centro',
|
||||
'Col. Hidalgo',
|
||||
'Col. Independencia',
|
||||
'Col. Obrera',
|
||||
'Col. San Juan',
|
||||
'Fracc. Los Pinos',
|
||||
'Col. Reforma',
|
||||
'Zona Centro', 'Las Arboledas', 'Trojes',
|
||||
'San Juanico', 'Los Olivos', 'Rancho Seco', 'Las Insurgentes',
|
||||
];
|
||||
_cargandoColonias = false;
|
||||
_errorColonias = 'Sin conexión al backend. Usando lista local.';
|
||||
@@ -137,100 +86,77 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// ACCIÓN: INICIAR SESIÓN
|
||||
// Valida el correo, llama al backend y navega.
|
||||
// LOGIN
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _iniciarSesion() async {
|
||||
final email = _emailController.text.trim();
|
||||
if (email.isEmpty) {
|
||||
_mostrarError('Por favor ingresa tu correo.');
|
||||
return;
|
||||
}
|
||||
final password = _passwordController.text;
|
||||
|
||||
if (email.isEmpty) { _mostrarError('Por favor ingresa tu correo.'); return; }
|
||||
if (password.isEmpty) { _mostrarError('Por favor ingresa tu contraseña.'); return; }
|
||||
|
||||
setState(() => _logueando = true);
|
||||
|
||||
try {
|
||||
final usuarioId = await _apiService.loginConCorreo(email);
|
||||
// v2: devuelve {usuario_id, nombre}
|
||||
final resultado = await _apiService.loginConCorreo(email, password);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt('usuario_id', usuarioId);
|
||||
await prefs.setInt('usuario_id', resultado['usuario_id']);
|
||||
await prefs.setString('nombre', resultado['nombre'] ?? '');
|
||||
await prefs.setString('email', email);
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/home',
|
||||
arguments: usuarioId,
|
||||
);
|
||||
Navigator.pushReplacementNamed(context, '/home', arguments: resultado['usuario_id']);
|
||||
}
|
||||
} catch (e) {
|
||||
_mostrarError('Error iniciando sesión. Revisa tu correo o regístrate.');
|
||||
// Muestra el mensaje de error que viene del backend (más específico)
|
||||
final mensaje = e.toString().replaceFirst('Exception: ', '');
|
||||
_mostrarError(mensaje);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _logueando = false);
|
||||
}
|
||||
if (mounted) setState(() => _logueando = false);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// ACCIÓN: REGISTRARSE
|
||||
// Valida los datos y crea un nuevo usuario en el backend.
|
||||
// REGISTRO
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> _registrarse() async {
|
||||
final nombre = _nameController.text.trim();
|
||||
final email = _emailController.text.trim();
|
||||
final password = _passwordController.text;
|
||||
final direccion = _direccionController.text.trim();
|
||||
|
||||
if (nombre.isEmpty) {
|
||||
_mostrarError('Por favor ingresa tu nombre.');
|
||||
return;
|
||||
}
|
||||
if (email.isEmpty) {
|
||||
_mostrarError('Por favor ingresa tu correo.');
|
||||
return;
|
||||
}
|
||||
if (_coloniaSeleccionada == null) {
|
||||
_mostrarError('Por favor selecciona tu colonia.');
|
||||
return;
|
||||
}
|
||||
if (direccion.isEmpty) {
|
||||
_mostrarError('Por favor ingresa tu dirección.');
|
||||
return;
|
||||
}
|
||||
if (nombre.isEmpty) { _mostrarError('Por favor ingresa tu nombre.'); return; }
|
||||
if (email.isEmpty) { _mostrarError('Por favor ingresa tu correo.'); return; }
|
||||
if (password.isEmpty) { _mostrarError('Por favor ingresa tu contraseña.'); return; }
|
||||
if (password.length < 6) { _mostrarError('La contraseña debe tener al menos 6 caracteres.'); return; }
|
||||
if (_coloniaSeleccionada == null) { _mostrarError('Por favor selecciona tu colonia.'); return; }
|
||||
if (direccion.isEmpty) { _mostrarError('Por favor ingresa tu dirección.'); return; }
|
||||
|
||||
setState(() => _logueando = true);
|
||||
|
||||
try {
|
||||
final usuarioId = await _apiService.registrarUsuario(
|
||||
nombre,
|
||||
email,
|
||||
direccion,
|
||||
_coloniaSeleccionada!,
|
||||
nombre, email, password, direccion, _coloniaSeleccionada!,
|
||||
);
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setInt('usuario_id', usuarioId);
|
||||
await prefs.setString('nombre', nombre);
|
||||
await prefs.setString('email', email);
|
||||
await prefs.setString('colonia', _coloniaSeleccionada!);
|
||||
|
||||
if (mounted) {
|
||||
Navigator.pushReplacementNamed(
|
||||
context,
|
||||
'/home',
|
||||
arguments: usuarioId,
|
||||
);
|
||||
Navigator.pushReplacementNamed(context, '/home', arguments: usuarioId);
|
||||
}
|
||||
} catch (e) {
|
||||
_mostrarError('Error registrando usuario. Intenta con otro correo.');
|
||||
final mensaje = e.toString().replaceFirst('Exception: ', '');
|
||||
_mostrarError(mensaje);
|
||||
} finally {
|
||||
if (mounted) {
|
||||
setState(() => _logueando = false);
|
||||
}
|
||||
if (mounted) setState(() => _logueando = false);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// HELPER: Mostrar mensaje de error con SnackBar
|
||||
// ----------------------------------------------------------------
|
||||
void _mostrarError(String mensaje) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Text(mensaje),
|
||||
@@ -241,220 +167,232 @@ class _LoginScreenState extends State<LoginScreen> {
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// UI
|
||||
// BUILD
|
||||
// ================================================================
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final colorScheme = Theme.of(context).colorScheme;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: colorScheme.surface,
|
||||
body: SafeArea(
|
||||
child: Center(
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.all(32.0),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
// ------------------------------------------------
|
||||
// HEADER: Ícono y título
|
||||
// ------------------------------------------------
|
||||
Icon(
|
||||
Icons.recycling_rounded,
|
||||
size: 80,
|
||||
child: SingleChildScrollView(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 28, vertical: 32),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// ── LOGO ──────────────────────────────────────────
|
||||
Icon(Icons.recycling_rounded, size: 80, color: colorScheme.primary),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Recolección\nInteligente',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
Text(
|
||||
'Recolección\nInteligente',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.headlineMedium?.copyWith(
|
||||
fontWeight: FontWeight.bold,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
'Ingresa tus datos para recibir notificaciones de tu camión',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 48),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Text(
|
||||
_esRegistro
|
||||
? 'Regístrate para recibir alertas del camión'
|
||||
: 'Inicia sesión para ver el estado del camión',
|
||||
textAlign: TextAlign.center,
|
||||
style: Theme.of(context).textTheme.bodyMedium?.copyWith(color: Colors.grey.shade600),
|
||||
),
|
||||
const SizedBox(height: 40),
|
||||
|
||||
// ------------------------------------------------
|
||||
// FORMULARIO: Correo / Registro
|
||||
// ------------------------------------------------
|
||||
// ── CAMPOS COMUNES ────────────────────────────────
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Correo electrónico',
|
||||
hintText: 'usuario@ejemplo.com',
|
||||
prefixIcon: const Icon(Icons.email_outlined),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _passwordController,
|
||||
obscureText: !_mostrarPassword,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Contraseña',
|
||||
hintText: '••••••••',
|
||||
prefixIcon: const Icon(Icons.lock_outline),
|
||||
suffixIcon: IconButton(
|
||||
icon: Icon(_mostrarPassword ? Icons.visibility_off : Icons.visibility),
|
||||
onPressed: () => setState(() => _mostrarPassword = !_mostrarPassword),
|
||||
),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// ── CAMPOS EXTRA (solo en registro) ───────────────
|
||||
if (_esRegistro) ...[
|
||||
TextField(
|
||||
controller: _emailController,
|
||||
keyboardType: TextInputType.emailAddress,
|
||||
controller: _nameController,
|
||||
textCapitalization: TextCapitalization.words,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Correo electrónico',
|
||||
hintText: 'usuario@ejemplo.com',
|
||||
prefixIcon: const Icon(Icons.email_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
labelText: 'Nombre completo',
|
||||
prefixIcon: const Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
if (_esRegistro) ...[
|
||||
TextField(
|
||||
controller: _nameController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nombre completo',
|
||||
prefixIcon: const Icon(Icons.person_outline),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
TextField(
|
||||
controller: _direccionController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Dirección',
|
||||
hintText: 'Calle, número',
|
||||
prefixIcon: const Icon(Icons.home_outlined),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
TextField(
|
||||
controller: _direccionController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Dirección',
|
||||
hintText: 'Calle, número, colonia',
|
||||
prefixIcon: const Icon(Icons.home_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (_cargandoColonias)
|
||||
const Center(child: Padding(padding: EdgeInsets.all(16), child: CircularProgressIndicator()))
|
||||
else ...[
|
||||
if (_errorColonias != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text('⚠️ $_errorColonias',
|
||||
style: TextStyle(fontSize: 12, color: Colors.orange.shade700)),
|
||||
),
|
||||
DropdownButtonFormField<String>(
|
||||
value: _coloniaSeleccionada,
|
||||
hint: const Text('Selecciona tu colonia'),
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.location_city_outlined),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
items: _colonias.map((c) => DropdownMenuItem(value: c, child: Text(c))).toList(),
|
||||
onChanged: (valor) => setState(() => _coloniaSeleccionada = valor),
|
||||
),
|
||||
const SizedBox(height: 20),
|
||||
],
|
||||
|
||||
if (_esRegistro)
|
||||
if (_cargandoColonias)
|
||||
const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 16),
|
||||
child: CircularProgressIndicator(),
|
||||
),
|
||||
)
|
||||
else ...[
|
||||
if (_errorColonias != null)
|
||||
Padding(
|
||||
padding: const EdgeInsets.only(bottom: 8),
|
||||
child: Text(
|
||||
'⚠️ $_errorColonias',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: Colors.orange.shade700,
|
||||
),
|
||||
),
|
||||
),
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: _coloniaSeleccionada,
|
||||
hint: const Text('Selecciona tu colonia'),
|
||||
decoration: InputDecoration(
|
||||
prefixIcon: const Icon(Icons.location_city_outlined),
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
items: _colonias.map((colonia) {
|
||||
return DropdownMenuItem(
|
||||
value: colonia,
|
||||
child: Text(colonia),
|
||||
);
|
||||
}).toList(),
|
||||
onChanged: (valor) {
|
||||
setState(() => _coloniaSeleccionada = valor);
|
||||
},
|
||||
),
|
||||
],
|
||||
const SizedBox(height: 32),
|
||||
|
||||
// ------------------------------------------------
|
||||
// BOTÓN: Entrar / Registrarse
|
||||
// Muestra spinner mientras _logueando == true
|
||||
// ------------------------------------------------
|
||||
SizedBox(
|
||||
height: 56,
|
||||
child: ElevatedButton(
|
||||
onPressed: _logueando
|
||||
? null
|
||||
: _esRegistro
|
||||
? _registrarse
|
||||
: _iniciarSesion,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
foregroundColor: colorScheme.onPrimary,
|
||||
shape: RoundedRectangleBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
),
|
||||
child: _logueando
|
||||
? const SizedBox(
|
||||
height: 24,
|
||||
width: 24,
|
||||
child: CircularProgressIndicator(
|
||||
strokeWidth: 2,
|
||||
color: Colors.white,
|
||||
),
|
||||
)
|
||||
: Text(
|
||||
_esRegistro ? 'Registrarse' : 'Iniciar sesión',
|
||||
style: const TextStyle(
|
||||
fontSize: 18,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: _logueando
|
||||
? null
|
||||
: () {
|
||||
setState(() {
|
||||
_esRegistro = !_esRegistro;
|
||||
// Clear fields when switching modes
|
||||
_nameController.clear();
|
||||
_direccionController.clear();
|
||||
_coloniaSeleccionada = null;
|
||||
});
|
||||
},
|
||||
child: Text(
|
||||
_esRegistro
|
||||
? '¿Ya tienes cuenta? Inicia sesión'
|
||||
: '¿No tienes cuenta? Regístrate',
|
||||
style: TextStyle(
|
||||
color: colorScheme.primary,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primaryContainer.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
_esRegistro
|
||||
? 'Regístrate con tu correo, nombre y dirección para recibir avisos de recolección.'
|
||||
: 'Inicia sesión con tu correo para ver el estado del camión y recibir notificaciones.',
|
||||
style: TextStyle(
|
||||
fontSize: 12,
|
||||
color: colorScheme.primary,
|
||||
),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// Indicador de fortaleza de contraseña
|
||||
_PasswordStrengthIndicator(password: _passwordController.text),
|
||||
const SizedBox(height: 8),
|
||||
],
|
||||
),
|
||||
|
||||
const SizedBox(height: 24),
|
||||
|
||||
// ── BOTÓN PRINCIPAL ───────────────────────────────
|
||||
SizedBox(
|
||||
height: 56,
|
||||
child: ElevatedButton(
|
||||
onPressed: _logueando ? null : (_esRegistro ? _registrarse : _iniciarSesion),
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: colorScheme.primary,
|
||||
foregroundColor: colorScheme.onPrimary,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
child: _logueando
|
||||
? const SizedBox(
|
||||
height: 24, width: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2, color: Colors.white),
|
||||
)
|
||||
: Text(
|
||||
_esRegistro ? 'Registrarse' : 'Iniciar sesión',
|
||||
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
|
||||
),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// ── TOGGLE LOGIN/REGISTRO ─────────────────────────
|
||||
TextButton(
|
||||
onPressed: _logueando
|
||||
? null
|
||||
: () => setState(() {
|
||||
_esRegistro = !_esRegistro;
|
||||
_nameController.clear();
|
||||
_direccionController.clear();
|
||||
_coloniaSeleccionada = null;
|
||||
_passwordController.clear();
|
||||
}),
|
||||
child: Text(
|
||||
_esRegistro ? '¿Ya tienes cuenta? Inicia sesión' : '¿No tienes cuenta? Regístrate',
|
||||
style: TextStyle(color: colorScheme.primary, fontWeight: FontWeight.w600),
|
||||
),
|
||||
),
|
||||
|
||||
const SizedBox(height: 16),
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: colorScheme.primaryContainer.withValues(alpha: 0.3),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
),
|
||||
child: Text(
|
||||
_esRegistro
|
||||
? 'Tu contraseña se almacena de forma segura (bcrypt). Mínimo 6 caracteres.'
|
||||
: 'Inicia sesión con tu correo para ver el estado del camión y recibir notificaciones.',
|
||||
style: TextStyle(fontSize: 12, color: colorScheme.primary),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// WIDGET: Indicador de fortaleza de contraseña
|
||||
// Muestra una barra de color que se llena según la complejidad.
|
||||
// Solo se muestra en el modo registro.
|
||||
// ================================================================
|
||||
class _PasswordStrengthIndicator extends StatelessWidget {
|
||||
final String password;
|
||||
const _PasswordStrengthIndicator({required this.password});
|
||||
|
||||
// Retorna (nivel 0-3, etiqueta, color)
|
||||
(int, String, Color) _evaluar() {
|
||||
if (password.isEmpty) return (0, '', Colors.grey);
|
||||
int puntos = 0;
|
||||
if (password.length >= 8) puntos++;
|
||||
if (password.contains(RegExp(r'[A-Z]'))) puntos++;
|
||||
if (password.contains(RegExp(r'[0-9]'))) puntos++;
|
||||
if (password.contains(RegExp(r'[!@#\$%^&*]'))) puntos++;
|
||||
|
||||
if (puntos <= 1) return (1, 'Débil', Colors.red);
|
||||
if (puntos == 2) return (2, 'Regular', Colors.orange);
|
||||
if (puntos == 3) return (3, 'Buena', Colors.lightGreen);
|
||||
return (4, 'Excelente', Colors.green);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
if (password.isEmpty) return const SizedBox.shrink();
|
||||
final (nivel, etiqueta, color) = _evaluar();
|
||||
return Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Row(
|
||||
children: List.generate(4, (i) {
|
||||
return Expanded(
|
||||
child: Container(
|
||||
margin: const EdgeInsets.only(right: 4),
|
||||
height: 4,
|
||||
decoration: BoxDecoration(
|
||||
color: i < nivel ? color : Colors.grey.shade300,
|
||||
borderRadius: BorderRadius.circular(2),
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
),
|
||||
const SizedBox(height: 4),
|
||||
Text('Contraseña: $etiqueta', style: TextStyle(fontSize: 12, color: color)),
|
||||
],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import '../services/api_service.dart';
|
||||
|
||||
class RouteListScreen extends StatefulWidget {
|
||||
@@ -14,11 +15,30 @@ class _RouteListScreenState extends State<RouteListScreen> {
|
||||
bool _avanzando = false;
|
||||
String? _error;
|
||||
List<RouteInfo> _rutas = [];
|
||||
int? _usuarioId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_cargarRutas();
|
||||
_cargarUsuarioYRutas();
|
||||
}
|
||||
|
||||
Future<void> _cargarUsuarioYRutas() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final usuarioId = prefs.getInt('usuario_id');
|
||||
|
||||
if (usuarioId == null) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = 'No se encontró sesión activa. Por favor inicia sesión de nuevo.';
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
_usuarioId = usuarioId;
|
||||
await _cargarRutas();
|
||||
}
|
||||
|
||||
Future<void> _cargarRutas() async {
|
||||
@@ -27,8 +47,18 @@ class _RouteListScreenState extends State<RouteListScreen> {
|
||||
_error = null;
|
||||
});
|
||||
|
||||
if (_usuarioId == null) {
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_error = 'No se encontró sesión activa. Por favor inicia sesión de nuevo.';
|
||||
_cargando = false;
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final rutas = await _apiService.obtenerRutas();
|
||||
final rutas = await _apiService.obtenerRutas(_usuarioId!);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_rutas = rutas;
|
||||
@@ -54,8 +84,20 @@ class _RouteListScreenState extends State<RouteListScreen> {
|
||||
_avanzando = true;
|
||||
});
|
||||
|
||||
if (_usuarioId == null) {
|
||||
if (mounted) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(
|
||||
content: Text('No se encontró sesión activa. Inicia sesión de nuevo.'),
|
||||
backgroundColor: Colors.redAccent,
|
||||
),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
final rutaActualizada = await _apiService.avanzarRuta(routeId);
|
||||
final rutaActualizada = await _apiService.avanzarRuta(routeId, _usuarioId!);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
final index = _rutas.indexWhere((r) => r.routeId == routeId);
|
||||
|
||||
@@ -1,30 +1,22 @@
|
||||
// ================================================================
|
||||
// lib/services/api_service.dart
|
||||
// lib/services/api_service.dart (v2)
|
||||
// Servicio de comunicación con el backend FastAPI
|
||||
// ================================================================
|
||||
//
|
||||
// PATRÓN: Service class singleton.
|
||||
// Una sola instancia maneja todas las llamadas HTTP de la app.
|
||||
//
|
||||
// ATAJO DE HACKATHON:
|
||||
// Usamos la librería 'http' sin abstracciones complejas.
|
||||
// En producción: usar Dio con interceptors para auth headers,
|
||||
// retry automático y mejor manejo de errores.
|
||||
//
|
||||
// CÓMO CONECTAR:
|
||||
// En cada Screen que necesite datos:
|
||||
// final service = ApiService();
|
||||
// final eta = await service.obtenerETA(usuarioId);
|
||||
// CAMBIOS v2:
|
||||
// - LoginResponse incluye 'nombre' del usuario
|
||||
// - ActualizarPassword requiere password_actual + password_nuevo
|
||||
// - Nuevos métodos: obtenerDashboard, historialPosiciones,
|
||||
// resumenRutas, estadisticasColonias
|
||||
// ================================================================
|
||||
|
||||
import 'dart:convert';
|
||||
import 'package:http/http.dart' as http;
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MODELO: ETAInfo
|
||||
// Representa la respuesta del endpoint GET /api/eta/{usuario_id}
|
||||
// Mapea exactamente los campos que devuelve el backend (main.py)
|
||||
// MODELOS
|
||||
// ----------------------------------------------------------------
|
||||
|
||||
class ETAInfo {
|
||||
final int usuarioId;
|
||||
final String colonia;
|
||||
@@ -46,9 +38,6 @@ class ETAInfo {
|
||||
required this.mensajePreventivo,
|
||||
});
|
||||
|
||||
// Factory constructor: convierte el JSON del backend a objeto Dart.
|
||||
// Los keys del JSON deben coincidir con los fields del ETAResponse
|
||||
// de Pydantic en main.py (usa snake_case, igual que FastAPI).
|
||||
factory ETAInfo.fromJson(Map<String, dynamic> json) {
|
||||
return ETAInfo(
|
||||
usuarioId: json['usuario_id'],
|
||||
@@ -67,16 +56,10 @@ class DireccionInfo {
|
||||
final String colonia;
|
||||
final String direccion;
|
||||
|
||||
DireccionInfo({
|
||||
required this.colonia,
|
||||
required this.direccion,
|
||||
});
|
||||
DireccionInfo({required this.colonia, required this.direccion});
|
||||
|
||||
factory DireccionInfo.fromJson(Map<String, dynamic> json) {
|
||||
return DireccionInfo(
|
||||
colonia: json['colonia'],
|
||||
direccion: json['direccion'],
|
||||
);
|
||||
return DireccionInfo(colonia: json['colonia'], direccion: json['direccion']);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,237 +117,367 @@ class RouteInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// Posición GPS individual de la ruta de un camión.
|
||||
class PosicionGPS {
|
||||
final int positionId;
|
||||
final double lat;
|
||||
final double lng;
|
||||
final int speed;
|
||||
final String timestamp;
|
||||
final bool esActual; // true = aquí está el camión ahora
|
||||
|
||||
PosicionGPS({
|
||||
required this.positionId,
|
||||
required this.lat,
|
||||
required this.lng,
|
||||
required this.speed,
|
||||
required this.timestamp,
|
||||
required this.esActual,
|
||||
});
|
||||
|
||||
factory PosicionGPS.fromJson(Map<String, dynamic> json) {
|
||||
return PosicionGPS(
|
||||
positionId: json['position_id'],
|
||||
lat: (json['lat'] as num).toDouble(),
|
||||
lng: (json['lng'] as num).toDouble(),
|
||||
speed: json['speed'],
|
||||
timestamp: json['timestamp'],
|
||||
esActual: json['es_actual'] ?? false,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Detalle de una ruta para el dashboard.
|
||||
class RutaDetalle {
|
||||
final String routeId;
|
||||
final String name;
|
||||
final String status;
|
||||
final int truckId;
|
||||
final int posicionActual;
|
||||
final int totalPosiciones;
|
||||
final double porcentajeCompletado;
|
||||
final int etaMinutos;
|
||||
final bool gpsOk;
|
||||
final int usuariosEnRuta;
|
||||
|
||||
RutaDetalle({
|
||||
required this.routeId,
|
||||
required this.name,
|
||||
required this.status,
|
||||
required this.truckId,
|
||||
required this.posicionActual,
|
||||
required this.totalPosiciones,
|
||||
required this.porcentajeCompletado,
|
||||
required this.etaMinutos,
|
||||
required this.gpsOk,
|
||||
required this.usuariosEnRuta,
|
||||
});
|
||||
|
||||
factory RutaDetalle.fromJson(Map<String, dynamic> json) {
|
||||
return RutaDetalle(
|
||||
routeId: json['route_id'],
|
||||
name: json['name'],
|
||||
status: json['status'],
|
||||
truckId: json['truck_id'],
|
||||
posicionActual: json['posicion_actual'],
|
||||
totalPosiciones: json['total_posiciones'],
|
||||
porcentajeCompletado: (json['porcentaje_completado'] as num).toDouble(),
|
||||
etaMinutos: json['eta_minutos'],
|
||||
gpsOk: json['gps_ok'],
|
||||
usuariosEnRuta: json['usuarios_en_ruta'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Respuesta completa del dashboard de operador.
|
||||
class DashboardInfo {
|
||||
final int totalRutas;
|
||||
final int rutasEnProgreso;
|
||||
final int rutasCompletadas;
|
||||
final int totalUsuarios;
|
||||
final int usuariosConToken;
|
||||
final double coberturaNotificaciones;
|
||||
final List<RutaDetalle> rutas;
|
||||
|
||||
DashboardInfo({
|
||||
required this.totalRutas,
|
||||
required this.rutasEnProgreso,
|
||||
required this.rutasCompletadas,
|
||||
required this.totalUsuarios,
|
||||
required this.usuariosConToken,
|
||||
required this.coberturaNotificaciones,
|
||||
required this.rutas,
|
||||
});
|
||||
|
||||
factory DashboardInfo.fromJson(Map<String, dynamic> json) {
|
||||
return DashboardInfo(
|
||||
totalRutas: json['total_rutas'],
|
||||
rutasEnProgreso: json['rutas_en_progreso'],
|
||||
rutasCompletadas: json['rutas_completadas'],
|
||||
totalUsuarios: json['total_usuarios'],
|
||||
usuariosConToken: json['usuarios_con_token'],
|
||||
coberturaNotificaciones: (json['cobertura_notificaciones'] as num).toDouble(),
|
||||
rutas: List<Map<String, dynamic>>.from(json['rutas'])
|
||||
.map(RutaDetalle.fromJson)
|
||||
.toList(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Estadísticas de una colonia.
|
||||
class ColoniaEstadistica {
|
||||
final String colonia;
|
||||
final String routeId;
|
||||
final String rutaNombre;
|
||||
final String horario;
|
||||
final int totalUsuarios;
|
||||
final int usuariosConNotificaciones;
|
||||
|
||||
ColoniaEstadistica({
|
||||
required this.colonia,
|
||||
required this.routeId,
|
||||
required this.rutaNombre,
|
||||
required this.horario,
|
||||
required this.totalUsuarios,
|
||||
required this.usuariosConNotificaciones,
|
||||
});
|
||||
|
||||
factory ColoniaEstadistica.fromJson(Map<String, dynamic> json) {
|
||||
return ColoniaEstadistica(
|
||||
colonia: json['colonia'],
|
||||
routeId: json['route_id'],
|
||||
rutaNombre: json['ruta_nombre'],
|
||||
horario: json['horario'],
|
||||
totalUsuarios: json['total_usuarios'],
|
||||
usuariosConNotificaciones: json['usuarios_con_notificaciones'],
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// CLASE PRINCIPAL: ApiService
|
||||
// ----------------------------------------------------------------
|
||||
class ApiService {
|
||||
// ============================================================
|
||||
// BASE URL DEL BACKEND
|
||||
//
|
||||
// DESARROLLO LOCAL:
|
||||
// - Android Emulator: usa 10.0.2.2 (mapea al localhost del PC)
|
||||
// - iOS Simulator: usa 127.0.0.1
|
||||
// - Dispositivo físico: IP real de tu máquina en la red local
|
||||
// (ej: http://192.168.1.100:8000)
|
||||
//
|
||||
// ATAJO: Cambia solo esta constante para apuntar a staging/prod.
|
||||
// BASE URL — Cambia solo esta línea para apuntar a otro entorno
|
||||
// Android emulator local: http://10.0.2.2:8000
|
||||
// Dispositivo físico (red local): http://192.168.X.X:8000
|
||||
// ============================================================
|
||||
static const String _baseUrl = 'http://192.168.192.96:8000';
|
||||
|
||||
|
||||
// Timeout razonable para demo. Si el backend es lento, sube a 15s.
|
||||
static const String _baseUrl = 'http://192.168.198.224:8000';
|
||||
static const Duration _timeout = Duration(seconds: 10);
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: obtenerETA
|
||||
//
|
||||
// Llama a GET /api/eta/{usuario_id} y retorna un ETAInfo.
|
||||
// Lanza una Exception si hay error de red o el servidor responde
|
||||
// con error (4xx, 5xx). La UI debe manejar el try/catch.
|
||||
// HELPER PRIVADO: maneja errores HTTP de forma consistente
|
||||
// ----------------------------------------------------------------
|
||||
Future<ETAInfo> obtenerETA(int usuarioId) async {
|
||||
final url = Uri.parse('$_baseUrl/api/eta/$usuarioId');
|
||||
|
||||
Never _throwError(http.Response response) {
|
||||
Map<String, dynamic> body = {};
|
||||
try {
|
||||
// Llamada HTTP GET con timeout para no bloquear la UI para siempre
|
||||
final response = await http.get(url).timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
// Decodifica el body JSON (viene como String, lo convertimos a Map)
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return ETAInfo.fromJson(jsonData);
|
||||
|
||||
} else if (response.statusCode == 404) {
|
||||
// El usuario no existe en la DB — pide que corran el seed
|
||||
throw Exception('Usuario no encontrado. ¿Corriste /api/seed en el backend?');
|
||||
|
||||
} else {
|
||||
// Error genérico del servidor
|
||||
throw Exception('Error del servidor: ${response.statusCode} - ${response.body}');
|
||||
}
|
||||
|
||||
} on Exception {
|
||||
// Re-lanzamos para que la UI lo maneje con un mensaje amigable
|
||||
rethrow;
|
||||
}
|
||||
body = json.decode(response.body);
|
||||
} catch (_) {}
|
||||
final detail = body['detail'] ?? response.body;
|
||||
throw Exception(detail);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: obtenerColonias
|
||||
//
|
||||
// Llama a GET /api/colonias para poblar el Dropdown del LoginScreen.
|
||||
// Retorna una lista de strings con los nombres de las colonias.
|
||||
// ----------------------------------------------------------------
|
||||
Future<List<String>> obtenerColonias() async {
|
||||
final url = Uri.parse('$_baseUrl/api/colonias');
|
||||
|
||||
final response = await http.get(url).timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
// El backend devuelve: { "colonias": ["Zona Centro", "Col. Hidalgo", ...] }
|
||||
return List<String>.from(jsonData['colonias']);
|
||||
} else {
|
||||
throw Exception('No se pudieron cargar las colonias.');
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: loginConCorreo
|
||||
//
|
||||
// Llama a POST /api/usuarios/login con email y obtiene el usuario_id
|
||||
// ----------------------------------------------------------------
|
||||
Future<int> loginConCorreo(String email) async {
|
||||
final url = Uri.parse('$_baseUrl/api/usuarios/login');
|
||||
// ================================================================
|
||||
// AUTENTICACIÓN
|
||||
// ================================================================
|
||||
|
||||
/// Login con email y contraseña. Retorna [usuarioId, nombre].
|
||||
Future<Map<String, dynamic>> loginConCorreo(String email, String password) async {
|
||||
final response = await http.post(
|
||||
url,
|
||||
Uri.parse('$_baseUrl/api/usuarios/login'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: json.encode({'email': email.trim().toLowerCase()}),
|
||||
body: json.encode({'email': email.trim().toLowerCase(), 'password': password}),
|
||||
).timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return jsonData['usuario_id'];
|
||||
} else {
|
||||
throw Exception('Error al iniciar sesión: ${response.body}');
|
||||
final data = json.decode(response.body);
|
||||
return {'usuario_id': data['usuario_id'], 'nombre': data['nombre']};
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: registrarUsuario
|
||||
//
|
||||
// Llama a POST /api/usuarios/register y crea el usuario con su primera dirección.
|
||||
// ----------------------------------------------------------------
|
||||
Future<int> registrarUsuario(
|
||||
String nombre,
|
||||
String email,
|
||||
String password,
|
||||
String direccion,
|
||||
String colonia,
|
||||
) async {
|
||||
final url = Uri.parse('$_baseUrl/api/usuarios/register');
|
||||
|
||||
final response = await http.post(
|
||||
url,
|
||||
Uri.parse('$_baseUrl/api/usuarios/register'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: json.encode({
|
||||
'nombre': nombre.trim(),
|
||||
'email': email.trim().toLowerCase(),
|
||||
'password': password,
|
||||
'colonia': colonia,
|
||||
'direccion': direccion.trim(),
|
||||
}),
|
||||
).timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return jsonData['usuario_id'];
|
||||
} else {
|
||||
throw Exception('Error al registrar usuario: ${response.body}');
|
||||
return json.decode(response.body)['usuario_id'];
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// USUARIOS
|
||||
// ================================================================
|
||||
|
||||
Future<ETAInfo> obtenerETA(int usuarioId) async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/eta/$usuarioId'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return ETAInfo.fromJson(json.decode(response.body));
|
||||
} else if (response.statusCode == 404) {
|
||||
throw Exception('Usuario no encontrado. ¿Corriste /api/seed en el backend?');
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
Future<List<String>> obtenerColonias() async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/colonias'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return List<String>.from(json.decode(response.body)['colonias']);
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: obtenerUsuario
|
||||
//
|
||||
// Llama a GET /api/usuarios/{usuario_id} y retorna los datos de perfil.
|
||||
// ----------------------------------------------------------------
|
||||
Future<UsuarioInfo> obtenerUsuario(int usuarioId) async {
|
||||
final url = Uri.parse('$_baseUrl/api/usuarios/$usuarioId');
|
||||
|
||||
final response = await http.get(url).timeout(_timeout);
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return UsuarioInfo.fromJson(jsonData);
|
||||
} else {
|
||||
throw Exception('Error al obtener usuario: ${response.body}');
|
||||
}
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: obtenerRutas
|
||||
//
|
||||
// Llama a GET /api/rutas para listar el estado actual de cada camión.
|
||||
// ----------------------------------------------------------------
|
||||
Future<List<RouteInfo>> obtenerRutas() async {
|
||||
final url = Uri.parse('$_baseUrl/api/rutas');
|
||||
final response = await http.get(url).timeout(_timeout);
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/usuarios/$usuarioId'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return List<Map<String, dynamic>>.from(jsonData['rutas'])
|
||||
.map(RouteInfo.fromJson)
|
||||
.toList();
|
||||
return UsuarioInfo.fromJson(json.decode(response.body));
|
||||
}
|
||||
|
||||
throw Exception('Error al obtener rutas: ${response.body}');
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: avanzarRuta
|
||||
//
|
||||
// Llama a POST /api/rutas/{route_id}/avanzar para simular el avance del camión.
|
||||
// ----------------------------------------------------------------
|
||||
Future<RouteInfo> avanzarRuta(String routeId) async {
|
||||
final url = Uri.parse('$_baseUrl/api/rutas/$routeId/avanzar');
|
||||
final response = await http.post(url).timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
final Map<String, dynamic> jsonData = json.decode(response.body);
|
||||
return RouteInfo.fromJson(jsonData);
|
||||
}
|
||||
|
||||
throw Exception('Error al avanzar la ruta: ${response.body}');
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: agregarDireccion
|
||||
//
|
||||
// Llama a POST /api/usuarios/{usuario_id}/direcciones para guardar
|
||||
// una nueva dirección asociada al usuario.
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> agregarDireccion(
|
||||
int usuarioId,
|
||||
String colonia,
|
||||
String direccion,
|
||||
) async {
|
||||
final url = Uri.parse('$_baseUrl/api/usuarios/$usuarioId/direcciones');
|
||||
|
||||
Future<void> agregarDireccion(int usuarioId, String colonia, String direccion) async {
|
||||
final response = await http.post(
|
||||
url,
|
||||
Uri.parse('$_baseUrl/api/usuarios/$usuarioId/direcciones'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: json.encode({'colonia': colonia, 'direccion': direccion.trim()}),
|
||||
).timeout(_timeout);
|
||||
|
||||
if (response.statusCode != 200) _throwError(response);
|
||||
}
|
||||
|
||||
/// Actualiza contraseña. Requiere la contraseña actual como confirmación.
|
||||
Future<void> actualizarPassword(int usuarioId, String passwordActual, String passwordNuevo) async {
|
||||
final response = await http.put(
|
||||
Uri.parse('$_baseUrl/api/usuarios/$usuarioId/password'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: json.encode({
|
||||
'colonia': colonia,
|
||||
'direccion': direccion.trim(),
|
||||
'password_actual': passwordActual,
|
||||
'password_nuevo': passwordNuevo,
|
||||
}),
|
||||
).timeout(_timeout);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
throw Exception('Error al guardar la dirección: ${response.body}');
|
||||
}
|
||||
if (response.statusCode != 200) _throwError(response);
|
||||
}
|
||||
|
||||
// ----------------------------------------------------------------
|
||||
// MÉTODO: registrarFcmToken
|
||||
//
|
||||
// Envía el FCM token del dispositivo al backend para que pueda
|
||||
// enviar notificaciones push personalizadas.
|
||||
//
|
||||
// CUÁNDO LLAMARLO:
|
||||
// - En HomeScreen al iniciar, después de obtener el token de
|
||||
// FirebaseMessaging.instance.getToken()
|
||||
// ----------------------------------------------------------------
|
||||
Future<void> registrarFcmToken(int usuarioId, String fcmToken) async {
|
||||
final url = Uri.parse('$_baseUrl/api/usuarios/$usuarioId/fcm-token');
|
||||
|
||||
final response = await http.put(
|
||||
url,
|
||||
Uri.parse('$_baseUrl/api/usuarios/$usuarioId/fcm-token'),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
body: json.encode({'fcm_token': fcmToken}),
|
||||
).timeout(_timeout);
|
||||
|
||||
if (response.statusCode != 200) {
|
||||
// No es crítico que falle en el hackathon, solo logueamos
|
||||
throw Exception('Error registrando FCM token: ${response.statusCode}');
|
||||
}
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// RUTAS
|
||||
// ================================================================
|
||||
|
||||
Future<List<RouteInfo>> obtenerRutas(int usuarioId) async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/rutas?usuario_id=$usuarioId'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return List<Map<String, dynamic>>.from(json.decode(response.body)['rutas'])
|
||||
.map(RouteInfo.fromJson)
|
||||
.toList();
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
Future<RouteInfo> avanzarRuta(String routeId, int usuarioId) async {
|
||||
final response = await http
|
||||
.post(Uri.parse('$_baseUrl/api/rutas/$routeId/avanzar?usuario_id=$usuarioId'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return RouteInfo.fromJson(json.decode(response.body));
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
// ================================================================
|
||||
// VISUALIZACIÓN — NUEVOS EN v2
|
||||
// ================================================================
|
||||
|
||||
/// Dashboard global: estado de todas las rutas + métricas de usuarios.
|
||||
Future<DashboardInfo> obtenerDashboard() async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/dashboard'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return DashboardInfo.fromJson(json.decode(response.body));
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
/// Historial de posiciones GPS de una ruta, con la posición actual marcada.
|
||||
Future<List<PosicionGPS>> historialPosiciones(String routeId) async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/rutas/$routeId/posiciones'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return List<Map<String, dynamic>>.from(json.decode(response.body))
|
||||
.map(PosicionGPS.fromJson)
|
||||
.toList();
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
/// Vista rápida y ligera de todas las rutas. Ideal para polling frecuente.
|
||||
Future<List<Map<String, dynamic>>> resumenRutas() async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/rutas/resumen'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return List<Map<String, dynamic>>.from(json.decode(response.body)['rutas']);
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
|
||||
/// Estadísticas por colonia: usuarios y cobertura de notificaciones.
|
||||
Future<List<ColoniaEstadistica>> estadisticasColonias() async {
|
||||
final response = await http
|
||||
.get(Uri.parse('$_baseUrl/api/estadisticas/colonias'))
|
||||
.timeout(_timeout);
|
||||
|
||||
if (response.statusCode == 200) {
|
||||
return List<Map<String, dynamic>>.from(json.decode(response.body))
|
||||
.map(ColoniaEstadistica.fromJson)
|
||||
.toList();
|
||||
}
|
||||
_throwError(response);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user