Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.github.com>
Co-authored-by: MENDOZA BALLARDO GAEL RICARDO <gael-meb123@users.noreply.github.com>

vistas
This commit is contained in:
shinra32
2026-05-23 00:45:34 -06:00
parent c58fa571aa
commit 3a3178eb3b
15 changed files with 527 additions and 4237 deletions

View File

@@ -14,14 +14,9 @@ import 'package:recolecta_app/features/home/citizen_shell.dart';
import 'package:recolecta_app/features/separation_guide/screens/category_detail_screen.dart';
import 'package:recolecta_app/features/separation_guide/screens/separation_guide_screen.dart';
import 'package:recolecta_app/core/services/auth_controller.dart';
// Mock Admin Screens
class AdminDashboardScreen extends StatelessWidget {
const AdminDashboardScreen({super.key});
@override
Widget build(BuildContext context) =>
const Scaffold(body: Center(child: Text('Admin Dashboard')));
}
import '../../features/admin/screens/admin_dashboard_screen.dart';
import '../../features/notifications/notifications_screen.dart';
import '../../features/quiz/quiz_screen.dart';
class AdminRouteDetailScreen extends StatelessWidget {
const AdminRouteDetailScreen({super.key, required this.routeId});
@@ -142,6 +137,11 @@ final routerProvider = Provider<GoRouter>((ref) {
),
],
),
GoRoute(
path: '/notifications',
builder: (context, state) => const NotificationsScreen(),
),
GoRoute(path: '/quiz', builder: (context, state) => const QuizScreen()),
],
);
});

View File

