Skip to content

Commit

Permalink
refactor: add types
Browse files Browse the repository at this point in the history
  • Loading branch information
Pinx0 committed Nov 8, 2024
1 parent 7e62957 commit 4906115
Show file tree
Hide file tree
Showing 6 changed files with 432 additions and 383 deletions.
39 changes: 20 additions & 19 deletions src/app/punto-recogida/page.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
'use client';

import { useState, useCallback, useEffect } from 'react';
import { useState, useCallback, useEffect, FormEvent } from 'react';
import { supabase } from '@/lib/supabase/client';
import { MapPin, Phone, Package, House, Contact, Megaphone } from 'lucide-react';
import AddressAutocomplete from '@/components/AddressAutocomplete';
import { isValidPhone } from '@/helpers/utils';
import { PhoneInput } from '@/components/PhoneInput';
import { CollectionPointData, CollectionPointInsert } from '@/types/DataPoints';

export const dynamic = 'force-dynamic';

Expand All @@ -22,16 +23,16 @@ export default function PuntosRecogida() {
status: 'active',
};

const [formData, setFormData] = useState(initialFormData);
const [formData, setFormData] = useState<CollectionPointInsert>(initialFormData);
const [showForm, setShowForm] = useState(false);
const [loading, setLoading] = useState(false);
const [collectionPoints, setCollectionPoints] = useState([]);
const [error, setError] = useState(null);
const [collectionPoints, setCollectionPoints] = useState<CollectionPointData[]>([]);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState(false);

const tiposAyuda = ['Alimentos', 'Agua', 'Ropa', 'Mantas', 'Medicamentos', 'Productos de higiene'];

