+ {isMyOffer && showEdit && (
+
+ Editar
+
+ )}
{showLink && (
{
- setFormData((prev) => ({
- ...prev,
- tiposAyuda: prev.tiposAyuda.includes(tipo)
- ? prev.tiposAyuda.filter((t) => t !== tipo)
- : [...prev.tiposAyuda, tipo],
- }));
- };
-
- const handleDisponibilidadChange = (dia) => {
- setFormData((prev) => ({
- ...prev,
- disponibilidad: prev.disponibilidad.includes(dia)
- ? prev.disponibilidad.filter((d) => d !== dia)
- : [...prev.disponibilidad, dia],
- }));
- };
-
- const handlePhoneChange = useCallback((phoneNumber) => {
- setFormData((formData) => ({ ...formData, telefono: phoneNumber }));
- }, []);
-
- const handleSubmit = async (e) => {
- e.preventDefault();
-
- // Form validation
- if (!formData.ubicacion) {
- alert('La ubicación es obligatoria');
- return;
- }
-
- if (!formData.aceptaProtocolo) {
- alert('Debes aceptar el protocolo de actuación');
- return;
- }
-
- if (!isValidPhone(formData.telefono)) {
- alert('El teléfono de contacto no es válido.');
- return;
- }
-
- setStatus({ isSubmitting: true, error: null, success: false });
-
- try {
- const helpOfferData = {
- type: 'ofrece',
- name: formData.nombre,
- location: formData.ubicacion,
- description: formData.comentarios,
- contact_info: formatPhoneNumber(formData.telefono),
- additional_info: {
- email: formData.email,
- experience: formData.experiencia,
- },
- resources: {
- vehicle: formData.vehiculo,
- availability: formData.disponibilidad,
- radius: formData.radio,
- },
- latitude: formData.coordinates ? parseFloat(formData.coordinates.lat) : null,
- longitude: formData.coordinates ? parseFloat(formData.coordinates.lng) : null,
- help_type: formData.tiposAyuda,
- other_help: formData.otraAyuda,
- town_id: formData.pueblo,
- status: formData.status || 'active',
- user_id: userId,
- };
-
- if (submitType === 'create') {
- const { error } = await helpRequestService.createRequest(helpOfferData);
- if (error) {
- throw new Error(error.message);
- }
- }
- if (submitType === 'edit') {
- console.log('EDITAR');
- const { error } = await helpRequestService.editRequest(helpOfferData, id);
- if (error) {
- throw new Error(error.message);
- }
- }
-
- setFormData({
- nombre: '',
- telefono: '',
- email: '',
- ubicacion: '',
- tiposAyuda: [],
- otraAyuda: '',
- vehiculo: '',
- disponibilidad: [],
- radio: 1,
- experiencia: '',
- comentarios: '',
- aceptaProtocolo: false,
- pueblo: '',
- status: 'active',
- });
- setStatus({ isSubmitting: false, error: null, success: true });
- setStatus((prev) => ({ ...prev, success: false }));
- router.push(redirect);
- } catch (error) {
- console.error('Error al registrar oferta de ayuda:', error);
- setStatus({
- isSubmitting: false,
- error: `Error al registrar tu oferta de ayuda: ${error.message || 'Error desconocido'}`,
- success: false,
- });
- }
- };
-
- return (
-
- );
-}
diff --git a/src/components/RequestHelp.js b/src/components/RequestHelp.js
deleted file mode 100644
index b96f1112..00000000
--- a/src/components/RequestHelp.js
+++ /dev/null
@@ -1,364 +0,0 @@
-'use client';
-
-import { useCallback, useState } from 'react';
-import { 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 { PhoneInput } from '@/components/input/PhoneInput';
-import { useRouter } from 'next/navigation';
-import { CallCenterLink } from '@/components/CallCenterLink';
-import AddressMap from './AddressMap';
-import { useTowns } from '@/context/TownProvider';
-import { useSession } from '@/context/SessionProvider';
-
-export default function RequestHelp({
- data = {},
- title = 'Solicitar Ayuda',
- button = ['Enviar solicitud de ayuda', 'Enviando solicitud...'],
- submitType = 'create',
- id,
- redirect = '/casos-activos/solicitudes',
-}) {
- const { towns } = useTowns();
- const router = useRouter();
- const session = useSession();
- const userId = session.user?.id;
- const [formData, setFormData] = useState({
- nombre: data.name || '',
- ubicacion: data.location || '',
- coordinates: { lat: data.latitude || 3, lng: data.longitude || 3 },
- tiposAyuda: data.help_type || [],
- numeroPersonas: data.number_of_people || '',
- descripcion: data.description || '',
- urgencia: data.urgency || 'alta',
- situacionEspecial: data.additional_info?.special_situations || '',
- contacto: data.contact_info || '',
- consentimiento: data.additional_info?.consent || false,
- pueblo: '',
- town_id: data.town_id || '',
- email: data.additional_info?.email || '',
- status: data.status || 'active',
- });
-
- const [status, setStatus] = useState({
- isSubmitting: false,
- error: null,
- success: false,
- });
-
- const handleTipoAyudaChange = (tipo) => {
- setFormData((prev) => ({
- ...prev,
- tiposAyuda: prev.tiposAyuda.includes(tipo)
- ? prev.tiposAyuda.filter((t) => t !== tipo)
- : [...prev.tiposAyuda, tipo],
- }));
- };
-
- const handleSubmit = async (e) => {
- e.preventDefault();
-
- /* Form validation */
- if (!formData.coordinates) {
- alert('Elige una ubicacion valida');
- return;
- }
-
- if (!formData.consentimiento) {
- alert('Debe aceptar el consentimiento para enviar la solicitud');
- return;
- }
-
- if (!isValidPhone(formData.contacto)) {
- alert('El teléfono de contacto no es válido. Si has usado espacios, elimínalos.');
- return;
- }
-
- setStatus({ isSubmitting: true, error: null, success: false });
-
- try {
- const latitude = String(formData.coordinates.lat);
- const longitude = String(formData.coordinates.lng);
- let town_id = formData.town_id;
-
- if (formData.pueblo !== '') {
- const { data: townResponse, error: townError } = await townService.createIfNotExists(formData.pueblo);
- if (townError) throw townError;
- town_id = townResponse[0].id;
- }
-
- const helpRequestData = {
- type: 'necesita',
- name: formData.nombre,
- location: formData.ubicacion,
- latitude,
- longitude,
- help_type: formData.tiposAyuda,
- description: formData.descripcion,
- urgency: formData.urgencia,
- number_of_people: parseInt(formData.numeroPersonas) || 1,
- contact_info: formatPhoneNumber(formData.contacto),
- additional_info: {
- special_situations: formData.situacionEspecial || null,
- consent: true,
- email: formData.email,
- },
- town_id,
- status: formData.status,
- user_id: userId,
- };
- if (submitType === 'create') {
- const { error } = await helpRequestService.createRequest(helpRequestData);
- if (error) {
- throw new Error(error.message);
- }
- }
- if (submitType === 'edit') {
- const { error } = await helpRequestService.editRequest(helpRequestData, id);
- if (error) {
- throw new Error(error.message);
- }
- }
-
- setFormData({
- nombre: '',
- ubicacion: '',
- coordinates: { lat: null, lng: null },
- tiposAyuda: [],
- numeroPersonas: '',
- descripcion: '',
- urgencia: 'alta',
- situacionEspecial: '',
- contacto: '',
- pueblo: '',
- email: '',
- consentimiento: false,
- status: 'active',
- });
-
- setStatus({ isSubmitting: false, error: null, success: true });
- setStatus((prev) => ({ ...prev, success: false }));
- router.push(redirect);
- } catch (error) {
- console.error('Error al enviar solicitud:', error.message);
- setStatus({
- isSubmitting: false,
- error: `Error al enviar la solicitud: ${error.message}`,
- success: false,
- });
- }
- };
-
- const handleOnNewAddressDescriptor = (addressDescriptor) => {
- setFormData((prev) => ({
- ...prev,
- coordinates: addressDescriptor.coordinates,
- pueblo: addressDescriptor.town,
- ubicacion: addressDescriptor.address,
- }));
- };
-
- const handleChange = (e) => {
- const { name, value, type, checked } = e.target;
- setFormData((prev) => ({
- ...prev,
- [name]: type === 'checkbox' ? checked : value || '',
- }));
- };
-
- const handlePhoneChange = useCallback((e) => {
- setFormData((formData) => ({ ...formData, contacto: e.target.value }));
- }, []);
-
- return (
-
- {status.error && (
-
- )}
-
- {/* Formulario principal */}
-
-
{title}
-
-
-
-
- Nombre completo
-
-
-
-
- {submitType === 'create' && (
-
-
- Correo electrónico *
-
-
-
- Se utilizara para que puedas eliminar o editar la información de tu solicitud
-
-
- )}
- {submitType === 'edit' && (
-
-
- Progreso de tu solicitud
-
-
- Activa - Aún no recibo ayuda
- En progreso - Están viniendo a ayudarme
- Terminada - Ya me han ayudado
-
-
- )}
-
-
-
Tipo de ayuda necesaria
-
- {mapToIdAndLabel(tiposAyudaOptions).map((tipo) => (
-
- handleTipoAyudaChange(tipo.id)}
- className="h-4 w-4 text-red-600 focus:ring-red-500 border-gray-300 rounded"
- />
- {tipo.label}
-
- ))}
-
-
-
-
- Número de personas afectadas
-
-
-
-
- Descripción de la situación
-
-
-
-
- Nivel de urgencia
-
- Alta - Necesito ayuda inmediata
- Media - Puedo esperar unas horas
- Baja - No es urgente
-
-
-
-
- Situaciones especiales
-
-
- {/* Mapa */}
-
-
- {/* Consentimiento */}
-
-
-
- Doy mi consentimiento para el tratamiento de los datos proporcionados y confirmo que la información
- proporcionada es verídica.
-
-
-
-
- {status.isSubmitting ? button[1] : button[0]}
-
-
-
-
- {status.success && (
-
-
-
-
-
Su solicitud de ayuda ha sido registrada correctamente.
-
- Se está coordinando la ayuda. En caso de empeorar la situación, contacte al 112.
-
-
-
-
- )}
-
- );
-}
diff --git a/src/components/auth/SocialButton.tsx b/src/components/auth/SocialButton.tsx
index 5b43792b..1f79a4e2 100644
--- a/src/components/auth/SocialButton.tsx
+++ b/src/components/auth/SocialButton.tsx
@@ -11,7 +11,6 @@ type SocialButtonProps = {
export default function SocialButton({ provider, redirectUrl, children }: SocialButtonProps) {
const baseUrl =
process.env.NEXT_PUBLIC_ENV === 'production' ? process.env.NEXT_PUBLIC_BASE_URL! : 'http://127.0.0.1:3000';
- console.log(baseUrl + redirectUrl);
const handleLogin = async (provider: Provider) => {
const { data, error } = await supabase.auth.signInWithOAuth({
provider,
diff --git a/src/components/input/PhoneInput/PhoneInputContainer.tsx b/src/components/input/PhoneInput/PhoneInputContainer.tsx
index 92904220..46e49bc9 100644
--- a/src/components/input/PhoneInput/PhoneInputContainer.tsx
+++ b/src/components/input/PhoneInput/PhoneInputContainer.tsx
@@ -6,7 +6,7 @@ import { PhoneInputRenderer } from './PhoneInputRenderer';
import { PhoneInputProps } from './types';
import { isValidPhone } from '@/helpers/utils';
-export function PhoneInputContainer({ onChange, phoneNumber, required = false }: PhoneInputProps) {
+export function PhoneInput({ onChange, phoneNumber, required = false }: PhoneInputProps) {
const [isInvalid, setIsInvalid] = useState(false);
const handleChange: PhoneInputProps['onChange'] = useCallback(
diff --git a/src/components/input/PhoneInput/index.ts b/src/components/input/PhoneInput/index.ts
index a2f76067..7499bd42 100644
--- a/src/components/input/PhoneInput/index.ts
+++ b/src/components/input/PhoneInput/index.ts
@@ -1,3 +1,3 @@
-import { PhoneInputContainer as PhoneInput } from './PhoneInputContainer';
+import { PhoneInput } from './PhoneInputContainer';
export { PhoneInput };
diff --git a/src/components/layout/Sidebar.tsx b/src/components/layout/Sidebar.tsx
index 212bcb3a..e161d0b9 100644
--- a/src/components/layout/Sidebar.tsx
+++ b/src/components/layout/Sidebar.tsx
@@ -15,11 +15,9 @@ import {
Thermometer,
Truck,
Inbox,
- Car,
Landmark,
Scale,
MessageCircleQuestion,
- CarTaxiFront,
} from 'lucide-react';
import UserInfo from '../UserInfo';
import { useSession } from '@/context/SessionProvider';
@@ -251,8 +249,7 @@ export default function Sidebar({ isOpen, toggleAction }: SidebarProps) {
{/* Toggle button for desktop */}
diff --git a/src/components/map/map.tsx b/src/components/map/map.tsx
index dd115b84..55789cb5 100644
--- a/src/components/map/map.tsx
+++ b/src/components/map/map.tsx
@@ -37,7 +37,6 @@ const Map: FC = ({ markers = [] }) => {
const { toggleModal } = useModal();
- console.log(selectedMarker);
return (
{
- return Object.keys(data).map((key) => ({
- id: key,
- label: data[key],
- }));
-};
+interface TipoAyudaOption {
+ id: TipoAyudaId;
+ label: TipoAyudaLabel;
+}
+
+export const tiposAyudaArray: TipoAyudaOption[] = Object.entries(tiposAyudaOptions).map(([id, label]) => ({
+ id: id as TipoAyudaId,
+ label,
+}));
diff --git a/src/lib/service.ts b/src/lib/service.ts
index 4064a24c..6ae341cd 100644
--- a/src/lib/service.ts
+++ b/src/lib/service.ts
@@ -1,19 +1,18 @@
import { supabase } from './supabase/client';
-import { Database } from '@/types/database';
-import { HelpRequestAssignmentInsert, HelpRequestUpdate } from '@/types/Requests';
+import { HelpRequestAssignmentInsert, HelpRequestData, HelpRequestInsert, HelpRequestUpdate } from '@/types/Requests';
import { createClient } from '@/lib/supabase/server';
export const helpRequestService = {
- async createRequest(requestData: Database['public']['Tables']['help_requests']['Insert']) {
+ async createRequest(requestData: HelpRequestInsert) {
const { data, error } = await supabase.from('help_requests').insert([requestData]).select();
if (error) throw error;
- return data[0];
+ return data[0] as HelpRequestData;
},
async editRequest(requestData: HelpRequestUpdate, id: number) {
const { data, error } = await supabase.from('help_requests').update(requestData).eq('id', id).select();
if (error) throw error;
- return data;
+ return data[0] as HelpRequestData;
},
async getAll() {
const { data, error } = await supabase.from('help_requests').select('*').order('created_at', { ascending: false });
@@ -25,7 +24,7 @@ export const helpRequestService = {
const supabase = await getSupabaseClient();
const { data, error } = await supabase.from('help_requests').select('*').eq('id', id).single();
if (error) throw error;
- return data;
+ return data as HelpRequestData;
},
async getRequestsByUser(user_id: string | undefined) {
@@ -42,7 +41,7 @@ export const helpRequestService = {
.eq('type', 'necesita')
.or(`user_id.eq.${user_id},id.in.(${helpRequestIds.join(',')})`);
if (requestsError) throw requestsError;
- return requests;
+ return requests as HelpRequestData[];
},
async getOffersByUser(user_id: string | undefined) {
@@ -53,7 +52,7 @@ export const helpRequestService = {
.eq('type', 'ofrece')
.eq('user_id', user_id);
if (requestsError) throw requestsError;
- return requests;
+ return requests as HelpRequestData[];
},
async getAssignments(id: number) {
diff --git a/src/types/Requests.ts b/src/types/Requests.ts
index 184276ea..1b535722 100644
--- a/src/types/Requests.ts
+++ b/src/types/Requests.ts
@@ -3,12 +3,26 @@ import { Database } from './database';
export type HelpRequestType = 'necesita' | 'ofrece';
export type HelpRequestUrgencyType = 'alta' | 'media' | 'baja';
export type HelpRequestStatusType = 'pending' | 'in_progress' | 'active';
-export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'];
-export type HelpRequestUpdate = Database['public']['Tables']['help_requests']['Update'];
+type HelpRequestJsonFields = {
+ additional_info: HelpRequestAdditionalInfo;
+ resources: HelpRequestResources | null;
+};
+export type HelpRequestHelpType = Database['public']['Enums']['help_type_enum'];
+export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'] & HelpRequestJsonFields;
+export type HelpRequestInsert = Database['public']['Tables']['help_requests']['Insert'] & HelpRequestJsonFields;
+export type HelpRequestUpdate = Database['public']['Tables']['help_requests']['Update'] & HelpRequestJsonFields;
export type HelpRequestAssignmentData = Database['public']['Tables']['help_request_assignments']['Row'];
export type HelpRequestAssignmentInsert = Database['public']['Tables']['help_request_assignments']['Insert'];
export type HelpRequestAdditionalInfo = {
special_situations?: string;
email?: string;
+ experience?: string;
+ consent?: boolean;
+};
+
+export type HelpRequestResources = {
+ radius?: number;
+ vehicle?: string;
+ availability?: string[];
};