Skip to content

Commit

Permalink
feat: refactor componente existente solicitud
Browse files Browse the repository at this point in the history
  • Loading branch information
Roberto Milla Martinez committed Nov 7, 2024
1 parent e78643f commit 74879d4
Show file tree
Hide file tree
Showing 7 changed files with 46 additions and 49 deletions.
73 changes: 35 additions & 38 deletions src/app/solicitar-ayuda/_components/Form/FormContainer.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
'use client';

import React, { useCallback, useEffect, useMemo, useState } from 'react';
import React, { useState, useCallback, useMemo } from 'react';

import { FormRenderer } from './FormRenderer';
import { FormData, Status } from '../types';
import { formatPhoneNumber, isValidPhone } from '@/helpers/utils';
import { helpRequestService } from '@/lib/service';
import { isValidPhone } from '@/helpers/utils';
import { formatPhoneNumber } from '@/helpers/utils';
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';

export type FormResult = Database['public']['Tables']['help_requests']['Insert'];
export type OnSaveResponse = { error: string } | boolean;

const mapHelpToEnum = (helpTypeMap: FormData['tiposDeAyuda']): Enums['help_type_enum'][] =>
Array.from(helpTypeMap).reduce(
(acc, [id, isSelected]) => {
Expand All @@ -28,7 +31,11 @@ const mapHelpToEnum = (helpTypeMap: FormData['tiposDeAyuda']): Enums['help_type_
[] as Enums['help_type_enum'][],
);

export function FormContainer() {
export type FormProps = {
onSave: (formData: FormResult) => Promise<OnSaveResponse>;
};

export default function FormContainer({ onSave }: FormProps) {
const router = useRouter();
const session = useSession();

Expand All @@ -47,14 +54,6 @@ export function FormContainer() {
email: session?.user?.user_metadata?.email || '',
});

useEffect(() => {
console.log('Component mounted');
}, []);

useEffect(() => {
console.log('formData changed: ', formData);
}, [formData]);

const [status, setStatus] = useState<Status>({
isSubmitting: false,
error: null,
Expand Down Expand Up @@ -88,29 +87,28 @@ export function FormContainer() {

setStatus({ isSubmitting: true, error: null, success: false });

try {
const helpRequestData: Database['public']['Tables']['help_requests']['Insert'] = {
type: 'necesita',
name: formData.nombre,
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,
number_of_people: formData.numeroDePersonas || 1,
contact_info: formatPhoneNumber(formData.contacto),
additional_info: {
special_situations: formData.situacionEspecial || null,
consent: true,
email: formData.email,
},
town_id: parseInt(formData.pueblo),
status: 'active',
};

await helpRequestService.createRequest(helpRequestData);

const helpRequestData: Database['public']['Tables']['help_requests']['Insert'] = {
type: 'necesita',
name: formData.nombre,
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,
number_of_people: formData.numeroDePersonas || 1,
contact_info: formatPhoneNumber(formData.contacto),
additional_info: {
special_situations: formData.situacionEspecial || null,
consent: true,
email: formData.email,
},
town_id: parseInt(formData.pueblo),
status: 'active',
};

const saveResponse = await onSave(helpRequestData);
if (typeof saveResponse === 'boolean') {
// Limpiar formulario
setFormData({
nombre: '',
Expand All @@ -130,11 +128,10 @@ export function FormContainer() {
setStatus({ isSubmitting: false, error: null, success: true });
setStatus((prev) => ({ ...prev, success: false }));
router.push('/casos-activos/solicitudes');
} catch (error: any) {
console.log('Error al enviar solicitud:', error.message);
} else {
setStatus({
isSubmitting: false,
error: `Error al enviar la solicitud: ${error.message}`,
error: `Error al enviar la solicitud: ${saveResponse.error}`,
success: false,
});
}
Expand Down
4 changes: 2 additions & 2 deletions src/app/solicitar-ayuda/_components/Form/FormRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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 AddressAutocomplete from '@/components/AddressAutocomplete';
import { TIPOS_DE_AYUDA } from '../constants';
import { TipoDeAyudaInputRenderer } from '../TipoDeAyudaInputRenderer';
import { FormData, HelpCategory, Status } from '../types';
import { TownSelector } from '../TownSelector';
import TownSelector from '../TownSelector/TownSelectorDataWrapper';

type FormRendererProps = {
status: Status;
Expand Down
3 changes: 0 additions & 3 deletions src/app/solicitar-ayuda/_components/Form/index.ts

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ type TownSelectorRendererProps = Pick<
'handleChange' | 'selectedTown'
>;

export function TownSelectorDataWrapper({ handleChange, selectedTown }: TownSelectorRendererProps) {
export default function TownSelectorDataWrapper({ handleChange, selectedTown }: TownSelectorRendererProps) {
const [towns, setTowns] = useState<Town[]>([]);

useEffect(() => {
Expand Down
3 changes: 0 additions & 3 deletions src/app/solicitar-ayuda/_components/TownSelector/index.ts

This file was deleted.

8 changes: 7 additions & 1 deletion src/components/AddressAutocomplete.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@
import { useState, useEffect, useRef, useCallback } from 'react';
import { MapPin } from 'lucide-react';

export default function AddressAutocomplete({ onSelect, placeholder = 'Buscar dirección...', initialValue = '' }) {
export default function AddressAutocomplete({
onSelect,
placeholder = 'Buscar dirección...',
initialValue = '',
required = false,
}) {
const [query, setQuery] = useState(initialValue);
const [suggestions, setSuggestions] = useState([]);
const [isLoading, setIsLoading] = useState(false);
Expand Down Expand Up @@ -136,6 +141,7 @@ export default function AddressAutocomplete({ onSelect, placeholder = 'Buscar di
onChange={handleInputChange}
placeholder={placeholder}
className="w-full p-2 pr-10 border rounded focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
required={required}
/>
<div className="absolute right-3 top-1/2 transform -translate-y-1/2">
{isLoading ? (
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
"strict": true,
"skipLibCheck": true,
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": false,
"allowJs": true,
"checkJs": false,
"noEmit": true,
"incremental": true,
Expand Down

0 comments on commit 74879d4

Please sign in to comment.