From c577659cb714c42fbbd0862d9ace903ca05b5e58 Mon Sep 17 00:00:00 2001 From: robertobobby1 <61552357+robertobobby1@users.noreply.github.com> Date: Thu, 7 Nov 2024 17:33:35 +0100 Subject: [PATCH] Revert "Feat/address map" --- src/app/api/address/route.ts | 2 - .../_components/Form/FormContainer.tsx | 55 ++++--- .../_components/Form/FormRenderer.tsx | 35 ++-- src/app/solicitar-ayuda/_components/types.ts | 5 +- src/components/AddressMap.tsx | 52 ++++-- src/components/RequestHelp.js | 95 +++++++---- src/components/map/GeolocationMap.tsx | 155 +++++++----------- src/context/TownProvider.tsx | 2 +- src/lib/service.ts | 13 -- 9 files changed, 212 insertions(+), 202 deletions(-) diff --git a/src/app/api/address/route.ts b/src/app/api/address/route.ts index 054e9f2c..bd5dc153 100644 --- a/src/app/api/address/route.ts +++ b/src/app/api/address/route.ts @@ -14,8 +14,6 @@ const mapsTranslationToDbTowns: { [key: string]: string } = { Alcudia: "L'Alcúdia", Guadasuar: 'Guadassuar', València: 'Valencia', - Almusafes: 'Almussafes', - Montroi: 'Montroy', }; const GOOGLE_URL = `https://maps.googleapis.com/maps/api/geocode/json?key=${process.env.API_KEY}&latlng=`; diff --git a/src/app/solicitar-ayuda/_components/Form/FormContainer.tsx b/src/app/solicitar-ayuda/_components/Form/FormContainer.tsx index 480018c9..ce94b157 100644 --- a/src/app/solicitar-ayuda/_components/Form/FormContainer.tsx +++ b/src/app/solicitar-ayuda/_components/Form/FormContainer.tsx @@ -1,18 +1,17 @@ 'use client'; -import React, { useCallback, useMemo, useState } from 'react'; +import React, { useCallback, useEffect, useMemo, useState } from 'react'; import { FormRenderer } from './FormRenderer'; import { FormData, Status } from '../types'; import { formatPhoneNumber, isValidPhone } from '@/helpers/utils'; -import { helpRequestService, locationService, townService } from '@/lib/service'; +import { helpRequestService } from '@/lib/service'; import { Database } from '@/types/database'; import { Enums } from '@/types/common'; import { useRouter } from 'next/navigation'; import { TIPOS_DE_AYUDA, TIPOS_DE_AYUDA_MAP } from '../constants'; import { useSession } from '@/context/SessionProvider'; -import { LngLat } from '@/components/map/GeolocationMap'; const mapHelpToEnum = (helpTypeMap: FormData['tiposDeAyuda']): Enums['help_type_enum'][] => Array.from(helpTypeMap).reduce( @@ -34,7 +33,8 @@ export function FormContainer() { const session = useSession(); const [formData, setFormData] = useState({ - nombre: session?.user?.user_metadata?.full_name || '', + nombre: session?.user?.user_metadata?.full_name.split(" ")[0]|| '', + ubicacion: '', coordinates: null, tiposDeAyuda: new Map(TIPOS_DE_AYUDA.map(({ id }) => [id, false])), numeroDePersonas: undefined, @@ -43,9 +43,18 @@ export function FormContainer() { situacionEspecial: '', contacto: session?.user?.user_metadata?.telefono || '', consentimiento: false, + pueblo: '', email: session?.user?.user_metadata?.email || '', }); + useEffect(() => { + console.log('Component mounted'); + }, []); + + useEffect(() => { + console.log('formData changed: ', formData); + }, [formData]); + const [status, setStatus] = useState({ isSubmitting: false, error: null, @@ -57,8 +66,8 @@ export function FormContainer() { e.preventDefault(); /* Form validation */ - if (!formData.coordinates) { - alert('Elige una ubicacion valida'); + if (!formData.ubicacion) { + alert('La ubicación es un campo obligatorio'); return; } @@ -80,20 +89,12 @@ export function FormContainer() { setStatus({ isSubmitting: true, error: null, success: false }); try { - const latitude = String(formData.coordinates.lat); - const longitude = String(formData.coordinates.lng); - - const { address, town } = await locationService.getFormattedAddress(longitude, latitude); - - const { data: townResponse, error: townError } = await townService.createIfNotExists(town); - if (townError) throw townError; - const helpRequestData: Database['public']['Tables']['help_requests']['Insert'] = { type: 'necesita', - name: formData.nombre, - location: address, - latitude: formData.coordinates ? parseFloat(latitude) : null, - longitude: formData.coordinates ? parseFloat(longitude) : null, + name: formData.nombre.split(" ")[0], + location: formData.ubicacion, + latitude: formData.coordinates ? parseFloat(formData.coordinates.lat) : null, + longitude: formData.coordinates ? parseFloat(formData.coordinates.lng) : null, help_type: mapHelpToEnum(formData.tiposDeAyuda), description: formData.descripcion, urgency: formData.urgencia, @@ -104,7 +105,7 @@ export function FormContainer() { consent: true, email: formData.email, }, - town_id: townResponse[0].id, + town_id: parseInt(formData.pueblo), status: 'active', }; @@ -113,6 +114,7 @@ export function FormContainer() { // Limpiar formulario setFormData({ nombre: '', + ubicacion: '', coordinates: null, tiposDeAyuda: new Map(), numeroDePersonas: undefined, @@ -120,6 +122,7 @@ export function FormContainer() { urgencia: 'alta', situacionEspecial: '', contacto: '', + pueblo: '', consentimiento: false, email: '', }); @@ -163,11 +166,18 @@ export function FormContainer() { })); }, []); - const handleCoordinatesChange = useCallback((lngLat: LngLat) => { + const handleAddressSelection = useCallback((address: any) => { setFormData((formData) => ({ ...formData, - coordinates: lngLat ?? null, + ubicacion: address.fullAddress, + coordinates: address.coordinates + ? { + lat: address.coordinates.lat, + lng: address.coordinates.lon, + } + : null, })); + console.log('address: ', address); }, []); const handlePhoneChange = useCallback((phoneNumber: string) => { @@ -200,13 +210,14 @@ export function FormContainer() { isUserLoggedIn={Boolean(session?.user)} handleConsentChange={handleInputElementChange} handleEmailChange={handleInputElementChange} - handleCoordinatesChange={handleCoordinatesChange} + handleAddressSelection={handleAddressSelection} handleDescriptionChange={handleTextAreaElementChange} handleNameChange={handleInputElementChange} handleNumberPeopleChange={handleInputElementChange} handlePhoneChange={handlePhoneChange} handleSituacionEspecialChange={handleTextAreaElementChange} handleTipoAyudaChange={handleHelpTypeChange} + handleTownChange={handleSelectElementChange} handleUrgencyChange={handleSelectElementChange} handleSubmit={handleSubmit} status={status} diff --git a/src/app/solicitar-ayuda/_components/Form/FormRenderer.tsx b/src/app/solicitar-ayuda/_components/Form/FormRenderer.tsx index 1daba848..e0196b30 100644 --- a/src/app/solicitar-ayuda/_components/Form/FormRenderer.tsx +++ b/src/app/solicitar-ayuda/_components/Form/FormRenderer.tsx @@ -3,11 +3,11 @@ import React from 'react'; import { Check } from 'lucide-react'; import { PhoneInput } from '@/components/PhoneInput'; +import AddressAutocomplete from '@/components/AddressAutocomplete.js'; import { TIPOS_DE_AYUDA } from '../constants'; import { TipoDeAyudaInputRenderer } from '../TipoDeAyudaInputRenderer'; import { FormData, HelpCategory, Status } from '../types'; -import AddressMap from '../../../../components/AddressMap'; -import { LngLat } from '@/components/map/GeolocationMap'; +import { TownSelector } from '../TownSelector'; type FormRendererProps = { status: Status; @@ -16,10 +16,11 @@ type FormRendererProps = { selectedHelp: Map; handleSubmit: React.FormEventHandler; handlePhoneChange: (phoneNumber: string) => void; - handleCoordinatesChange: (lngLat: LngLat) => void; + handleAddressSelection: (address: string) => void; handleSituacionEspecialChange: React.ChangeEventHandler; handleUrgencyChange: React.ChangeEventHandler; handleDescriptionChange: React.ChangeEventHandler; + handleTownChange: React.ChangeEventHandler; handleTipoAyudaChange: React.ChangeEventHandler; handleNameChange: React.ChangeEventHandler; handleEmailChange: React.ChangeEventHandler; @@ -33,10 +34,11 @@ export function FormRenderer({ formData, isUserLoggedIn, handlePhoneChange, - handleCoordinatesChange, + handleAddressSelection, handleSituacionEspecialChange, handleUrgencyChange, handleDescriptionChange, + handleTownChange, handleTipoAyudaChange, handleNameChange, handleEmailChange, @@ -82,11 +84,23 @@ export function FormRenderer({ className="w-full p-2 border rounded focus:ring-2 focus:ring-green-500 focus:border-green-500" />

- {isUserLoggedIn - ? 'Se utilizará para que puedas eliminar o editar la información de tu solicitud' + {isUserLoggedIn ? 'Se utilizará para que puedas eliminar o editar la información de tu solicitud' : 'Se utilizará para que puedas actualizar tu solicitud y marcarla como completada. Para realizar cambios, deberás registrarte con el mismo email'}

+
+ + +

+ Incluya todos los detalles posibles para poder localizarle (campo obligatorio) +

+
@@ -152,13 +166,8 @@ export function FormRenderer({ placeholder="Personas mayores, niños pequeños, personas con movilidad reducida, necesidades médicas, mascotas..." />
- -
- - -
+ {/* Pueblos */} + {/* Consentimiento */}
diff --git a/src/app/solicitar-ayuda/_components/types.ts b/src/app/solicitar-ayuda/_components/types.ts index 4a6b1391..94bb4470 100644 --- a/src/app/solicitar-ayuda/_components/types.ts +++ b/src/app/solicitar-ayuda/_components/types.ts @@ -1,6 +1,5 @@ import { Town as SupabaseTown } from '@/types/Town'; import { Enums } from '@/types/common'; -import { LngLat } from '@/components/map/GeolocationMap'; export type FormData = { nombre: string; @@ -10,8 +9,10 @@ export type FormData = { descripcion: string; urgencia: string; situacionEspecial: string; + pueblo: string; consentimiento: boolean; - coordinates: LngLat | null; + ubicacion: string; + coordinates: any; tiposDeAyuda: Map; }; diff --git a/src/components/AddressMap.tsx b/src/components/AddressMap.tsx index 605d238c..d0b4de94 100644 --- a/src/components/AddressMap.tsx +++ b/src/components/AddressMap.tsx @@ -1,29 +1,49 @@ 'use client'; import GeoLocationMap, { LngLat } from '@/components/map/GeolocationMap'; -import { useEffect, useState } from 'react'; +import { useState } from 'react'; +export type AddressDescriptopr = { address: string; town: string; coordinates: LngLat }; +export type AddressAndTownCallback = (addressAndTown: AddressDescriptopr) => void; export type AddressMapProps = { - onNewCoordinatesCallback: (lngLat: LngLat) => void; + onNewAddressCallback: AddressAndTownCallback; }; -export default function AddressMap({ onNewCoordinatesCallback }: AddressMapProps) { - const [status, setStatus] = useState('unknown'); +export default function AddressMap({ onNewAddressCallback }: AddressMapProps) { + const [address, setAddress] = useState(''); + const [town, setTown] = useState(''); + + const onNewPosition = async (lngLat: LngLat) => { + if (address !== '') { + return; + } + + const response = await fetch('/api/address', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + longitude: lngLat.lng, + latitude: lngLat.lat, + }), + }).then((res) => res.json()); + + setAddress(response.address); + setTown(response.town); + if (typeof onNewAddressCallback === 'function') { + onNewAddressCallback({ address: response.address, town: response.town, coordinates: lngLat }); + } + }; return (
- {/* Mensaje de error */} - {(status === 'denied' || status === 'prompt') && ( -
-

Debes activar la ubicación para que podamos localizarte

-
- )} - { - setStatus(permission); - }} - onNewPositionCallback={(lngLat) => {}} - onNewCenterCallback={onNewCoordinatesCallback} + + {/* Address */} + setAddress(e.target.value)} + className="w-full p-2 border rounded focus:ring-2 focus:ring-green-500 focus:border-green-500" />
); diff --git a/src/components/RequestHelp.js b/src/components/RequestHelp.js index bd0f1ce0..0e861d76 100644 --- a/src/components/RequestHelp.js +++ b/src/components/RequestHelp.js @@ -5,14 +5,13 @@ import { AlertTriangle, Check, Mail } from 'lucide-react'; import AddressAutocomplete from '@/components/AddressAutocomplete'; import { mapToIdAndLabel, tiposAyudaOptions } from '@/helpers/constants'; import { formatPhoneNumber, isValidPhone } from '@/helpers/utils'; -import { helpRequestService, locationService, townService } from '@/lib/service'; +import { helpRequestService } from '@/lib/service'; import { PhoneInput } from '@/components/PhoneInput'; import Image from 'next/image'; import { useRouter } from 'next/navigation'; import { useTowns } from '../context/TownProvider'; import { CallCenterLink } from '@/components/CallCenterLink'; -import AddressMap from './AddressMap'; export default function RequestHelp({ data = {}, @@ -58,9 +57,8 @@ export default function RequestHelp({ const handleSubmit = async (e) => { e.preventDefault(); - /* Form validation */ - if (!formData.coordinates) { - alert('Elige una ubicacion valida'); + if (!formData.ubicacion) { + alert('La ubicación es un campo obligatorio'); return; } @@ -77,25 +75,12 @@ export default function RequestHelp({ setStatus({ isSubmitting: true, error: null, success: false }); try { - const latitude = String(formData.coordinates.lat); - const longitude = String(formData.coordinates.lng); - - debugger; - - const { address, town } = await locationService.getFormattedAddress(longitude, latitude); - if (!address || !town) { - throw { error: 'Error inesperado con la api de google' }; - } - - const { data: townResponse, error: townError } = await townService.createIfNotExists(town); - if (townError) throw townError; - const helpRequestData = { type: 'necesita', name: formData.nombre, - location: address, - latitude, - longitude, + location: formData.ubicacion, + latitude: formData.coordinates ? parseFloat(formData.coordinates.lat) : 3, + longitude: formData.coordinates ? parseFloat(formData.coordinates.lng) : 3, help_type: formData.tiposAyuda, description: formData.descripcion, urgency: formData.urgencia, @@ -106,7 +91,7 @@ export default function RequestHelp({ consent: true, email: formData.email, }, - town_id: townResponse[0].id, + town_id: formData.pueblo, status: formData.status, }; if (submitType === 'create') { @@ -116,6 +101,7 @@ export default function RequestHelp({ } } if (submitType === 'edit') { + console.log('EDITAR'); const { error } = await helpRequestService.editRequest(helpRequestData, id); if (error) { throw new Error(error.message); @@ -274,6 +260,31 @@ export default function RequestHelp({
)} +
+ + { + setFormData({ + ...formData, + ubicacion: address.fullAddress, + coordinates: address.coordinates + ? { + lat: address.coordinates.lat, + lng: address.coordinates.lon, + } + : null, + }); + }} + placeholder="Calle, número, piso, ciudad..." + required + /> +

+ Incluya todos los detalles posibles para poder localizarle (campo obligatorio) +

+
@@ -346,21 +357,35 @@ export default function RequestHelp({ placeholder="Personas mayores, niños pequeños, personas con movilidad reducida, necesidades médicas, mascotas..." />
- {/* Mapa */} + {/* Pueblos */}
- - { - setFormData((prev) => ({ - ...prev, - coordinates: lngLat, - })); - }} - /> + +
- {/* Consentimiento */}