const handlePhoneChange = useCallback((phoneNumber) => {
const handlePhoneChange = useCallback((phoneNumber: string) => {
setFormData((formData) => ({ ...formData, contact_phone: phoneNumber }));
}, []);

Expand All @@ -54,20 +55,20 @@ export default function PuntosRecogida() {
}
}

async function handleSubmit(e) {
async function handleSubmit(e: FormEvent) {
e.preventDefault();
setLoading(true);
setError(null);

try {
const requiredFields = ['name', 'location', 'contact_phone'];
const requiredFields = ['name', 'location', 'contact_phone'] as const;
const missingFields = requiredFields.filter((field) => !formData[field]);

if (missingFields.length > 0) {
throw new Error('Por favor completa todos los campos obligatorios');
}

if (!isValidPhone(formData.contact_phone)) {
if (!isValidPhone(formData.contact_phone ?? '')) {
alert('El teléfono de contacto no es válido.');
return;
}
Expand All @@ -94,7 +95,7 @@ export default function PuntosRecogida() {
setFormData(initialFormData);

setTimeout(() => setSuccess(false), 3000);
} catch (error) {
} catch (error: any) {
console.error('Error al registrar punto de recogida:', error);
setError(error.message || 'Error al registrar el punto de recogida');
} finally {
Expand Down Expand Up @@ -210,7 +211,7 @@ export default function PuntosRecogida() {
<label className="block text-sm font-medium text-gray-700 mb-1">Nombre del centro *</label>
<input
type="text"
value={formData.name}
value={formData.name ?? ''}
onChange={(e) => setFormData({ ...formData, name: e.target.value })}
className="w-full p-2 border rounded"
required
Expand All @@ -219,7 +220,7 @@ export default function PuntosRecogida() {
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Dirección completa *</label>
<AddressAutocomplete
onSelect={(address) => {
onSelect={(address: any) => {
setFormData((prev) => ({
...prev,
location: address.fullAddress,
Expand All @@ -242,18 +243,18 @@ export default function PuntosRecogida() {
<label
key={tipo}
className={`flex items-center p-3 rounded cursor-pointer ${
formData.accepted_items.includes(tipo)
formData.accepted_items?.includes(tipo)
? 'bg-blue-100 text-blue-800'
: 'bg-gray-50 hover:bg-gray-100'
}`}
>
<input
type="checkbox"
checked={formData.accepted_items.includes(tipo)}
checked={formData.accepted_items?.includes(tipo)}
onChange={(e) => {
const newItems = e.target.checked
? [...formData.accepted_items, tipo]
: formData.accepted_items.filter((item) => item !== tipo);
? [...(formData.accepted_items ?? []), tipo]
: formData.accepted_items?.filter((item) => item !== tipo);
setFormData({ ...formData, accepted_items: newItems });
}}
className="sr-only"
Expand All @@ -268,21 +269,21 @@ export default function PuntosRecogida() {
<label className="block text-sm font-medium text-gray-700 mb-1">Persona responsable</label>
<input
type="text"
value={formData.contact_name}
value={formData.contact_name ?? ''}
onChange={(e) => setFormData({ ...formData, contact_name: e.target.value })}
className="w-full p-2 border rounded"
/>
</div>
<PhoneInput phoneNumber={formData.contact_phone} onChange={handlePhoneChange} required />
<PhoneInput phoneNumber={formData.contact_phone ?? ''} onChange={handlePhoneChange} required />
</div>

<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Necesidades urgentes</label>
<textarea
value={formData.urgent_needs}
value={formData.urgent_needs ?? ''}
onChange={(e) => setFormData({ ...formData, urgent_needs: e.target.value })}
className="w-full p-2 border rounded"
rows="3"
rows={3}
placeholder="¿Qué se necesita con más urgencia?"
/>
</div>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@ import { useTowns } from '@/context/TownProvider';
import { useRole } from '@/context/RoleProvider';
import { useState } from 'react';

// type SolicitudCardProps = {
// caso: HelpRequestData;
// showLink?: boolean;
// showEdit?: boolean;
// };
type SolicitudCardProps = {
caso: HelpRequestData;
showLink?: boolean;
showEdit?: boolean;
};

export default function SolicitudCard({ caso, showLink = true, showEdit = false }) {
export default function SolicitudCard({ caso, showLink = true, showEdit = false }: SolicitudCardProps) {
const session = useSession();
const role = useRole();
const { getTownById } = useTowns();
const additionalInfo = caso.additional_info;
const additionalInfo = caso.additional_info as HelpRequestAdditionalInfo;
const special_situations = 'special_situations' in additionalInfo ? additionalInfo.special_situations : undefined;
const isAdmin = role === 'admin';
const [deleted, setDeleted] = useState(false);
Expand Down
10 changes: 5 additions & 5 deletions src/context/RoleProvider.jsx → src/context/RoleProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
'use client';
import React, { createContext, ReactNode, useContext, useEffect, useState } from 'react';
import React, { createContext, PropsWithChildren, ReactNode, useContext, useEffect, useState } from 'react';
import { supabase } from '@/lib/supabase/client';
import { useSession } from './SessionProvider';

const RoleContext = createContext();
const RoleContext = createContext<string>('user');

export const RoleProvider = ({ children }) => {
export const RoleProvider = ({ children }: PropsWithChildren) => {
const session = useSession();
const [role, setRole] = useState('user');
const [role, setRole] = useState<string | null>('user');

useEffect(() => {
const fetchRole = async () => {
Expand Down Expand Up @@ -39,7 +39,7 @@ export const RoleProvider = ({ children }) => {
fetchRole();
}, [session]);

return <RoleContext.Provider value={role}>{children}</RoleContext.Provider>;
return <RoleContext.Provider value={role ?? 'anon'}>{children}</RoleContext.Provider>;
};

export const useRole = () => useContext(RoleContext);
1 change: 1 addition & 0 deletions src/types/DataPoints.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { Database } from '@/types/database';

export type CollectionPointData = Database['public']['Tables']['collection_points']['Row'];
export type CollectionPointInsert = Database['public']['Tables']['collection_points']['Insert'];

export type DeliveryPointData = Database['public']['Tables']['delivery_points']['Row'];
export type DeliveryPointInsert = Database['public']['Tables']['delivery_points']['Insert'];
Expand Down
4 changes: 0 additions & 4 deletions src/types/Requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,3 @@ export type HelpRequestAdditionalInfo = {
special_situations?: string;
email?: string;
};

export type CollectionPointType = 'permanente' | 'temporal';
export type CollectionPointStatus = 'active' | 'inactive';
export type CollectionPointData = Database['public']['Tables']['collection_points']['Row'];
Loading

0 comments on commit 4906115

Please sign in to comment.