From 91fe15a057487ba886956ead1cf3fbcadc997dfb Mon Sep 17 00:00:00 2001 From: Liinares Date: Tue, 5 Nov 2024 20:28:06 +0100 Subject: [PATCH 01/38] =?UTF-8?q?feat(collect=5Fpoints):=20A=C3=B1adir=20l?= =?UTF-8?q?istado=20a=20los=20puntos=20de=20recogida?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/app/punto-recogida/page.js | 448 +++++++++++++++++++++------------ 1 file changed, 288 insertions(+), 160 deletions(-) diff --git a/src/app/punto-recogida/page.js b/src/app/punto-recogida/page.js index af2ed5ef..09c6d825 100644 --- a/src/app/punto-recogida/page.js +++ b/src/app/punto-recogida/page.js @@ -1,12 +1,12 @@ 'use client'; -import { useState } from 'react'; -import { Package } from 'lucide-react'; +import { useState, useEffect } from 'react'; import { supabase } from '@/lib/supabase/client'; -import { isValidPhone, isNumericOrSpaces } from '@/helpers/utils'; +import { MapPin, Phone, Package, House, Contact, Megaphone } from 'lucide-react'; +import AddressAutocomplete from '@/components/AddressAutocomplete'; -export default function PuntoRecogida() { - const [formData, setFormData] = useState({ +export default function PuntosRecogida() { + const initialFormData = { name: '', type: 'permanente', location: '', @@ -16,191 +16,319 @@ export default function PuntoRecogida() { accepted_items: [], urgent_needs: '', status: 'active', - }); + }; - const [status, setStatus] = useState({ - isSubmitting: false, - error: null, - success: false, - }); + const [formData, setFormData] = useState(initialFormData); + const [showForm, setShowForm] = useState(false); + const [loading, setLoading] = useState(false); + const [collectionPoints, setCollectionPoints] = useState([]); + const [error, setError] = useState(null); + const [success, setSuccess] = useState(false); const tiposAyuda = ['Alimentos', 'Agua', 'Ropa', 'Mantas', 'Medicamentos', 'Productos de higiene']; - const handleSubmit = async (e) => { - e.preventDefault(); - setStatus({ isSubmitting: true, error: null, success: false }); + useEffect(() => { + fetchCollectionPoints(); + }, []); + async function fetchCollectionPoints() { try { - // Validar campos requeridos - if (!formData.name || !formData.location || !formData.city || !formData.contact_name || !formData.contact_phone) { - throw new Error('Por favor, complete todos los campos obligatorios'); - } + let { data, error } = await supabase + .from('collection_points') + .select('*') + .order('created_at', { ascending: false }); - if (formData.accepted_items.length === 0) { - throw new Error('Seleccione al menos un tipo de ayuda'); - } + if (error) throw error; + setCollectionPoints(data || []); + } catch (error) { + console.error('Error:', error); + setError('Error al cargar los puntos de recogida'); + } + } - if (!isValidPhone(formData.contact_phone)) { - throw new Error('El teléfono de contacto no es válido'); - } + async function handleSubmit(e) { + e.preventDefault(); + setLoading(true); + setError(null); - // Insertar en Supabase directamente - const { error } = await supabase.from('collection_points').insert([formData]); + try { + const requiredFields = ['name', 'location', 'contact_phone']; + const missingFields = requiredFields.filter((field) => !formData[field]); - if (error) throw error; + if (missingFields.length > 0) { + throw new Error('Por favor completa todos los campos obligatorios'); + } + + console.log('FormData before submission:', formData); // Debug log - // Limpiar formulario - setFormData({ - name: '', + const pointData = { + name: formData.name, type: 'permanente', - location: '', - city: '', - contact_name: '', - contact_phone: '', - accepted_items: [], - urgent_needs: '', + location: formData.location, + city: formData.city || null, + contact_name: formData.contact_name || null, + contact_phone: formData.contact_phone, + accepted_items: formData.accepted_items || [], + urgent_needs: formData.urgent_needs || null, status: 'active', - }); + }; - setStatus({ isSubmitting: false, error: null, success: true }); - setTimeout(() => setStatus((prev) => ({ ...prev, success: false })), 5000); + console.log('PointData for submission:', pointData); // Debug log + + const { error: insertError } = await supabase.from('collection_points').insert([pointData]); + + if (insertError) throw insertError; + + await fetchCollectionPoints(); + setSuccess(true); + setShowForm(false); + setFormData(initialFormData); + + setTimeout(() => setSuccess(false), 3000); } catch (error) { - console.error('Error:', error); - setStatus({ - isSubmitting: false, - error: error.message || 'Error al registrar el punto de recogida', - success: false, - }); + console.error('Error al registrar punto de recogida:', error); + setError(error.message || 'Error al registrar el punto de recogida'); + } finally { + setLoading(false); } - }; + } return ( -
- {status.error && ( -
-

{status.error}

-
- )} - - {status.success && ( -
-

Punto de recogida registrado correctamente

-
- )} - -
-
+
+
+

-

Registrar Punto de Recogida

-

- -
-
- - setFormData({ ...formData, name: e.target.value })} - className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500" - /> -
+ Puntos de recogida + + +
-
- - setFormData({ ...formData, location: e.target.value })} - className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500" - /> -
+ {/* Lista de puntos de recogida */} +
+ {collectionPoints.length > 0 ? ( + collectionPoints.map((point) => ( +
+
+
+

{point.name}

+
+ + {point.location} +
+
+ + {point.type === 'permanente' ? 'Permanente' : 'Temporal'} + +
-
- - setFormData({ ...formData, city: e.target.value })} - className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500" - /> +
+ {point.city && ( +
+ + Ciudad: {point.city} +
+ )} + {point.contact_name && ( +
+ + Nombre de contacto: {point.contact_name} +
+ )} + {point.accepted_items && ( +
+ + + Necesita:{' '} + {Array.isArray(point.accepted_items) + ? point.accepted_items + .map((tipo) => { + return tipo; + }) + .join(', ') + : 'Ayuda general'} + +
+ )} + {point.contact_phone && ( +
+ + Teléfono: {point.contact_phone} +
+ )} + {point.urgent_needs && ( +
+ Necesidades urgentes: +

{point.urgent_needs}

+
+ )} +
+
+ )) + ) : ( +
+ +

No hay puntos de recogida registrados

+

+ Sé el primero en registrar un punto de recogida para ayudar con la logística de suministros. +

+
+ )} +
-
- - setFormData({ ...formData, contact_name: e.target.value })} - className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500" - /> -
+ {/* Modal2 de formulario */} + {showForm && ( +
+
+

Registrar Punto de Recogida

+ +
+ + setFormData({ ...formData, name: e.target.value })} + className="w-full p-2 border rounded" + required + /> +
+
+ + { + console.log('Address selected:', address); // Debug log + setFormData((prev) => ({ + ...prev, + location: address.fullAddress, + city: address.details.city, + coordinates: address.coordinates + ? { + lat: address.coordinates.lat, + lng: address.coordinates.lon, + } + : null, + })); + }} + placeholder="Buscar dirección..." + /> +
+
+ +
+ {tiposAyuda.map((tipo) => ( + + ))} +
+
+
+
+ + setFormData({ ...formData, contact_name: e.target.value })} + className="w-full p-2 border rounded" + /> +
+
+ + setFormData({ ...formData, contact_phone: e.target.value })} + className="w-full p-2 border rounded" + required + /> +
+
-
- - - isNumericOrSpaces(e.target.value) && setFormData({ ...formData, contact_phone: e.target.value }) - } - className="w-full p-2 border rounded focus:ring-2 focus:ring-blue-500" - /> -
+
+ +