@@ -1,3 +1,4 @@
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../models/auth_state.dart';
@@ -14,28 +15,28 @@ class AuthController extends AsyncNotifier<AuthState> {
if (session == null) {
return const AuthState.unauthenticated();
}
return AuthState.authenticated(
final authState = AuthState.authenticated(
token: session.token,
userRole: session.userRole,
routeId: session.routeId,
);
_subscribeIfCitizen(authState);
return authState;
}
Future<void> login({required String email, required String password}) async {
state = const AsyncLoading<AuthState>();
try {
final session = await ref
.read(authServiceProvider)
.login(email: email, password: password);
state = AsyncData(
AuthState.authenticated(
token: session.token,
userRole: session.userRole,
routeId: session.routeId,
),
final authState = AuthState.authenticated(
token: session.token,
userRole: session.userRole,
routeId: session.routeId,
);
_subscribeIfCitizen(authState);
state = AsyncData(authState);
} catch (error, stackTrace) {
state = AsyncError<AuthState>(error, stackTrace);
rethrow;
@@ -48,18 +49,17 @@ class AuthController extends AsyncNotifier<AuthState> {
required String password,
}) async {
state = const AsyncLoading<AuthState>();
try {
final session = await ref
.read(authServiceProvider)
.register(email: email, phone: phone, password: password);
state = AsyncData(
AuthState.authenticated(
token: session.token,
userRole: session.userRole,
routeId: session.routeId,
),
final authState = AuthState.authenticated(
token: session.token,
userRole: session.userRole,
routeId: session.routeId,
);
_subscribeIfCitizen(authState);
state = AsyncData(authState);
} catch (error, stackTrace) {
state = AsyncError<AuthState>(error, stackTrace);
rethrow;
@@ -67,7 +67,17 @@ class AuthController extends AsyncNotifier<AuthState> {
}
Future<void> logout() async {
final previousRouteId = state.value?.routeId;
await ref.read(authServiceProvider).logout();
if (previousRouteId != null) {
FirebaseMessaging.instance.unsubscribeFromTopic('topic_$previousRouteId');
}
state = const AsyncData(AuthState.unauthenticated());
}
void _subscribeIfCitizen(AuthState authState) {
if (authState.userRole == 'citizen' && authState.routeId != null) {
FirebaseMessaging.instance.subscribeToTopic('topic_${authState.routeId}');
}
}
}

View File

@@ -0,0 +1,307 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:latlong2/latlong.dart';
import '../../../../core/constants/auth_constants.dart';
import '../../../../core/theme/app_theme.dart';
const _kRelleno = LatLng(20.5111, -100.9037);
const _kRouteColors = [
Colors.blue,
Colors.green,
Colors.orange,
Colors.red,
Colors.purple,
Colors.teal,
];
class _RouteData {
const _RouteData({
required this.routeId,
required this.currentPositionId,
required this.status,
required this.positions,
});
final String routeId;
final int currentPositionId;
final String status;
final List<LatLng> positions;
}
class AdminDashboardScreen extends StatefulWidget {
const AdminDashboardScreen({super.key});
@override
State<AdminDashboardScreen> createState() => _AdminDashboardScreenState();
}
class _AdminDashboardScreenState extends State<AdminDashboardScreen> {
List<_RouteData> _routes = [];
bool _isLoading = true;
String? _error;
@override
void initState() {
super.initState();
_loadRoutes();
}
Future<void> _loadRoutes() async {
setState(() {
_isLoading = true;
_error = null;
});
try {
const storage = FlutterSecureStorage();
final token = await storage.read(key: authTokenStorageKey) ?? '';
final dio = Dio(
BaseOptions(
baseUrl: const String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://10.0.2.2:8000',
),
headers: {
'Authorization': 'Bearer $token',
'Content-Type': 'application/json',
},
),
);
final routesRes = await dio.get<List<dynamic>>('/routes');
final routeList = routesRes.data ?? [];
final List<_RouteData> loaded = [];
for (final r in routeList) {
final routeId = (r['route_id'] ?? r['id'] ?? '').toString();
if (routeId.isEmpty) continue;
List<LatLng> positions = [];
try {
final posRes = await dio.get<List<dynamic>>('/routes/$routeId/positions');
positions = (posRes.data ?? [])
.map<LatLng>((p) => LatLng(
(p['lat'] as num).toDouble(),
(p['lng'] as num).toDouble(),
))
.toList();
} catch (_) {}
loaded.add(_RouteData(
routeId: routeId,
currentPositionId: (r['current_position_id'] as int?) ?? 1,
status: (r['status'] ?? 'pendiente').toString(),
positions: positions,
));
}
if (mounted) {
setState(() {
_routes = loaded;
_isLoading = false;
});
}
} catch (e) {
if (mounted) {
setState(() {
_error = e.toString();
_isLoading = false;
});
}
}
}
Marker _buildTruckMarker(_RouteData route, Color color) {
final posIdx = (route.currentPositionId - 1).clamp(0, route.positions.length - 1);
return Marker(
point: route.positions[posIdx],
width: 48,
height: 48,
child: Tooltip(
message: '${route.routeId} · pos ${route.currentPositionId} · ${route.status}',
child: Container(
decoration: BoxDecoration(
color: color,
shape: BoxShape.circle,
border: Border.all(color: Colors.white, width: 2),
),
child: const Icon(Icons.local_shipping, color: Colors.white, size: 22),
),
),
);
}
@override
Widget build(BuildContext context) {
final routesWithPos = _routes.where((r) => r.positions.isNotEmpty).toList();
return Scaffold(
appBar: AppBar(
title: const Text('Panel de Control - Flotilla'),
backgroundColor: AppTheme.primaryDark,
foregroundColor: Colors.white,
elevation: 0,
actions: [
IconButton(
icon: const Icon(Icons.refresh),
onPressed: _loadRoutes,
tooltip: 'Actualizar',
),
],
),
body: Column(
children: [
Container(
width: double.infinity,
color: AppTheme.amberLight,
padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12),
child: const Row(
children: [
Icon(Icons.security, color: AppTheme.amber, size: 20),
SizedBox(width: 10),
Expanded(
child: Text(
'Privilegio Admin: Vista global de coordenadas. No compartir pantalla.',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppTheme.amber,
),
),
),
],
),
),
Expanded(
child: Stack(
children: [
FlutterMap(
options: const MapOptions(
initialCenter: _kRelleno,
initialZoom: 12.5,
interactionOptions: InteractionOptions(
flags: InteractiveFlag.all,
),
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.onlineshack.recolecta',
),
if (routesWithPos.isNotEmpty) ...[
PolylineLayer(
polylines: [
for (int i = 0; i < routesWithPos.length; i++)
if (routesWithPos[i].positions.length > 1)
Polyline(
points: routesWithPos[i].positions,
color: _kRouteColors[i % _kRouteColors.length]
.withValues(alpha: 0.7),
strokeWidth: 3.5,
),
],
),
MarkerLayer(
markers: [
for (int i = 0; i < routesWithPos.length; i++)
_buildTruckMarker(
routesWithPos[i],
_kRouteColors[i % _kRouteColors.length],
),
],
),
],
],
),
if (_isLoading)
const Center(child: CircularProgressIndicator()),
if (_error != null && !_isLoading)
Positioned(
bottom: 16,
left: 16,
right: 16,
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppTheme.danger.withValues(alpha: 0.9),
borderRadius: BorderRadius.circular(8),
),
child: Text(
'Sin conexión al backend: $_error',
style: const TextStyle(
color: Colors.white,
fontSize: 12,
),
),
),
),
if (routesWithPos.isNotEmpty)
Positioned(
top: 12,
right: 12,
child: _RouteLegend(routes: routesWithPos),
),
],
),
),
],
),
);
}
}
class _RouteLegend extends StatelessWidget {
const _RouteLegend({required this.routes});
final List<_RouteData> routes;
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 8),
decoration: BoxDecoration(
color: Colors.white.withValues(alpha: 0.93),
borderRadius: BorderRadius.circular(8),
boxShadow: const [BoxShadow(color: Colors.black12, blurRadius: 4)],
),
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
for (int i = 0; i < routes.length; i++)
Padding(
padding: const EdgeInsets.symmetric(vertical: 2),
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
width: 10,
height: 10,
decoration: BoxDecoration(
color: _kRouteColors[i % _kRouteColors.length],
shape: BoxShape.circle,
),
),
const SizedBox(width: 6),
Text(
'${routes[i].routeId} · pos ${routes[i].currentPositionId}',
style: const TextStyle(
fontSize: 10,
color: AppTheme.textPrimary,
),
),
],
),
),
],
),
);
}
}

