Actualizacion del programa
This commit is contained in:
@@ -50,12 +50,32 @@ class _AddDomicilioScreenState extends State<AddDomicilioScreen> {
|
||||
setState(() => _loading = true);
|
||||
|
||||
final auth = context.read<AuthService>();
|
||||
final routeData = getColonyByName(_coloniaSeleccionada!);
|
||||
final routeId = routeData?.routeId ?? 'RUTA-01';
|
||||
final horario = routeData?.horarioEstimado ?? 'Matutino (06:00-08:00)';
|
||||
|
||||
// 1. Buscar primero en colonies_data (rutas predefinidas)
|
||||
final staticData = getColonyByName(_coloniaSeleccionada!);
|
||||
String routeId = staticData?.routeId ?? '';
|
||||
String horario = staticData?.horarioEstimado ?? '';
|
||||
|
||||
// 2. Si no hay match estático, buscar en route_definitions del admin
|
||||
if (routeId.isEmpty) {
|
||||
final routeDefs = await DbHelper.getAllRouteDefinitions();
|
||||
for (final rd in routeDefs) {
|
||||
if (rd.colonias.any((c) =>
|
||||
c.toLowerCase() == _coloniaSeleccionada!.toLowerCase())) {
|
||||
routeId = rd.routeId;
|
||||
horario = '${_turnoLabel(rd.turno)} (${rd.horaInicio}–${rd.horaFin})';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Fallback si no se encontró
|
||||
if (routeId.isEmpty) {
|
||||
routeId = 'RUTA-01';
|
||||
horario = 'Matutino (06:00–08:00)';
|
||||
}
|
||||
|
||||
if (widget.editing != null) {
|
||||
// Editar existente — eliminar y volver a insertar
|
||||
await DbHelper.deleteDomicilio(widget.editing!.id!);
|
||||
}
|
||||
|
||||
@@ -75,6 +95,9 @@ class _AddDomicilioScreenState extends State<AddDomicilioScreen> {
|
||||
Navigator.pop(context, true);
|
||||
}
|
||||
|
||||
String _turnoLabel(String t) =>
|
||||
t == 'MATUTINO' ? 'Matutino' : t == 'VESPERTINO' ? 'Vespertino' : 'Nocturno';
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
|
||||
@@ -16,12 +16,12 @@ class _AiCameraScreenState extends State<AiCameraScreen> {
|
||||
CameraController? _cam;
|
||||
Interpreter? _interpreter;
|
||||
bool _processing = false;
|
||||
String _result = 'Apunta a un residuo y escanea';
|
||||
String _result = 'Apunta a un residuo y toca el botón';
|
||||
String _confidence = '';
|
||||
bool _modelLoaded = false;
|
||||
|
||||
// 0=Orgánico, 1=Inorgánico (según waste_classification_model)
|
||||
final _labels = ['Residuo Orgánico ♻️', 'Residuo Inorgánico 🗑️'];
|
||||
final _labels = ['Residuo Organico', 'Residuo Inorganico'];
|
||||
final _labelColors = [AppColors.verdeExito, AppColors.naranjaAlerta];
|
||||
|
||||
@override
|
||||
@@ -52,7 +52,7 @@ class _AiCameraScreenState extends State<AiCameraScreen> {
|
||||
_interpreter = await Interpreter.fromAsset('assets/models/waste_model.tflite');
|
||||
setState(() => _modelLoaded = true);
|
||||
} catch (e) {
|
||||
setState(() => _result = '⚠️ Modelo no encontrado.\nAgrega waste_model.tflite a assets/models/');
|
||||
setState(() => _result = 'Modelo no encontrado.\nAgrega waste_model.tflite a assets/models/');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
270
lib/screens/citizen/chatbot_screen.dart
Normal file
270
lib/screens/citizen/chatbot_screen.dart
Normal file
@@ -0,0 +1,270 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
|
||||
// ── Árbol de respuestas predefinidas ──────────────────────────────────────
|
||||
class _ChatNode {
|
||||
final String text;
|
||||
final List<_ChatOption> options;
|
||||
final bool isAnswer;
|
||||
const _ChatNode(this.text, this.options, {this.isAnswer = false});
|
||||
}
|
||||
|
||||
class _ChatOption {
|
||||
final String label;
|
||||
final _ChatNode next;
|
||||
const _ChatOption(this.label, this.next);
|
||||
}
|
||||
|
||||
final _chatTree = _ChatNode('Hola, soy el asistente de Celaya Limpia. ¿En que te puedo ayudar?', [
|
||||
_ChatOption('Separacion de residuos', _ChatNode('¿Que quieres saber sobre separacion?', [
|
||||
_ChatOption('Como separo mi basura', _ChatNode(
|
||||
'Separa tus residuos en 3 grupos:\n\n'
|
||||
'ORGANICOS (bolsa verde):\nRestos de comida, cascara de huevo, pasto, hojas.\n\n'
|
||||
'INORGANICOS reciclables (bolsa azul):\nPET, latas, carton limpio, vidrio.\n\n'
|
||||
'NO reciclables (bolsa negra):\nPanales, papel sanitario, colillas, chicles.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('Que NO debo mezclar', _ChatNode(
|
||||
'NUNCA mezcles:\n\n'
|
||||
'- Pilas o baterias con basura comun\n'
|
||||
'- Aceite de cocina (contamina el agua)\n'
|
||||
'- Medicamentos vencidos\n'
|
||||
'- Jeringas o material medico\n'
|
||||
'- Electronicos con basura doméstica\n\n'
|
||||
'Estos requieren manejo especial.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('Que hago con el aceite', _ChatNode(
|
||||
'El aceite de cocina usado NO va a la basura ni al drenaje.\n\n'
|
||||
'1. Dejalo enfriar completamente\n'
|
||||
'2. Guardalo en botella de PET cerrada\n'
|
||||
'3. Llevalo a los puntos de acopio del Ayuntamiento de Celaya\n\n'
|
||||
'El aceite reciclado se convierte en biodiesel.',
|
||||
[], isAnswer: true)),
|
||||
])),
|
||||
_ChatOption('Residuos especiales', _ChatNode('¿Que tipo de residuo especial tienes?', [
|
||||
_ChatOption('Donde dejo electronicos', _ChatNode(
|
||||
'Los aparatos electronicos (celulares, computadoras, focos ahorradores) '
|
||||
'son residuos RAEE.\n\n'
|
||||
'Puntos de acopio en Celaya:\n'
|
||||
'- Tiendas de electronica\n'
|
||||
'- Centros comerciales con contenedores especiales\n'
|
||||
'- Eventos de recoleccion del municipio\n\n'
|
||||
'NUNCA los tires a la basura comun.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('Que hago con medicamentos', _ChatNode(
|
||||
'Los medicamentos vencidos son residuos peligrosos.\n\n'
|
||||
'- Llevalos a farmacias que tengan programa de devolucion\n'
|
||||
'- Algunos hospitales los reciben\n'
|
||||
'- Nunca los tires al drenaje ni a la basura comun\n\n'
|
||||
'Contaminar el agua con medicamentos afecta a toda la comunidad.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('Que hago con pilas y baterias', _ChatNode(
|
||||
'Las pilas y baterias contienen metales pesados toxicos.\n\n'
|
||||
'Depositalas en:\n'
|
||||
'- Supermercados (contenedores naranjas)\n'
|
||||
'- Tiendas de electronica\n'
|
||||
'- Oficinas del Ayuntamiento de Celaya\n\n'
|
||||
'1 pila puede contaminar 600,000 litros de agua.',
|
||||
[], isAnswer: true)),
|
||||
])),
|
||||
_ChatOption('Sobre el servicio de recoleccion', _ChatNode('¿Que necesitas saber?', [
|
||||
_ChatOption('Cuando debo sacar la basura', _ChatNode(
|
||||
'Celaya Limpia te notificara:\n\n'
|
||||
'1. Cuando el camion salga del relleno sanitario\n'
|
||||
'2. Cuando este a 30 minutos\n'
|
||||
'3. A 15 minutos: este es el momento de sacar tus bolsas\n\n'
|
||||
'NO saques la basura antes del aviso de 15 minutos. '
|
||||
'Atrae fauna nociva y obstruye la acera.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('El camion no paso', _ChatNode(
|
||||
'Si el camion no paso en tu horario habitual:\n\n'
|
||||
'1. Revisa las alertas en la app (puede haber un retraso o incidente)\n'
|
||||
'2. Guarda tu basura bien cerrada\n'
|
||||
'3. Reporta la incidencia desde la seccion "Reportar"\n\n'
|
||||
'El administrador revisara tu reporte y te mantendra informado.',
|
||||
[], isAnswer: true)),
|
||||
_ChatOption('Como califico el servicio', _ChatNode(
|
||||
'Despues de que el camion pase por tu zona, '
|
||||
'la app te mostrara una notificacion para calificar.\n\n'
|
||||
'Puedes dar de 1 a 5 estrellas y dejar un comentario.\n\n'
|
||||
'Tus calificaciones ayudan al Ayuntamiento a identificar '
|
||||
'colonias con problemas y mejorar el servicio.',
|
||||
[], isAnswer: true)),
|
||||
])),
|
||||
_ChatOption('Denuncia o emergencia', _ChatNode(
|
||||
'Para situaciones urgentes:\n\n'
|
||||
'- Reporte de incidencias: usa la seccion "Reportar" en la app\n'
|
||||
'- Emergencias: llama al 911\n'
|
||||
'- Ayuntamiento de Celaya: (461) 614-8000\n'
|
||||
'- SEMARNAT Guanajuato: (477) 717-2600\n\n'
|
||||
'Para basura clandestina o tiraderos ilegales, reportalo al municipio.',
|
||||
[], isAnswer: true)),
|
||||
]);
|
||||
|
||||
// ── Pantalla del chatbot ──────────────────────────────────────────────────
|
||||
class ChatbotScreen extends StatefulWidget {
|
||||
const ChatbotScreen({super.key});
|
||||
@override State<ChatbotScreen> createState() => _ChatbotScreenState();
|
||||
}
|
||||
|
||||
class _ChatbotScreenState extends State<ChatbotScreen> {
|
||||
final List<_Message> _messages = [];
|
||||
_ChatNode _current = _chatTree;
|
||||
final _scroll = ScrollController();
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Mensaje inicial
|
||||
_messages.add(_Message(text: _chatTree.text, isBot: true));
|
||||
}
|
||||
|
||||
void _handleOption(_ChatOption option) {
|
||||
setState(() {
|
||||
// Mensaje del usuario
|
||||
_messages.add(_Message(text: option.label, isBot: false));
|
||||
// Ir al siguiente nodo
|
||||
_current = option.next;
|
||||
_messages.add(_Message(text: _current.text, isBot: true,
|
||||
isAnswer: _current.isAnswer));
|
||||
});
|
||||
Future.delayed(const Duration(milliseconds: 100), () {
|
||||
_scroll.animateTo(_scroll.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
|
||||
});
|
||||
}
|
||||
|
||||
void _reset() {
|
||||
setState(() {
|
||||
_messages.clear();
|
||||
_current = _chatTree;
|
||||
_messages.add(_Message(text: _chatTree.text, isBot: true));
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
backgroundColor: AppColors.grisFondo,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.guindaPrimary, foregroundColor: Colors.white,
|
||||
title: const Row(children: [
|
||||
CircleAvatar(radius: 14,
|
||||
backgroundColor: Colors.white24,
|
||||
child: Icon(Icons.smart_toy, color: AppColors.dorado, size: 18)),
|
||||
SizedBox(width: 8),
|
||||
Text('Asistente Celaya Limpia'),
|
||||
]),
|
||||
bottom: PreferredSize(preferredSize: const Size.fromHeight(4),
|
||||
child: Container(height: 4, color: AppColors.dorado)),
|
||||
actions: [
|
||||
IconButton(icon: const Icon(Icons.refresh), tooltip: 'Reiniciar',
|
||||
onPressed: _reset),
|
||||
],
|
||||
),
|
||||
body: Column(children: [
|
||||
// Mensajes
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: _scroll,
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: _messages.length,
|
||||
itemBuilder: (_, i) => _MessageBubble(msg: _messages[i]),
|
||||
),
|
||||
),
|
||||
// Opciones del nodo actual
|
||||
if (_current.options.isNotEmpty)
|
||||
Container(
|
||||
color: Colors.white,
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text('Selecciona una opcion:',
|
||||
style: TextStyle(fontSize: 11, color: AppColors.grisTexto,
|
||||
fontWeight: FontWeight.w500)),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(spacing: 8, runSpacing: 8,
|
||||
children: _current.options.map((opt) =>
|
||||
ActionChip(
|
||||
label: Text(opt.label, style: const TextStyle(fontSize: 12)),
|
||||
backgroundColor: AppColors.guindaPrimary.withOpacity(0.1),
|
||||
side: const BorderSide(color: AppColors.guindaPrimary),
|
||||
labelStyle: const TextStyle(color: AppColors.guindaPrimary),
|
||||
onPressed: () => _handleOption(opt),
|
||||
)).toList()),
|
||||
],
|
||||
),
|
||||
)
|
||||
else
|
||||
// Botón de reiniciar al llegar a una respuesta final
|
||||
Container(
|
||||
color: Colors.white,
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: SizedBox(width: double.infinity,
|
||||
child: OutlinedButton.icon(
|
||||
onPressed: _reset,
|
||||
style: OutlinedButton.styleFrom(
|
||||
foregroundColor: AppColors.guindaPrimary,
|
||||
side: const BorderSide(color: AppColors.guindaPrimary)),
|
||||
icon: const Icon(Icons.arrow_back, size: 16),
|
||||
label: const Text('Hacer otra pregunta'))),
|
||||
),
|
||||
]),
|
||||
);
|
||||
|
||||
@override void dispose() { _scroll.dispose(); super.dispose(); }
|
||||
}
|
||||
|
||||
class _Message {
|
||||
final String text;
|
||||
final bool isBot;
|
||||
final bool isAnswer;
|
||||
const _Message({required this.text, required this.isBot, this.isAnswer = false});
|
||||
}
|
||||
|
||||
class _MessageBubble extends StatelessWidget {
|
||||
final _Message msg;
|
||||
const _MessageBubble({super.key, required this.msg});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.symmetric(vertical: 4),
|
||||
child: Row(
|
||||
mainAxisAlignment: msg.isBot ? MainAxisAlignment.start : MainAxisAlignment.end,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
if (msg.isBot) ...[
|
||||
CircleAvatar(radius: 16,
|
||||
backgroundColor: AppColors.guindaPrimary,
|
||||
child: const Icon(Icons.smart_toy, color: Colors.white, size: 16)),
|
||||
const SizedBox(width: 8),
|
||||
],
|
||||
Flexible(child: Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: msg.isBot
|
||||
? (msg.isAnswer ? Colors.green.shade50 : Colors.white)
|
||||
: AppColors.guindaPrimary,
|
||||
borderRadius: BorderRadius.only(
|
||||
topLeft: const Radius.circular(16),
|
||||
topRight: const Radius.circular(16),
|
||||
bottomLeft: Radius.circular(msg.isBot ? 4 : 16),
|
||||
bottomRight: Radius.circular(msg.isBot ? 16 : 4),
|
||||
),
|
||||
border: msg.isBot ? Border.all(
|
||||
color: msg.isAnswer
|
||||
? Colors.green.shade200
|
||||
: Colors.grey.shade200) : null,
|
||||
boxShadow: [BoxShadow(color: Colors.black.withOpacity(0.06),
|
||||
blurRadius: 4, offset: const Offset(0, 2))],
|
||||
),
|
||||
child: Text(msg.text,
|
||||
style: TextStyle(fontSize: 13, height: 1.5,
|
||||
color: msg.isBot ? AppColors.negroTexto : Colors.white)),
|
||||
)),
|
||||
if (!msg.isBot) const SizedBox(width: 8),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,10 @@ import 'citizen_guia_screen.dart';
|
||||
import 'citizen_reporte_screen.dart';
|
||||
import 'add_domicilio_screen.dart';
|
||||
import 'review_screen.dart';
|
||||
import 'collection_calendar_screen.dart';
|
||||
import 'notification_history_screen.dart';
|
||||
import 'chatbot_screen.dart';
|
||||
import '../settings_screen.dart';
|
||||
|
||||
class CitizenHomeScreen extends StatefulWidget {
|
||||
const CitizenHomeScreen({super.key});
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import 'dart:io';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:image_picker/image_picker.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../database/db_helper.dart';
|
||||
import '../../models/models.dart';
|
||||
@@ -16,12 +18,14 @@ class _CitizenReporteScreenState extends State<CitizenReporteScreen> {
|
||||
int _calif = 5;
|
||||
bool _loading = false, _sent = false;
|
||||
List<ReporteModel> _reportes = [];
|
||||
File? _foto;
|
||||
final _picker = ImagePicker();
|
||||
|
||||
static const _tipos = {
|
||||
'CAMION_NO_PASO':'🚛 El camión no pasó',
|
||||
'RETRASO':'⏱️ Retraso significativo',
|
||||
'RESIDUOS_NO_RECOGIDOS':'🗑️ Residuos no recogidos',
|
||||
'OTRO':'📝 Otro motivo',
|
||||
'CAMION_NO_PASO': 'El camion no paso',
|
||||
'RETRASO': 'Retraso significativo',
|
||||
'RESIDUOS_NO_RECOGIDOS': 'Residuos no recogidos',
|
||||
'OTRO': 'Otro motivo',
|
||||
};
|
||||
|
||||
@override void initState() { super.initState(); _load(); }
|
||||
@@ -33,22 +37,59 @@ class _CitizenReporteScreenState extends State<CitizenReporteScreen> {
|
||||
if (mounted) setState(() => _reportes = r);
|
||||
}
|
||||
|
||||
Future<void> _pickImage(ImageSource source) async {
|
||||
try {
|
||||
final picked = await _picker.pickImage(source: source, imageQuality: 70, maxWidth: 1024);
|
||||
if (picked != null && mounted) setState(() => _foto = File(picked.path));
|
||||
} catch (e) {
|
||||
if (mounted) ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('No se pudo acceder a la camara: $e'),
|
||||
backgroundColor: AppColors.rojoError));
|
||||
}
|
||||
}
|
||||
|
||||
void _showPhotoOptions() {
|
||||
showModalBottomSheet(context: context, builder: (_) => SafeArea(
|
||||
child: Column(mainAxisSize: MainAxisSize.min, children: [
|
||||
ListTile(leading: const Icon(Icons.camera_alt, color: AppColors.guindaPrimary),
|
||||
title: const Text('Tomar foto'),
|
||||
onTap: () { Navigator.pop(context); _pickImage(ImageSource.camera); }),
|
||||
ListTile(leading: const Icon(Icons.photo_library, color: AppColors.guindaPrimary),
|
||||
title: const Text('Elegir de galeria'),
|
||||
onTap: () { Navigator.pop(context); _pickImage(ImageSource.gallery); }),
|
||||
if (_foto != null)
|
||||
ListTile(leading: const Icon(Icons.delete_outline, color: AppColors.rojoError),
|
||||
title: const Text('Quitar foto', style: TextStyle(color: AppColors.rojoError)),
|
||||
onTap: () { Navigator.pop(context); setState(() => _foto = null); }),
|
||||
])));
|
||||
}
|
||||
|
||||
Future<void> _send() async {
|
||||
final auth = context.read<AuthService>();
|
||||
if (auth.currentUser == null || _desc.text.trim().isEmpty) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(const SnackBar(
|
||||
content: Text('Describe el problema'), backgroundColor: AppColors.rojoError)); return;
|
||||
content: Text('Describe el problema'),
|
||||
backgroundColor: AppColors.rojoError));
|
||||
return;
|
||||
}
|
||||
setState(() => _loading = true);
|
||||
await DbHelper.insertReporte(ReporteModel(
|
||||
userId: auth.currentUser!.id!, tipo: _tipo, descripcion: _desc.text.trim(),
|
||||
colonia: auth.primaryDomicilio?.colonia ?? '',
|
||||
routeId: auth.primaryDomicilio?.routeId ?? '',
|
||||
fecha: DateTime.now().toIso8601String(), calificacion: _calif,
|
||||
));
|
||||
|
||||
final db = await DbHelper.database;
|
||||
await db.insert('reportes', {
|
||||
'user_id': auth.currentUser!.id,
|
||||
'tipo': _tipo,
|
||||
'descripcion': _desc.text.trim(),
|
||||
'colonia': auth.primaryDomicilio?.colonia ?? '',
|
||||
'route_id': auth.primaryDomicilio?.routeId ?? '',
|
||||
'fecha': DateTime.now().toIso8601String(),
|
||||
'estado': 'PENDIENTE',
|
||||
'calificacion': _calif,
|
||||
'foto_path': _foto?.path,
|
||||
});
|
||||
|
||||
await _load();
|
||||
if (!mounted) return;
|
||||
setState(() { _loading = false; _sent = true; _desc.clear(); });
|
||||
setState(() { _loading = false; _sent = true; _desc.clear(); _foto = null; });
|
||||
await Future.delayed(const Duration(seconds: 2));
|
||||
if (mounted) setState(() => _sent = false);
|
||||
}
|
||||
@@ -61,57 +102,120 @@ class _CitizenReporteScreenState extends State<CitizenReporteScreen> {
|
||||
title: const Text('Reportar Incidencia'),
|
||||
bottom: PreferredSize(preferredSize: const Size.fromHeight(4),
|
||||
child: Container(height: 4, color: AppColors.dorado))),
|
||||
body: _sent ? Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
const Icon(Icons.check_circle, color: AppColors.verdeExito, size: 64),
|
||||
const SizedBox(height: 12),
|
||||
const Text('¡Reporte enviado!', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold, color: AppColors.verdeExito)),
|
||||
const Text('El Ayuntamiento lo revisará pronto.', style: TextStyle(color: AppColors.grisTexto)),
|
||||
])) : SingleChildScrollView(padding: const EdgeInsets.all(16), child: Column(children: [
|
||||
Card(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: Padding(padding: const EdgeInsets.all(16), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Text('Nueva Incidencia', style: TextStyle(fontWeight: FontWeight.bold, color: AppColors.guindaPrimary, fontSize: 16)),
|
||||
const SizedBox(height: 12),
|
||||
const Text('Tipo:', style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13)),
|
||||
..._tipos.entries.map((e) => RadioListTile<String>(dense: true, value: e.key,
|
||||
groupValue: _tipo, title: Text(e.value, style: const TextStyle(fontSize: 13)),
|
||||
activeColor: AppColors.guindaPrimary,
|
||||
onChanged: (v) => setState(() => _tipo = v!))),
|
||||
const SizedBox(height: 8),
|
||||
DropdownButtonFormField<int>(value: _calif,
|
||||
decoration: const InputDecoration(labelText: 'Calificación', border: OutlineInputBorder()),
|
||||
items: [5,4,3,2,1].map((n) => DropdownMenuItem(value: n,
|
||||
child: Text(['⭐⭐⭐⭐⭐ Excelente','⭐⭐⭐⭐ Bueno','⭐⭐⭐ Regular','⭐⭐ Malo','⭐ Muy malo'][5-n]))).toList(),
|
||||
onChanged: (v) => setState(() => _calif = v!)),
|
||||
const SizedBox(height: 10),
|
||||
TextField(controller: _desc, maxLines: 3,
|
||||
decoration: const InputDecoration(hintText: 'Describe el problema...',
|
||||
border: OutlineInputBorder(), filled: true, fillColor: Colors.white)),
|
||||
const SizedBox(height: 14),
|
||||
SizedBox(width: double.infinity, height: 48,
|
||||
child: ElevatedButton.icon(onPressed: _loading ? null : _send,
|
||||
style: ElevatedButton.styleFrom(backgroundColor: AppColors.guindaPrimary,
|
||||
foregroundColor: Colors.white, shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),
|
||||
icon: _loading ? const SizedBox(width: 18, height: 18,
|
||||
child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2)) : const Icon(Icons.send),
|
||||
label: const Text('ENVIAR REPORTE', style: TextStyle(fontWeight: FontWeight.bold)))),
|
||||
]))),
|
||||
if (_reportes.isNotEmpty) ...[
|
||||
const SizedBox(height: 16),
|
||||
const Align(alignment: Alignment.centerLeft,
|
||||
child: Text('Mis Reportes', style: TextStyle(fontWeight: FontWeight.bold, color: AppColors.guindaPrimary, fontSize: 15))),
|
||||
const SizedBox(height: 8),
|
||||
..._reportes.map((r) => Card(margin: const EdgeInsets.only(bottom: 6),
|
||||
child: ListTile(dense: true,
|
||||
leading: const CircleAvatar(backgroundColor: AppColors.guindaPrimary, radius: 16,
|
||||
child: Icon(Icons.report, color: Colors.white, size: 16)),
|
||||
title: Text(_tipos[r.tipo] ?? r.tipo, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(r.descripcion, maxLines: 1, overflow: TextOverflow.ellipsis, style: const TextStyle(fontSize: 11)),
|
||||
trailing: Container(padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
|
||||
decoration: BoxDecoration(color: AppColors.naranjaAlerta.withOpacity(0.15), borderRadius: BorderRadius.circular(10)),
|
||||
child: Text(r.estado, style: const TextStyle(fontSize: 9, color: AppColors.naranjaAlerta, fontWeight: FontWeight.bold)))))),
|
||||
],
|
||||
])),
|
||||
body: _sent
|
||||
? Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
const Icon(Icons.check_circle, color: AppColors.verdeExito, size: 64),
|
||||
const SizedBox(height: 12),
|
||||
const Text('Reporte enviado', style: TextStyle(fontSize: 20,
|
||||
fontWeight: FontWeight.bold, color: AppColors.verdeExito)),
|
||||
const Text('El Ayuntamiento lo revisara pronto.',
|
||||
style: TextStyle(color: AppColors.grisTexto)),
|
||||
]))
|
||||
: SingleChildScrollView(padding: const EdgeInsets.all(16), child: Column(children: [
|
||||
Card(shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(12)),
|
||||
child: Padding(padding: const EdgeInsets.all(16), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Text('Tipo de incidencia', style: TextStyle(
|
||||
fontWeight: FontWeight.bold, color: AppColors.guindaPrimary, fontSize: 15)),
|
||||
const SizedBox(height: 8),
|
||||
..._tipos.entries.map((e) => RadioListTile<String>(dense: true,
|
||||
value: e.key, groupValue: _tipo,
|
||||
title: Text(e.value, style: const TextStyle(fontSize: 13)),
|
||||
activeColor: AppColors.guindaPrimary,
|
||||
onChanged: (v) => setState(() => _tipo = v!))),
|
||||
const SizedBox(height: 8),
|
||||
DropdownButtonFormField<int>(value: _calif,
|
||||
decoration: const InputDecoration(labelText: 'Calificacion del servicio',
|
||||
border: OutlineInputBorder()),
|
||||
items: [5,4,3,2,1].map((n) => DropdownMenuItem(value: n,
|
||||
child: Text(['Excelente','Bueno','Regular','Malo','Muy malo'][5-n]))).toList(),
|
||||
onChanged: (v) => setState(() => _calif = v!)),
|
||||
const SizedBox(height: 10),
|
||||
TextField(controller: _desc, maxLines: 3,
|
||||
decoration: const InputDecoration(hintText: 'Describe el problema...',
|
||||
border: OutlineInputBorder(), filled: true, fillColor: Colors.white)),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Foto adjunta
|
||||
const Text('Foto del incidente (opcional)',
|
||||
style: TextStyle(fontWeight: FontWeight.w600, fontSize: 13)),
|
||||
const SizedBox(height: 8),
|
||||
GestureDetector(
|
||||
onTap: _showPhotoOptions,
|
||||
child: Container(
|
||||
width: double.infinity, height: _foto != null ? 180 : 80,
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade100,
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(color: _foto != null
|
||||
? AppColors.guindaPrimary : Colors.grey.shade300,
|
||||
style: BorderStyle.solid)),
|
||||
child: _foto != null
|
||||
? Stack(children: [
|
||||
ClipRRect(borderRadius: BorderRadius.circular(8),
|
||||
child: Image.file(_foto!, fit: BoxFit.cover,
|
||||
width: double.infinity, height: 180)),
|
||||
Positioned(top: 8, right: 8,
|
||||
child: GestureDetector(onTap: () => setState(() => _foto = null),
|
||||
child: Container(padding: const EdgeInsets.all(4),
|
||||
decoration: const BoxDecoration(
|
||||
color: AppColors.rojoError, shape: BoxShape.circle),
|
||||
child: const Icon(Icons.close, color: Colors.white, size: 16)))),
|
||||
])
|
||||
: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
const Icon(Icons.add_a_photo_outlined,
|
||||
color: AppColors.grisTexto, size: 28),
|
||||
const SizedBox(height: 4),
|
||||
const Text('Agregar foto', style: TextStyle(
|
||||
color: AppColors.grisTexto, fontSize: 12)),
|
||||
]),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 14),
|
||||
SizedBox(width: double.infinity, height: 48,
|
||||
child: ElevatedButton.icon(
|
||||
onPressed: _loading ? null : _send,
|
||||
style: ElevatedButton.styleFrom(
|
||||
backgroundColor: AppColors.guindaPrimary, foregroundColor: Colors.white,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(8))),
|
||||
icon: _loading ? const SizedBox(width: 18, height: 18,
|
||||
child: CircularProgressIndicator(color: Colors.white, strokeWidth: 2))
|
||||
: const Icon(Icons.send),
|
||||
label: const Text('ENVIAR REPORTE',
|
||||
style: TextStyle(fontWeight: FontWeight.bold)))),
|
||||
]))),
|
||||
if (_reportes.isNotEmpty) ...[
|
||||
const SizedBox(height: 16),
|
||||
const Align(alignment: Alignment.centerLeft,
|
||||
child: Text('Mis Reportes', style: TextStyle(fontWeight: FontWeight.bold,
|
||||
color: AppColors.guindaPrimary, fontSize: 15))),
|
||||
const SizedBox(height: 8),
|
||||
..._reportes.map((r) => Card(margin: const EdgeInsets.only(bottom: 6),
|
||||
child: ListTile(dense: true,
|
||||
leading: CircleAvatar(backgroundColor: AppColors.guindaPrimary, radius: 16,
|
||||
child: const Icon(Icons.report, color: Colors.white, size: 16)),
|
||||
title: Text(_tipos[r.tipo] ?? r.tipo,
|
||||
style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(r.descripcion, maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontSize: 11)),
|
||||
trailing: Container(padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: _estadoColor(r.estado).withOpacity(0.15),
|
||||
borderRadius: BorderRadius.circular(10)),
|
||||
child: Text(r.estado, style: TextStyle(fontSize: 9,
|
||||
color: _estadoColor(r.estado), fontWeight: FontWeight.bold)))))),
|
||||
],
|
||||
])),
|
||||
);
|
||||
|
||||
Color _estadoColor(String e) {
|
||||
switch (e) {
|
||||
case 'RESUELTO': return AppColors.verdeExito;
|
||||
case 'EN_REVISION': return AppColors.azulInfo;
|
||||
default: return AppColors.naranjaAlerta;
|
||||
}
|
||||
}
|
||||
|
||||
@override void dispose() { _desc.dispose(); super.dispose(); }
|
||||
}
|
||||
|
||||
253
lib/screens/citizen/collection_calendar_screen.dart
Normal file
253
lib/screens/citizen/collection_calendar_screen.dart
Normal file
@@ -0,0 +1,253 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import 'package:share_plus/share_plus.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../database/db_helper.dart';
|
||||
import '../../models/models.dart';
|
||||
import '../../services/auth_service.dart';
|
||||
|
||||
class CollectionCalendarScreen extends StatefulWidget {
|
||||
const CollectionCalendarScreen({super.key});
|
||||
@override State<CollectionCalendarScreen> createState() => _CollectionCalendarScreenState();
|
||||
}
|
||||
|
||||
class _CollectionCalendarScreenState extends State<CollectionCalendarScreen> {
|
||||
RouteDefinitionModel? _routeDef;
|
||||
List<ReviewModel> _myReviews = [];
|
||||
bool _loading = true;
|
||||
|
||||
@override
|
||||
void initState() { super.initState(); _load(); }
|
||||
|
||||
Future<void> _load() async {
|
||||
final auth = context.read<AuthService>();
|
||||
final dom = auth.primaryDomicilio;
|
||||
if (dom != null) {
|
||||
final rd = await DbHelper.getRouteDefinitionById(dom.routeId);
|
||||
final rv = await DbHelper.getAllReviews();
|
||||
final mine = rv.where((r) => r.userId == auth.currentUser?.id).toList();
|
||||
if (mounted) setState(() { _routeDef = rd; _myReviews = mine; _loading = false; });
|
||||
} else {
|
||||
if (mounted) setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
void _shareSchedule() {
|
||||
final auth = context.read<AuthService>();
|
||||
final dom = auth.primaryDomicilio;
|
||||
if (dom == null) return;
|
||||
final rd = _routeDef;
|
||||
final diasStr = rd?.dias.map(_diaLabel).join(', ') ?? 'Lunes, Miércoles y Viernes';
|
||||
final horario = rd != null ? '${rd.horaInicio}–${rd.horaFin}' : dom.horarioEstimado;
|
||||
|
||||
Share.share(
|
||||
'🗑️ Horario de recolección de basura\n'
|
||||
'📍 Colonia: ${dom.colonia}\n'
|
||||
'📅 Días: $diasStr\n'
|
||||
'⏰ Horario: $horario\n'
|
||||
'🚛 Ruta: ${dom.routeId}\n\n'
|
||||
'Descarga Celaya Limpia para recibir avisos en tiempo real.',
|
||||
);
|
||||
}
|
||||
|
||||
String _diaLabel(String d) {
|
||||
const m = {'LUNES':'Lu','MARTES':'Ma','MIERCOLES':'Mi',
|
||||
'JUEVES':'Ju','VIERNES':'Vi','SABADO':'Sa','DOMINGO':'Do'};
|
||||
return m[d] ?? d;
|
||||
}
|
||||
|
||||
// Días del mes actual con marcas de recolección
|
||||
List<Widget> _buildCalendar() {
|
||||
final now = DateTime.now();
|
||||
final first = DateTime(now.year, now.month, 1);
|
||||
final days = DateTime(now.year, now.month + 1, 0).day;
|
||||
final dias = _routeDef?.dias ?? [];
|
||||
|
||||
const weekDays = ['LUNES','MARTES','MIERCOLES','JUEVES','VIERNES','SABADO','DOMINGO'];
|
||||
final monthName = ['','Enero','Febrero','Marzo','Abril','Mayo','Junio',
|
||||
'Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre'][now.month];
|
||||
|
||||
return [
|
||||
Padding(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 4),
|
||||
child: Text('$monthName ${now.year}',
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16,
|
||||
color: AppColors.guindaPrimary)),
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
// Cabeceras días
|
||||
Row(children: ['Lu','Ma','Mi','Ju','Vi','Sa','Do'].map((d) =>
|
||||
Expanded(child: Center(child: Text(d, style: const TextStyle(
|
||||
fontWeight: FontWeight.bold, fontSize: 11, color: AppColors.grisTexto))))).toList()),
|
||||
const SizedBox(height: 4),
|
||||
// Grilla de días
|
||||
GridView.builder(
|
||||
shrinkWrap: true,
|
||||
physics: const NeverScrollableScrollPhysics(),
|
||||
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
|
||||
crossAxisCount: 7, childAspectRatio: 1),
|
||||
itemCount: (first.weekday - 1) + days,
|
||||
itemBuilder: (_, i) {
|
||||
if (i < first.weekday - 1) return const SizedBox();
|
||||
final day = i - (first.weekday - 1) + 1;
|
||||
final date = DateTime(now.year, now.month, day);
|
||||
final diaSem = weekDays[date.weekday - 1];
|
||||
final isCollection = dias.contains(diaSem);
|
||||
final isToday = day == now.day;
|
||||
final isPast = date.isBefore(DateTime(now.year, now.month, now.day));
|
||||
|
||||
return Container(
|
||||
margin: const EdgeInsets.all(2),
|
||||
decoration: BoxDecoration(
|
||||
color: isCollection
|
||||
? (isPast ? AppColors.guindaPrimary.withOpacity(0.4) : AppColors.guindaPrimary)
|
||||
: (isToday ? Colors.grey.shade200 : null),
|
||||
shape: BoxShape.circle,
|
||||
border: isToday ? Border.all(color: AppColors.dorado, width: 2) : null,
|
||||
),
|
||||
child: Stack(alignment: Alignment.center, children: [
|
||||
Text('$day', style: TextStyle(
|
||||
fontSize: 12,
|
||||
fontWeight: isToday ? FontWeight.bold : FontWeight.normal,
|
||||
color: isCollection ? Colors.white : AppColors.negroTexto,
|
||||
)),
|
||||
if (isCollection)
|
||||
Positioned(bottom: 2, child: Container(
|
||||
width: 4, height: 4,
|
||||
decoration: const BoxDecoration(color: AppColors.dorado, shape: BoxShape.circle),
|
||||
)),
|
||||
]),
|
||||
);
|
||||
},
|
||||
),
|
||||
];
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final auth = context.read<AuthService>();
|
||||
final dom = auth.primaryDomicilio;
|
||||
|
||||
return Scaffold(
|
||||
backgroundColor: AppColors.grisFondo,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.guindaPrimary, foregroundColor: Colors.white,
|
||||
title: const Text('Calendario de Recoleccion'),
|
||||
bottom: PreferredSize(preferredSize: const Size.fromHeight(4),
|
||||
child: Container(height: 4, color: AppColors.dorado)),
|
||||
actions: [
|
||||
IconButton(icon: const Icon(Icons.share), tooltip: 'Compartir horario',
|
||||
onPressed: _shareSchedule),
|
||||
],
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: SingleChildScrollView(padding: const EdgeInsets.all(16), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
// Info de la ruta
|
||||
if (dom != null)
|
||||
Card(child: Padding(padding: const EdgeInsets.all(14), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Row(children: [
|
||||
Icon(Icons.local_shipping, color: AppColors.guindaPrimary, size: 18),
|
||||
SizedBox(width: 6),
|
||||
Text('Tu servicio de recoleccion', style: TextStyle(
|
||||
fontWeight: FontWeight.bold, color: AppColors.guindaPrimary)),
|
||||
]),
|
||||
const Divider(),
|
||||
Text('Colonia: ${dom.colonia}',
|
||||
style: const TextStyle(fontWeight: FontWeight.w600, fontSize: 13)),
|
||||
Text('Ruta: ${dom.routeId}',
|
||||
style: const TextStyle(color: AppColors.grisTexto, fontSize: 12)),
|
||||
if (_routeDef != null) ...[
|
||||
Text('Dias: ${_routeDef!.dias.map(_diaLabel).join(" · ")}',
|
||||
style: const TextStyle(fontSize: 12)),
|
||||
Text('Horario: ${_routeDef!.horaInicio} - ${_routeDef!.horaFin}',
|
||||
style: const TextStyle(fontSize: 12)),
|
||||
] else
|
||||
Text(dom.horarioEstimado,
|
||||
style: const TextStyle(color: AppColors.grisTexto, fontSize: 12)),
|
||||
]))),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Leyenda
|
||||
Row(children: [
|
||||
_Legend(color: AppColors.guindaPrimary, label: 'Dia de recoleccion'),
|
||||
const SizedBox(width: 12),
|
||||
_Legend(color: AppColors.dorado, label: 'Punto en dia activo'),
|
||||
const SizedBox(width: 12),
|
||||
_Legend(color: Colors.grey.shade200, label: 'Hoy'),
|
||||
]),
|
||||
const SizedBox(height: 12),
|
||||
|
||||
// Calendario
|
||||
Card(child: Padding(padding: const EdgeInsets.all(14), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: _buildCalendar()))),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Consejos semanales
|
||||
Card(color: Colors.blue.shade50,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10),
|
||||
side: BorderSide(color: Colors.blue.shade200)),
|
||||
child: Padding(padding: const EdgeInsets.all(14), child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
const Row(children: [
|
||||
Icon(Icons.tips_and_updates, color: AppColors.azulInfo),
|
||||
SizedBox(width: 8),
|
||||
Text('Consejo de la semana', style: TextStyle(
|
||||
fontWeight: FontWeight.bold, color: AppColors.azulInfo, fontSize: 14)),
|
||||
]),
|
||||
const SizedBox(height: 8),
|
||||
Text(_weeklyTip(), style: const TextStyle(fontSize: 13, color: AppColors.negroTexto)),
|
||||
])),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
|
||||
// Mis calificaciones
|
||||
if (_myReviews.isNotEmpty) ...[
|
||||
const Text('Mis calificaciones', style: TextStyle(
|
||||
fontWeight: FontWeight.bold, fontSize: 15, color: AppColors.guindaPrimary)),
|
||||
const SizedBox(height: 8),
|
||||
..._myReviews.take(3).map((r) => Card(margin: const EdgeInsets.only(bottom: 8),
|
||||
child: ListTile(dense: true,
|
||||
leading: CircleAvatar(backgroundColor: Colors.amber.shade100,
|
||||
child: Text('${r.estrellas}', style: const TextStyle(
|
||||
fontWeight: FontWeight.bold, color: Colors.amber))),
|
||||
title: Text(r.colonia, style: const TextStyle(fontSize: 12, fontWeight: FontWeight.w600)),
|
||||
subtitle: Text(r.comentario, maxLines: 1, overflow: TextOverflow.ellipsis,
|
||||
style: const TextStyle(fontSize: 11)),
|
||||
trailing: Text(
|
||||
'${DateTime.tryParse(r.fecha)?.day}/${DateTime.tryParse(r.fecha)?.month}',
|
||||
style: const TextStyle(fontSize: 10, color: AppColors.grisTexto)),
|
||||
))),
|
||||
],
|
||||
const SizedBox(height: 30),
|
||||
])),
|
||||
);
|
||||
}
|
||||
|
||||
String _weeklyTip() {
|
||||
final tips = [
|
||||
'Separa tus residuos en organicos (restos de comida) e inorganicos (plasticos, metales). Facilita el reciclaje y reduce la contaminacion.',
|
||||
'Coloca tus bolsas en la acera SOLO cuando recibas el aviso de 15 minutos. Sacarlas antes atrae fauna nociva.',
|
||||
'El reciclaje de 1 tonelada de papel salva 17 arboles. Dobla tus cajas y periodicos antes de depositarlos.',
|
||||
'Los aceites usados de cocina NO van a la basura. Llevalos a los puntos de acopio del municipio.',
|
||||
'Composta tus restos organicos si tienes jardin. Reduce hasta un 40% tu basura y mejora tu suelo.',
|
||||
'Las pilas y baterias son residuos peligrosos. Depositalas en los contenedores especiales de tiendas.',
|
||||
'Un celular viejo contiene oro, plata y cobre. Llevalo a un punto RAEE para su reciclaje correcto.',
|
||||
];
|
||||
return tips[DateTime.now().weekday % tips.length];
|
||||
}
|
||||
}
|
||||
|
||||
class _Legend extends StatelessWidget {
|
||||
final Color color; final String label;
|
||||
const _Legend({required this.color, required this.label});
|
||||
@override
|
||||
Widget build(BuildContext context) => Row(mainAxisSize: MainAxisSize.min, children: [
|
||||
Container(width: 12, height: 12, decoration: BoxDecoration(color: color, shape: BoxShape.circle)),
|
||||
const SizedBox(width: 4),
|
||||
Text(label, style: const TextStyle(fontSize: 10, color: AppColors.grisTexto)),
|
||||
]);
|
||||
}
|
||||
127
lib/screens/citizen/notification_history_screen.dart
Normal file
127
lib/screens/citizen/notification_history_screen.dart
Normal file
@@ -0,0 +1,127 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:provider/provider.dart';
|
||||
import '../../core/app_colors.dart';
|
||||
import '../../database/db_helper.dart';
|
||||
import '../../services/auth_service.dart';
|
||||
|
||||
class NotificationHistoryScreen extends StatefulWidget {
|
||||
const NotificationHistoryScreen({super.key});
|
||||
@override State<NotificationHistoryScreen> createState() => _NotificationHistoryScreenState();
|
||||
}
|
||||
|
||||
class _NotificationHistoryScreenState extends State<NotificationHistoryScreen> {
|
||||
List<Map<String, dynamic>> _notifs = [];
|
||||
bool _loading = true;
|
||||
|
||||
@override
|
||||
void initState() { super.initState(); _load(); }
|
||||
|
||||
Future<void> _load() async {
|
||||
final auth = context.read<AuthService>();
|
||||
if (auth.currentUser == null) return;
|
||||
final n = await DbHelper.getNotifHistory(auth.currentUser!.id!);
|
||||
await DbHelper.markAllNotifsRead(auth.currentUser!.id!);
|
||||
if (mounted) setState(() { _notifs = n; _loading = false; });
|
||||
}
|
||||
|
||||
Color _color(String type) {
|
||||
switch (type) {
|
||||
case 'truckProximity':
|
||||
case 'truckApproaching15min': return AppColors.naranjaAlerta;
|
||||
case 'routeCompleted':
|
||||
case 'reviewPrompt': return AppColors.verdeExito;
|
||||
case 'routeCancelled': return AppColors.rojoError;
|
||||
case 'gpsLost': return Colors.red.shade800;
|
||||
case 'truckStopped': return AppColors.naranjaAlerta;
|
||||
default: return AppColors.azulInfo;
|
||||
}
|
||||
}
|
||||
|
||||
IconData _icon(String type) {
|
||||
switch (type) {
|
||||
case 'truckProximity':
|
||||
case 'truckApproaching15min': return Icons.warning_amber_rounded;
|
||||
case 'routeCompleted': return Icons.check_circle;
|
||||
case 'reviewPrompt': return Icons.star;
|
||||
case 'routeCancelled': return Icons.cancel;
|
||||
case 'gpsLost': return Icons.gps_off;
|
||||
default: return Icons.notifications;
|
||||
}
|
||||
}
|
||||
|
||||
String _timeAgo(String fechaStr) {
|
||||
final f = DateTime.tryParse(fechaStr);
|
||||
if (f == null) return '';
|
||||
final diff = DateTime.now().difference(f);
|
||||
if (diff.inMinutes < 1) return 'Ahora';
|
||||
if (diff.inMinutes < 60) return 'Hace ${diff.inMinutes} min';
|
||||
if (diff.inHours < 24) return 'Hace ${diff.inHours}h';
|
||||
return '${f.day}/${f.month}/${f.year}';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) => Scaffold(
|
||||
backgroundColor: AppColors.grisFondo,
|
||||
appBar: AppBar(
|
||||
backgroundColor: AppColors.guindaPrimary, foregroundColor: Colors.white,
|
||||
title: const Text('Historial de Alertas'),
|
||||
bottom: PreferredSize(preferredSize: const Size.fromHeight(4),
|
||||
child: Container(height: 4, color: AppColors.dorado)),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () async {
|
||||
await DbHelper.markAllNotifsRead(
|
||||
context.read<AuthService>().currentUser!.id!);
|
||||
setState(() {});
|
||||
},
|
||||
child: const Text('Marcar leídas', style: TextStyle(color: AppColors.dorado, fontSize: 12)),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: _notifs.isEmpty
|
||||
? Center(child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
|
||||
Icon(Icons.notifications_none, color: Colors.grey.shade400, size: 64),
|
||||
const SizedBox(height: 12),
|
||||
Text('Sin alertas registradas', style: TextStyle(color: Colors.grey.shade500)),
|
||||
]))
|
||||
: ListView.builder(
|
||||
padding: const EdgeInsets.all(12),
|
||||
itemCount: _notifs.length,
|
||||
itemBuilder: (_, i) {
|
||||
final n = _notifs[i];
|
||||
final isUnread = (n['leida'] as int?) == 0;
|
||||
final color = _color(n['event_type'] ?? '');
|
||||
return Container(
|
||||
margin: const EdgeInsets.only(bottom: 8),
|
||||
decoration: BoxDecoration(
|
||||
color: isUnread ? color.withOpacity(0.05) : Colors.white,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
border: Border.all(
|
||||
color: isUnread ? color.withOpacity(0.3) : Colors.grey.shade200),
|
||||
),
|
||||
child: ListTile(
|
||||
leading: CircleAvatar(
|
||||
backgroundColor: color.withOpacity(0.15),
|
||||
child: Icon(_icon(n['event_type'] ?? ''), color: color, size: 20),
|
||||
),
|
||||
title: Text(n['title'] ?? '', style: TextStyle(
|
||||
fontWeight: isUnread ? FontWeight.bold : FontWeight.normal,
|
||||
fontSize: 13)),
|
||||
subtitle: Column(crossAxisAlignment: CrossAxisAlignment.start, children: [
|
||||
Text(n['body'] ?? '', style: const TextStyle(fontSize: 11), maxLines: 2,
|
||||
overflow: TextOverflow.ellipsis),
|
||||
const SizedBox(height: 2),
|
||||
Text('${n['route_id']} · ${_timeAgo(n['fecha'] ?? '')}',
|
||||
style: TextStyle(fontSize: 10, color: color.withOpacity(0.7))),
|
||||
]),
|
||||
trailing: isUnread
|
||||
? Container(width: 8, height: 8,
|
||||
decoration: BoxDecoration(color: color, shape: BoxShape.circle))
|
||||
: null,
|
||||
),
|
||||
);
|
||||
}),
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user