Skip to content

Commit

Permalink
refactor: remove unnecessary info in the forms
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinx0 committed Nov 9, 2024
1 parent 8e0cb31 commit caeb052
Show file tree
Hide file tree
Showing 8 changed files with 206 additions and 212 deletions.
11 changes: 0 additions & 11 deletions src/app/solicitar-ayuda/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,6 @@ export default function SolicitarAyuda() {
return (
<div className="space-y-6">
{/* Banner de emergencia */}
<div className="bg-red-100 border-l-4 border-red-500 p-4 rounded">
<div className="flex items-start">
<AlertTriangle className="h-5 w-5 text-red-500 mt-0.5 mr-2" />
<div>
<h2 className="text-red-800 font-bold">EMERGENCIA ACTIVA - Inundaciones CV</h2>
<p className="text-red-700 text-sm mt-1">
Para emergencias médicas inmediatas, llame al 112. Este formulario es para coordinar ayuda y asistencia.
</p>
</div>
</div>
</div>
<div className="bg-red-100 border-l-4 border-red-500 p-4 rounded">
<div className="flex items-start">
<AlertTriangle className="h-5 w-5 text-red-500 mt-0.5 mr-2" />
Expand Down
2 changes: 1 addition & 1 deletion src/components/AddressMap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const THROTTLE_MS = 2000;
const DEBOUNCE_MS = 400;

export default function AddressMap({ onNewAddressDescriptor, initialAddressDescriptor, titulo }: AddressMapProps) {
const isEdit = useRef(Boolean(initialAddressDescriptor));
const isEdit = useRef(initialAddressDescriptor?.address !== '');
const [status, setStatus] = useState<PermissionState | 'unknown'>('unknown');
const [lngLat, setLngLat] = useState<LngLat | undefined>(initialAddressDescriptor?.coordinates ?? undefined);
const [addressDescriptor, setAddressDescriptor] = useState<AddressDescriptor>({
Expand Down
35 changes: 28 additions & 7 deletions src/components/HelpOffers/CreateHelpOffer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import { HelpRequestInsert } from '@/types/Requests';
import { useSession } from '@/context/SessionProvider';
import { User } from '@supabase/auth-js';
import { HeartHandshake } from 'lucide-react';

function formToDatabaseMap(userId: string | null, formData: HelpOfferFormData): HelpRequestInsert {
function formToDatabaseMap(user: User, formData: HelpOfferFormData): HelpRequestInsert {
return {
description: formData.comentarios,
resources: {
Expand All @@ -17,7 +19,7 @@ function formToDatabaseMap(userId: string | null, formData: HelpOfferFormData):
availability: formData.disponibilidad,
},
town_id: formData.pueblo,
user_id: userId,
user_id: user.id,
type: 'ofrece',
other_help: formData.otraAyuda,
help_type: formData.tiposAyuda,
Expand All @@ -26,7 +28,7 @@ function formToDatabaseMap(userId: string | null, formData: HelpOfferFormData):
name: formData.nombre,
contact_info: formData.telefono,
additional_info: {
email: formData.email,
email: user.email || user.user_metadata?.email,
experience: formData.experiencia,
},
};
Expand All @@ -35,11 +37,13 @@ function formToDatabaseMap(userId: string | null, formData: HelpOfferFormData):
export default function CreateHelpOffer() {
const queryClient = useQueryClient();
const router = useRouter();
const session = useSession();
const { user } = useSession();

const mutation = useMutation({
mutationFn: (data: HelpOfferFormData) =>
helpRequestService.createRequest(formToDatabaseMap(session.user?.id ?? null, data)),
mutationFn: (data: HelpOfferFormData) => {
if (!user) throw 'Sesión no iniciada';
return helpRequestService.createRequest(formToDatabaseMap(user, data));
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['help_requests'] });
router.push('/casos-activos/ofertas');
Expand All @@ -50,5 +54,22 @@ export default function CreateHelpOffer() {
},
});

return <HelpOfferForm submitMutation={mutation.mutateAsync} buttonText={['Ofrecer ayuda', 'Enviando...']} />;
return (
<div className="space-y-6 bg-white rounded-lg shadow-lg p-6">
<h1 className="text-2xl font-bold mb-6">Ofrecer ayuda</h1>
<div className="bg-green-50 border-green-500 p-4 rounded">
<div className="flex items-start">
<HeartHandshake className="h-5 w-5 text-green-500 mt-0.5 mr-2" />
<div>
<h2 className="text-green-800 font-semibold">Me apunto como voluntario</h2>
<p className="text-green-700 text-sm mt-1">
Al registrarte como voluntario, te comprometes a seguir las indicaciones de las autoridades y los
protocolos establecidos.
</p>
</div>
</div>
</div>
<HelpOfferForm submitMutation={mutation.mutateAsync} buttonText={['Ofrecer ayuda', 'Enviando...']} />
</div>
);
}
7 changes: 2 additions & 5 deletions src/components/HelpOffers/EditHelpOffer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function formToDatabaseMap(request: HelpRequestData, formData: HelpOfferFormData
name: formData.nombre,
contact_info: formData.telefono,
additional_info: {
email: formData.email,
email: request.additional_info.email,
experience: formData.experiencia,
},
};
Expand All @@ -54,10 +54,7 @@ export default function EditHelpOffer({ request }: EditHelpOfferProps) {
});
return (
<HelpOfferForm
data={{
...request,
coordinates: { lat: (request.latitude ?? 0)?.toString(), lng: (request.longitude ?? 0)?.toString() },
}}
data={request}
submitMutation={mutation.mutateAsync}
buttonText={['Guardar cambios', 'Guardando...']}
/>
Expand Down
11 changes: 6 additions & 5 deletions src/components/HelpOffers/HelpOfferForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import { HelpRequestData, HelpRequestHelpType } from '@/types/Requests';
import { useSession } from '@/context/SessionProvider';
import { tiposAyudaArray } from '@/helpers/constants';
import { Town } from '@/types/Town';
import Unauthorized from '@/components/Unauthorized';

export type HelpOfferFormData = {
aceptaProtocolo: boolean;
nombre: string;
telefono: string;
email: string;
ubicacion: string;
tiposAyuda: HelpRequestHelpType[];
otraAyuda: string;
Expand All @@ -32,12 +32,11 @@ export interface HelpOfferProps {
}

export default function HelpOfferForm({ town, data, buttonText, submitMutation }: HelpOfferProps) {
const session = useSession();
const { user } = useSession();

const [formData, setFormData] = useState<HelpOfferFormData>({
nombre: data?.name || session?.user?.user_metadata?.full_name || '',
telefono: data?.contact_info || session?.user?.user_metadata?.telefono || '',
email: data?.additional_info?.email || session?.user?.user_metadata?.email || '',
nombre: data?.name || user?.user_metadata?.full_name || user?.user_metadata?.nombre || '',
telefono: data?.contact_info || user?.user_metadata?.telefono || '',
ubicacion: data?.location || '',
tiposAyuda: data?.help_type || [],
otraAyuda: data?.other_help || '',
Expand Down Expand Up @@ -81,6 +80,8 @@ export default function HelpOfferForm({ town, data, buttonText, submitMutation }
await submitMutation(formData);
};

if (!user) return <Unauthorized />;

return (
<form onSubmit={handleSubmit} className="bg-white rounded-lg p-6 w-full">
{/* Datos personales */}
Expand Down
18 changes: 9 additions & 9 deletions src/components/HelpRequests/CreateHelpRequest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,16 @@ import { toast } from 'sonner';
import { useRouter } from 'next/navigation';
import { HelpRequestInsert } from '@/types/Requests';
import { useSession } from '@/context/SessionProvider';
import { User } from '@supabase/auth-js';

function formToDatabaseMap(userId: string | null, formData: HelpRequestFormData): HelpRequestInsert {
function formToDatabaseMap(user: User, formData: HelpRequestFormData): HelpRequestInsert {
return {
description: formData.descripcion,
resources: null,
urgency: formData.urgencia,
number_of_people: formData.numeroPersonas,
town_id: formData.town_id,
user_id: userId,
user_id: user.id,
type: 'necesita',
help_type: formData.tiposAyuda,
latitude: formData.coordinates?.lat,
Expand All @@ -25,7 +26,7 @@ function formToDatabaseMap(userId: string | null, formData: HelpRequestFormData)
name: formData.nombre,
contact_info: formData.telefono,
additional_info: {
email: formData.email,
email: user.email || user.user_metadata?.email,
consent: formData.consentimiento,
special_situations: formData.situacionEspecial,
},
Expand All @@ -35,20 +36,19 @@ function formToDatabaseMap(userId: string | null, formData: HelpRequestFormData)
export default function CreateHelpRequest() {
const queryClient = useQueryClient();
const router = useRouter();
const session = useSession();
const { user } = useSession();

const mutation = useMutation({
mutationFn: async (data: HelpRequestFormData) => {
if (!user) throw 'Sesión no iniciada';
let town_id = data.town_id;
if (data.pueblo !== '') {
const { data: townResponse, error: townError } = await townService.createIfNotExists(data.pueblo);
if (townError) throw townError;
town_id = townResponse[0].id;
}

return helpRequestService.createRequest(
formToDatabaseMap(session.user?.id ?? null, { ...data, town_id: town_id }),
);
return helpRequestService.createRequest(formToDatabaseMap(user, { ...data, town_id: town_id }));
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['help_requests'] });
Expand All @@ -61,13 +61,13 @@ export default function CreateHelpRequest() {
});

return (
<>
<div className="space-y-6 bg-white rounded-lg shadow-lg p-6">
<h1 className="text-2xl font-bold mb-6">Solicitar ayuda</h1>
<HelpRequestForm
submitMutation={mutation.mutateAsync}
isSubmitting={mutation.isPending}
buttonText={['Enviar solicitud', 'Enviando solicitud...']}
/>
</>
</div>
);
}
8 changes: 6 additions & 2 deletions src/components/HelpRequests/EditHelpRequest.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -63,13 +63,17 @@ export default function EditHelpRequest({ request }: EditHelpRequestProps) {
});

return (
<>
<div className="space-y-6 bg-white rounded-lg shadow-lg p-6">
<h1 className="text-2xl font-bold mb-6">Editar solicitud de ayuda</h1>
<HelpRequestForm
request={{
...request,
coordinates: { lat: (request.latitude ?? 0)?.toString(), lng: (request.longitude ?? 0)?.toString() },
}}
submitMutation={mutation.mutateAsync}
isSubmitting={mutation.isPending}
buttonText={['Guardar cambios', 'Guardando...']}
/>
</>
</div>
);
}
Loading

0 comments on commit caeb052

Please sign in to comment.