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

Co-authored-by: Azareth-Tr <Azareth-Tr@users.noreply.github.com>
Co-authored-by: eddgranados12 <eddgranados12@users.noreply.github.com>

vistas de mockup actualizaco
This commit is contained in:
shinra32
2026-05-22 23:50:10 -06:00
parent c91b6e2091
commit fd7b0c132c
44 changed files with 4108 additions and 140 deletions

View File

@@ -10,9 +10,19 @@ import '../../core/theme/app_theme.dart';
import '../../core/widgets/app_widgets.dart';
import '../../core/services/auth_controller.dart';
import '../../core/models/auth_state.dart';
import '../addresses/colonias_selector.dart';
import '../../core/models/colonia.dart';
import '../home/colonias_data.dart';
import '../addresses/colonias_provider.dart';
const Map<String, String> _cpToColonia = {
'38000': 'Zona Centro',
'38060': 'Las Arboledas',
'38027': 'San Juanico',
'38037': 'Los Olivos',
'38090': 'Rancho Seco',
'38080': 'Las Insurgentes',
'38086': 'Trojes',
};
class RegisterPage extends ConsumerStatefulWidget {
const RegisterPage({super.key});
@@ -37,7 +47,8 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
final _calleCtrl = TextEditingController();
Colonia? _selectedColonia;
LatLng? _selectedLocation;
int _radioAlerta = 200;
String _tipoInmueble = 'Casa';
bool _whatsappNotif = false;
@override
void initState() {
@@ -94,6 +105,95 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
setState(() => _currentPage = 1);
}
// Llama a la API de OpenStreetMap (Nominatim) para obtener la calle automáticamente
Future<void> _fetchStreetName(LatLng latlng) async {
setState(() => _selectedLocation = latlng);
try {
final dio = Dio();
final response = await dio.get(
'https://nominatim.openstreetmap.org/reverse',
queryParameters: {
'lat': latlng.latitude,
'lon': latlng.longitude,
'format': 'json',
'addressdetails': 1,
},
options: Options(headers: {'User-Agent': 'com.onlineshack.recolecta'}),
);
if (response.data != null && response.data['address'] != null) {
final address = response.data['address'];
final road =
address['road'] ?? address['pedestrian'] ?? address['street'] ?? '';
final houseNumber = address['house_number'] ?? '';
if (road.isNotEmpty) {
setState(() {
_calleCtrl.text = '$road $houseNumber'.trim();
});
}
}
} catch (e) {
debugPrint('Aviso: Error al obtener nombre de la calle de OSM: $e');
}
}
void _validarCP(String cp, List<Colonia> colonias) {
if (cp.length != 5) {
if (_selectedColonia != null) {
setState(() {
_selectedColonia = null;
_selectedLocation = null;
_calleCtrl.clear();
});
}
return;
}
final nombre = _cpToColonia[cp];
if (nombre == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text(
'Código postal fuera de nuestra zona de servicio actual.',
),
backgroundColor: AppTheme.danger,
behavior: SnackBarBehavior.floating,
),
);
setState(() {
_selectedColonia = null;
_selectedLocation = null;
});
return;
}
final backendC = colonias
.where((c) => c.nombre.toLowerCase() == nombre.toLowerCase())
.firstOrNull;
if (backendC == null) {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Esta colonia aún no tiene horarios configurados.'),
backgroundColor: AppTheme.danger,
behavior: SnackBarBehavior.floating,
),
);
setState(() {
_selectedColonia = null;
_selectedLocation = null;
});
return;
}
setState(() {
_selectedColonia = backendC;
_selectedLocation = kColoniasCoordinates[nombre];
});
FocusScope.of(context).unfocus(); // Cierra el teclado
}
Future<void> _register() async {
if (_calleCtrl.text.trim().isEmpty || _selectedColonia == null) {
ScaffoldMessenger.of(context).showSnackBar(
@@ -168,6 +268,8 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
@override
Widget build(BuildContext context) {
final loading = ref.watch(authControllerProvider).isLoading;
final coloniasAsync = ref.watch(coloniasProvider);
final coloniasList = coloniasAsync.value ?? [];
return Scaffold(
backgroundColor: AppTheme.background,
@@ -202,18 +304,14 @@ class _RegisterPageState extends ConsumerState<RegisterPage> {
calleCtrl: _calleCtrl,
selectedColonia: _selectedColonia,
selectedLocation: _selectedLocation,
radioAlerta: _radioAlerta,
tipoInmueble: _tipoInmueble,
whatsappNotif: _whatsappNotif,
loading: loading,
onColoniaChanged: (c) {
setState(() {
_selectedColonia = c;
if (c != null && kColoniasCoordinates.containsKey(c.nombre)) {
_selectedLocation = kColoniasCoordinates[c.nombre];
}
});
},
onLocationChanged: (l) => setState(() => _selectedLocation = l),
onRadioChanged: (v) => setState(() => _radioAlerta = v),
onTipoChanged: (v) => setState(() => _tipoInmueble = v),
onCPChanged: (v) => _validarCP(v, coloniasList),
onLocationChanged: _fetchStreetName,
onWhatsappChanged: (v) =>
setState(() => _whatsappNotif = v ?? false),
onRegister: _register,
),
],
@@ -386,11 +484,13 @@ class _Step2 extends StatelessWidget {
final TextEditingController calleCtrl;
final Colonia? selectedColonia;
final LatLng? selectedLocation;
final int radioAlerta;
final String tipoInmueble;
final bool whatsappNotif;
final bool loading;
final ValueChanged<Colonia?> onColoniaChanged;
final ValueChanged<String> onTipoChanged;
final ValueChanged<String> onCPChanged;
final ValueChanged<LatLng> onLocationChanged;
final ValueChanged<int> onRadioChanged;
final ValueChanged<bool?> onWhatsappChanged;
final VoidCallback onRegister;
const _Step2({
@@ -398,17 +498,28 @@ class _Step2 extends StatelessWidget {
required this.calleCtrl,
required this.selectedColonia,
required this.selectedLocation,
required this.radioAlerta,
required this.tipoInmueble,
required this.whatsappNotif,
required this.loading,
required this.onColoniaChanged,
required this.onTipoChanged,
required this.onCPChanged,
required this.onLocationChanged,
required this.onRadioChanged,
required this.onWhatsappChanged,
required this.onRegister,
});
@override
Widget build(BuildContext context) {
final mapCenter = selectedLocation ?? const LatLng(20.5222, -100.8123);
// Magia de privacidad: Restringir paneo a 1km a la redonda de la colonia
final bounds = selectedColonia != null
? LatLngBounds(
LatLng(mapCenter.latitude - 0.01, mapCenter.longitude - 0.01),
LatLng(mapCenter.latitude + 0.01, mapCenter.longitude + 0.01),
)
: null;
return SingleChildScrollView(
padding: const EdgeInsets.all(24),
child: Column(
@@ -420,84 +531,183 @@ class _Step2 extends StatelessWidget {
title: 'Dirección de tu casa',
child: Column(
children: [
AppFormField(
label: 'Código Postal',
hint: 'Ej. 38000',
controller: cpCtrl,
keyboardType: TextInputType.number,
),
const SizedBox(height: 14),
ColoniasSelector(
labelText: 'Colonia',
initialValue: selectedColonia,
onChanged: onColoniaChanged,
),
const SizedBox(height: 14),
AppFormField(
label: 'Calle y número',
hint: 'Av. Insurgentes 245',
controller: calleCtrl,
),
const SizedBox(height: 16),
const Text(
'Toca el mapa para ubicar tu casa exacta:',
'Tipo de inmueble',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: AppTheme.textSecondary,
),
),
const SizedBox(height: 8),
Container(
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppTheme.radiusSm),
border: Border.all(color: AppTheme.border),
),
clipBehavior: Clip.hardEdge,
child: FlutterMap(
key: ValueKey(selectedColonia?.nombre ?? 'default'),
options: MapOptions(
initialCenter: mapCenter,
initialZoom: 15.0,
onTap: (_, latlng) => onLocationChanged(latlng),
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.onlineshack.recolecta',
Row(
children: [
Expanded(
child: RadioListTile<String>(
title: const Text(
'Casa',
style: TextStyle(fontSize: 14),
),
value: 'Casa',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
if (selectedLocation != null)
MarkerLayer(
markers: [
Marker(
point: selectedLocation!,
width: 40,
height: 40,
child: const Icon(
Icons.location_on,
color: AppTheme.danger,
size: 40,
),
Expanded(
child: RadioListTile<String>(
title: const Text(
'Negocio',
style: TextStyle(fontSize: 14),
),
value: 'Negocio',
groupValue: tipoInmueble,
onChanged: (v) => onTipoChanged(v!),
),
),
],
),
const SizedBox(height: 8),
AppFormField(
label: 'Código Postal',
hint: 'Ej. 38000',
controller: cpCtrl,
keyboardType: TextInputType.number,
onChanged: onCPChanged,
),
if (selectedColonia != null) ...[
const SizedBox(height: 14),
Container(
padding: const EdgeInsets.all(14),
decoration: BoxDecoration(
color: AppTheme.primaryLight.withValues(alpha: 0.5),
borderRadius: BorderRadius.circular(AppTheme.radiusSm),
border: Border.all(color: AppTheme.primaryMid),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(
Icons.check_circle_outline,
color: AppTheme.primary,
size: 18,
),
const SizedBox(width: 8),
Text(
'Colonia: ${selectedColonia!.nombre}',
style: const TextStyle(
fontWeight: FontWeight.w600,
color: AppTheme.primaryDark,
),
),
],
),
],
const SizedBox(height: 8),
Text(
'Horario ${selectedColonia!.turno?.toLowerCase() ?? 'asignado'}',
style: const TextStyle(
fontSize: 13,
color: AppTheme.textPrimary,
),
),
Text(
selectedColonia!.horarioEstimado ??
'Sin horario especificado',
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.bold,
color: AppTheme.textPrimary,
),
),
],
),
),
),
const SizedBox(height: 14),
AppFormField(
label: 'Calle y número',
hint: 'Av. Insurgentes 245',
controller: calleCtrl,
),
const SizedBox(height: 16),
const Text(
'Toca el mapa para ubicar tu casa exacta:',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w500,
color: AppTheme.textSecondary,
),
),
const SizedBox(height: 8),
Container(
height: 200,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(AppTheme.radiusSm),
border: Border.all(color: AppTheme.border),
),
clipBehavior: Clip.hardEdge,
child: FlutterMap(
key: ValueKey(selectedColonia?.nombre ?? 'default'),
options: MapOptions(
initialCenter: mapCenter,
initialZoom: 15.0,
cameraConstraint: bounds != null
? CameraConstraint.contain(bounds: bounds)
: const CameraConstraint.unconstrained(),
onTap: (_, latlng) => onLocationChanged(latlng),
),
children: [
TileLayer(
urlTemplate:
'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.onlineshack.recolecta',
),
if (selectedLocation != null)
MarkerLayer(
markers: [
Marker(
point: selectedLocation!,
width: 40,
height: 40,
child: const Icon(
Icons.location_on,
color: AppTheme.danger,
size: 40,
),
),
],
),
],
),
),
] else ...[
const SizedBox(height: 24),
const Center(
child: Text(
'Ingresa un código postal con servicio\npara asignar tu colonia.',
textAlign: TextAlign.center,
style: TextStyle(
color: AppTheme.textSecondary,
fontSize: 13,
),
),
),
],
],
),
),
const SizedBox(height: 16),
// ── Sección OCR (Privacidad por diseño) ──
AppFormCard(
icon: Icons.notifications_outlined,
title: 'Distancia de alerta',
icon: Icons.document_scanner_outlined,
title: 'Verificación de Domicilio',
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Te avisamos cuando el camión esté a esta distancia de tu casa.',
'Para prevenir abusos, requerimos validar tu dirección con un recibo (luz o agua). '
'Por privacidad, la imagen será borrada inmediatamente después de la lectura.',
style: TextStyle(
fontSize: 13,
color: AppTheme.textSecondary,
@@ -505,17 +715,46 @@ class _Step2 extends StatelessWidget {
),
),
const SizedBox(height: 14),
...[200, 400, 600].map(
(dist) => _RadioOption(
value: dist,
groupValue: radioAlerta,
label: '$dist metros',
sublabel: dist == 200
? '~2-3 min de anticipación'
: dist == 400
? '~4-5 min de anticipación'
: '~6-8 min de anticipación',
onChanged: onRadioChanged,
SizedBox(
width: double.infinity,
child: OutlinedButton.icon(
icon: const Icon(
Icons.upload_file,
color: AppTheme.primary,
),
label: const Text(
'Escanear recibo (OCR)',
style: TextStyle(color: AppTheme.primary),
),
onPressed: () {
ScaffoldMessenger.of(context).showSnackBar(
const SnackBar(
content: Text('Abriendo cámara... (Próximamente)'),
),
);
},
),
),
],
),
),
const SizedBox(height: 16),
// ── Sección WhatsApp ──
AppFormCard(
icon: Icons.chat_outlined,
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),
),
),
],

View File

@@ -1,15 +1,314 @@
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:latlong2/latlong.dart';
class CitizenHomeScreen extends StatelessWidget {
import '../../core/theme/app_theme.dart';
import '../../core/models/ui_models.dart';
import 'colonias_data.dart';
class CitizenHomeScreen extends StatefulWidget {
const CitizenHomeScreen({super.key});
@override
State<CitizenHomeScreen> createState() => _CitizenHomeScreenState();
}
class _CitizenHomeScreenState extends State<CitizenHomeScreen> {
bool _isLoading = true;
List<UIHouseModel> _casas = [];
Map<String, String> _etas = {};
Map<String, String> _horarios = {};
@override
void initState() {
super.initState();
_loadData();
}
Future<void> _loadData() async {
try {
const storage = FlutterSecureStorage();
final token = await storage.read(key: 'token') ?? '';
if (token.isEmpty) {
if (mounted) setState(() => _isLoading = false);
return;
}
final dio = Dio(
BaseOptions(
baseUrl: const String.fromEnvironment(
'API_BASE_URL',
defaultValue: 'http://localhost:8000',
),
headers: {'Authorization': 'Bearer $token'},
),
);
// 1. Obtener horarios de las colonias
try {
final colRes = await dio.get('/colonias');
if (colRes.data is List) {
for (var c in colRes.data) {
final nombre = c['nombre'] ?? c['colonia'] ?? '';
final horario = c['horario_estimado'] ?? c['schedule'] ?? 'Horario no definido';
if (nombre.isNotEmpty) {
_horarios[nombre] = horario;
}
}
}
} catch (_) {
debugPrint('Aviso: No se pudieron cargar los horarios.');
}
// 2. Obtener los domicilios del ciudadano
final res = await dio.get('/addresses');
List<UIHouseModel> loadedCasas = [];
if (res.data is List) {
loadedCasas = (res.data as List).map((e) => UIHouseModel.fromJson(e)).toList();
}
// 3. Obtener ETA (Tiempo Estimado) para cada domicilio
Map<String, String> loadedEtas = {};
for (var casa in loadedCasas) {
try {
final etaRes = await dio.get('/eta', queryParameters: {'address_id': casa.id});
loadedEtas[casa.id] = etaRes.data['mensaje'] ?? 'Estado desconocido';
} catch (e) {
loadedEtas[casa.id] = 'Calculando...';
}
}
if (mounted) {
setState(() {
_casas = loadedCasas;
_etas = loadedEtas;
_isLoading = false;
});
}
} catch (e) {
debugPrint('Error en CitizenHomeScreen: $e');
if (mounted) {
setState(() => _isLoading = false);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Inicio')),
body: const Center(
child: Text('TODO: Citizen Home Screen - Mostrar tarjeta ETA'),
backgroundColor: AppTheme.background,
appBar: AppBar(
title: const Text('Estado del Servicio'),
actions: [
IconButton(
icon: const Icon(Icons.refresh),
tooltip: 'Actualizar tiempos',
onPressed: () {
setState(() => _isLoading = true);
_loadData();
},
)
],
),
body: _isLoading
? const Center(child: CircularProgressIndicator())
: _casas.isEmpty
? const Center(
child: Text(
'No tienes domicilios registrados.',
style: TextStyle(color: AppTheme.textSecondary),
),
)
: ListView.separated(
padding: const EdgeInsets.all(16),
itemCount: _casas.length,
separatorBuilder: (_, __) => const SizedBox(height: 24),
itemBuilder: (context, index) {
final casa = _casas[index];
final eta = _etas[casa.id] ?? 'Actualizando...';
final horario = _horarios[casa.colonia] ?? 'Horario asignado a la ruta';
return _HouseEtaCard(casa: casa, etaMsg: eta, horario: horario);
},
),
);
}
}
// ── Widget para la Tarjeta de Mapa y ETA ─────────────────────────────────────
class _HouseEtaCard extends StatelessWidget {
final UIHouseModel casa;
final String etaMsg;
final String horario;
const _HouseEtaCard({
required this.casa,
required this.etaMsg,
required this.horario,
});
@override
Widget build(BuildContext context) {
final center = kColoniasCoordinates[casa.colonia] ?? const LatLng(20.5222, -100.8123);
// Restricción del mapa a la colonia (Privacidad por Diseño)
final bounds = LatLngBounds(
LatLng(center.latitude - 0.01, center.longitude - 0.01),
LatLng(center.latitude + 0.01, center.longitude + 0.01),
);
return Container(
decoration: BoxDecoration(
color: AppTheme.surface,
borderRadius: BorderRadius.circular(AppTheme.radiusLg),
border: Border.all(color: AppTheme.border),
boxShadow: AppTheme.cardShadow,
),
clipBehavior: Clip.hardEdge,
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
// ── Mapa Restringido ──
SizedBox(
height: 180,
child: FlutterMap(
options: MapOptions(
initialCameraFit: CameraFit.bounds(bounds: bounds),
cameraConstraint: CameraConstraint.contain(bounds: bounds),
interactionOptions: const InteractionOptions(
flags: InteractiveFlag.drag | InteractiveFlag.pinchZoom,
),
),
children: [
TileLayer(
urlTemplate: 'https://tile.openstreetmap.org/{z}/{x}/{y}.png',
userAgentPackageName: 'com.onlineshack.recolecta',
),
CircleLayer(
circles: [
CircleMarker(
point: center,
color: AppTheme.primary.withValues(alpha: 0.15),
borderColor: AppTheme.primary,
borderStrokeWidth: 2,
radius: 400,
useRadiusInMeter: true,
),
],
),
],
),
),
// ── Recuadro de Información ──
Padding(
padding: const EdgeInsets.all(16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
const Icon(Icons.home, color: AppTheme.primary, size: 20),
const SizedBox(width: 8),
Text(
casa.alias.isNotEmpty ? casa.alias : 'Mi Domicilio',
style: const TextStyle(
fontSize: 16,
fontWeight: FontWeight.w700,
color: AppTheme.textPrimary,
),
),
],
),
const SizedBox(height: 14),
_InfoRow(icon: Icons.location_on_outlined, title: 'Dirección', value: casa.direccionCompleta),
const SizedBox(height: 12),
_InfoRow(icon: Icons.schedule_outlined, title: 'Horario Habitual', value: horario),
const SizedBox(height: 18),
// ── Alerta de ETA en Tiempo Real ──
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: AppTheme.primaryLight,
borderRadius: BorderRadius.circular(AppTheme.radiusSm),
border: Border.all(color: AppTheme.primaryMid),
),
child: Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Icon(Icons.local_shipping_outlined, color: AppTheme.primaryDark),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'Estado del Camión',
style: TextStyle(
fontSize: 12,
fontWeight: FontWeight.w600,
color: AppTheme.primaryDark,
),
),
const SizedBox(height: 4),
Text(
etaMsg,
style: const TextStyle(
fontSize: 14,
fontWeight: FontWeight.w500,
color: AppTheme.primaryDark,
),
),
],
),
),
],
),
),
],
),
),
],
),
);
}
}
// ── Fila auxiliar de info ────────────────────────────────────────────────────
class _InfoRow extends StatelessWidget {
final IconData icon;
final String title;
final String value;
const _InfoRow({required this.icon, required this.title, required this.value});
@override
Widget build(BuildContext context) {
return Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Icon(icon, size: 18, color: AppTheme.textSecondary),
const SizedBox(width: 10),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
title,
style: const TextStyle(fontSize: 12, color: AppTheme.textSecondary, fontWeight: FontWeight.w500),
),
const SizedBox(height: 2),
Text(
value,
style: const TextStyle(fontSize: 14, color: AppTheme.textPrimary, height: 1.3),
),
],
),
),
],
);
}
}