View File

@@ -1,4 +1,5 @@
import 'package:flutter/material.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:dio/dio.dart';
@@ -43,6 +44,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
bool _obscurePass = true;
// Paso 2
final _mapController = MapController();
final _cpCtrl = TextEditingController();
final _calleCtrl = TextEditingController();
Colonia? _selectedColonia;
@@ -92,6 +94,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
_passCtrl.dispose();
_calleCtrl.dispose();
_cpCtrl.dispose();
_mapController.dispose();
super.dispose();
}
@@ -119,7 +122,9 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
'format': 'json',
'addressdetails': 1,
},
options: Options(headers: {'User-Agent': 'com.onlineshack.recolecta'}),
options: kIsWeb
? null
: Options(headers: {'User-Agent': 'com.onlineshack.recolecta'}),
);
if (response.data != null && response.data['address'] != null) {
@@ -194,32 +199,11 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
FocusScope.of(context).unfocus(); // Cierra el teclado
}
Future<void> _register() async {
if (_calleCtrl.text.trim().isEmpty || _selectedColonia == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ingresa tu calle y selecciona una colonia'),
behavior: SnackBarBehavior.floating,
),
);
return;
}
// 1. Registra al usuario
await ref
.read(authControllerProvider.notifier)
.register(
email: _emailCtrl.text.trim(),
phone: _telefonoCtrl.text.trim(),
password: _passCtrl.text,
);
// Detenernos si hubo algún error en el auth (ej. contraseña corta)
if (ref.read(authControllerProvider).hasError) return;
// 2. Guardar la dirección en el backend de forma silenciosa
Future<void> _postAddressInBackground(String calle, String colonia) async {
try {
const storage = FlutterSecureStorage();
// Esperar un momento para asegurar que el token se haya guardado
await Future.delayed(const Duration(milliseconds: 500));
final token = await storage.read(key: 'token') ?? '';
if (token.isNotEmpty) {
@@ -235,33 +219,51 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
await dio.post(
'/addresses',
data: {
'label': 'Mi Casa',
'calle': _calleCtrl.text.trim(),
'colonia': _selectedColonia!.nombre,
},
data: {'label': 'Mi Casa', 'calle': calle, 'colonia': colonia},
);
}
} catch (e) {
debugPrint('Aviso: No se pudo guardar la dirección inicial: $e');
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Error al guardar tu dirección. Inténtalo más tarde.',
),
backgroundColor: AppTheme.danger,
),
);
}
return; // No navegar si falla el guardado de la dirección
}
}
Future<void> _register() async {
if (_calleCtrl.text.trim().isEmpty || _selectedColonia == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Ingresa tu calle y selecciona una colonia'),
behavior: SnackBarBehavior.floating,
),
);
return;
}
// 3. Navegar a inicio de manera limpia
// Capturar variables antes del proceso asíncrono
final calle = _calleCtrl.text.trim();
final colonia = _selectedColonia!.nombre;
// 1. Registra al usuario
await ref
.read(authControllerProvider.notifier)
.register(
email: _emailCtrl.text.trim(),
phone: _telefonoCtrl.text.trim(),
password: _passCtrl.text,
);
// Si el widget ya no está montado, GoRouter nos redirigió automáticamente al Home por éxito.
if (!mounted) {
_postAddressInBackground(calle, colonia);
return;
}
// Si seguimos aquí, verificar si hubo un error (ej. contraseña corta)
if (ref.read(authControllerProvider).hasError) return;
// Fallback: guardar dirección y navegar manualmente
await _postAddressInBackground(calle, colonia);
if (mounted) {
context.go(
'/home',
); // ¡Solución al GoException! Navega a la ruta correcta
context.go('/home');
}
}
@@ -300,6 +302,7 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
onNext: _nextPage,
),
_Step2(
mapController: _mapController,
cpCtrl: _cpCtrl,
calleCtrl: _calleCtrl,
selectedColonia: _selectedColonia,
@@ -480,6 +483,7 @@ class _Step1 extends StatelessWidget {
// ── Paso 2: Dirección ─────────────────────────────────────────────────────────
class _Step2 extends StatelessWidget {
final MapController mapController;
final TextEditingController cpCtrl;
final TextEditingController calleCtrl;
final Colonia? selectedColonia;
@@ -494,6 +498,7 @@ class _Step2 extends StatelessWidget {
final VoidCallback onRegister;
const _Step2({
required this.mapController,
required this.cpCtrl,
required this.calleCtrl,
required this.selectedColonia,
@@ -510,13 +515,19 @@ class _Step2 extends StatelessWidget {
@override
Widget build(BuildContext context) {
final mapCenter = selectedLocation ?? const LatLng(20.5222, -100.8123);
// Usamos el centro original de la colonia para los límites estáticos
final baseCenter = selectedColonia != null
? kColoniasCoordinates[selectedColonia!.nombre] ??
const LatLng(20.5222, -100.8123)
: const LatLng(20.5222, -100.8123);
// Magia de privacidad: Restringir paneo a 1km a la redonda de la colonia
final mapCenter = selectedLocation ?? baseCenter;
// Magia de privacidad: Restringir paneo a 1km a la redonda usando el centro original
final bounds = selectedColonia != null
? LatLngBounds(
LatLng(mapCenter.latitude - 0.01, mapCenter.longitude - 0.01),
LatLng(mapCenter.latitude + 0.01, mapCenter.longitude + 0.01),
LatLng(baseCenter.latitude - 0.01, baseCenter.longitude - 0.01),
LatLng(baseCenter.latitude + 0.01, baseCenter.longitude + 0.01),
)
: null;
@@ -542,25 +553,31 @@ class _Step2 extends StatelessWidget {
Row(
children: [
Expanded(
child: RadioListTile<String>(
title: const Text(
'Casa',
style: TextStyle(fontSize: 14),
child: Material(
color: Colors.transparent,
child: RadioListTile<String>(
title: const Text(
'Casa',
style: TextStyle(fontSize: 14),
),
value: 'Casa',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
value: 'Casa',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
),
Expanded(
child: RadioListTile<String>(
title: const Text(
'Negocio',
style: TextStyle(fontSize: 14),
child: Material(
color: Colors.transparent,
child: RadioListTile<String>(
title: const Text(
'Negocio',
style: TextStyle(fontSize: 14),
),
value: 'Negocio',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
value: 'Negocio',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
),
],
@@ -647,12 +664,12 @@ class _Step2 extends StatelessWidget {
),
clipBehavior: Clip.hardEdge,
child: FlutterMap(
key: ValueKey(selectedColonia?.nombre ?? 'default'),
mapController: mapController,
options: MapOptions(
initialCenter: mapCenter,
initialZoom: 15.0,
cameraConstraint: bounds != null
? CameraConstraint.contain(bounds: bounds)
? CameraConstraint.containCenter(bounds: bounds)
: const CameraConstraint.unconstrained(),
onTap: (_, latlng) => onLocationChanged(latlng),
),
@@ -746,15 +763,21 @@ class _Step2 extends StatelessWidget {
title: 'Notificaciones Externas',
child: Column(
children: [
CheckboxListTile(
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
activeColor: AppTheme.primary,
value: whatsappNotif,
onChanged: onWhatsappChanged,
title: const Text(
'Recibir alertas del camión vía WhatsApp (Próximamente)',
style: TextStyle(fontSize: 14, color: AppTheme.textPrimary),
Material(
color: Colors.transparent,
child: CheckboxListTile(
contentPadding: EdgeInsets.zero,
controlAffinity: ListTileControlAffinity.leading,
activeColor: AppTheme.primary,
value: whatsappNotif,
onChanged: onWhatsappChanged,
title: const Text(
'Recibir alertas del camión vía WhatsApp (Próximamente)',
style: TextStyle(
fontSize: 14,
color: AppTheme.textPrimary,
),
),
),
),
],

View File

@@ -0,0 +1,20 @@
import 'package:flutter/material.dart';
import '../../core/theme/app_theme.dart';
class NotificationsScreen extends StatelessWidget {
const NotificationsScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppTheme.background,
appBar: AppBar(title: const Text('Avisos y Alertas')),
body: const Center(
child: Text(
'Bandeja de entrada de FCM',
style: TextStyle(color: AppTheme.textSecondary),
),
),
);
}
}

View File

@@ -0,0 +1,21 @@
// Vista de Educación y Quiz
import 'package:flutter/material.dart';
import '../../core/theme/app_theme.dart';
class QuizScreen extends StatelessWidget {
const QuizScreen({super.key});
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppTheme.background,
appBar: AppBar(title: const Text('Educación y Quiz')),
body: const Center(
child: Text(
'Chat IA / Guía de separación offline',
style: TextStyle(color: AppTheme.textSecondary),
),
),
);
}
}

View File

@@ -1,11 +1,36 @@
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'app/app.dart';
import 'firebase_options.dart';
@pragma('vm:entry-point')
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
} catch (_) {}
debugPrint('FCM background: ${message.messageId} | data: ${message.data}');
}
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await dotenv.load(fileName: '.env');
try {
await dotenv.load(fileName: 'assets/.env');
} catch (_) {
// .env no disponible — api_client.dart usa los valores por defecto
}
try {
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
} on UnsupportedError {
await Firebase.initializeApp();
}
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
runApp(const ProviderScope(child: RecolectaApp()));
}