diff --git a/src/app/api/user/route.ts b/src/app/api/user/route.ts index 54d3769c..ef9bc0d0 100644 --- a/src/app/api/user/route.ts +++ b/src/app/api/user/route.ts @@ -1,7 +1,7 @@ -import { createServerRoleClient } from '@/lib/supabase/server_role'; +import { createClient } from '@/lib/supabase/server'; export async function GET() { - const supabase = await createServerRoleClient(); + const supabase = await createClient(); const { data, error } = await supabase.auth.getUser(); if (error || !data?.user) { return Response.json({ message: 'Not logged.', error }); diff --git a/src/app/casos-activos/solicitudes/page.tsx b/src/app/casos-activos/solicitudes/page.tsx index e2c9a82f..218fd8b7 100644 --- a/src/app/casos-activos/solicitudes/page.tsx +++ b/src/app/casos-activos/solicitudes/page.tsx @@ -1,110 +1,29 @@ 'use client'; -import { Suspense, useEffect, useState } from 'react'; -import { supabase } from '@/lib/supabase/client'; +import { Search } from 'lucide-react'; import SolicitudCard from '@/components/SolicitudCard'; -import Pagination from '@/components/Pagination'; -import { useRouter, useSearchParams } from 'next/navigation'; -import { tiposAyudaOptions } from '@/helpers/constants'; -import { useTowns } from '@/context/TownProvider'; +import { useSession } from '@/context/SessionProvider'; +import Link from 'next/link'; +import { useQuery } from '@tanstack/react-query'; import { HelpRequestData } from '@/types/Requests'; +import { helpRequestService } from '@/lib/service'; export const dynamic = 'force-dynamic'; -export default function SolicitudesPage() { - return ( - - - - ); -} - -function Solicitudes() { - const { towns } = useTowns(); - const searchParams = useSearchParams(); - const router = useRouter(); - - const [loading, setLoading] = useState(true); - const [error, setError] = useState(null); - - const [data, setData] = useState([]); - const [currentPage, setCurrentPage] = useState(Number(searchParams.get('page')) || 1); - const [currentCount, setCurrentCount] = useState(0); - - const itemsPerPage = 10; - const numPages = (count: number) => { - return Math.ceil(count / itemsPerPage) || 0; - }; - - const updateFilter = (filter: 'urgencia' | 'tipoAyuda' | 'pueblo' | 'page', value: string | number) => { - const params = new URLSearchParams(searchParams.toString()); - params.set(filter, value.toString()); - router.push(`?${params.toString()}`); - }; - - const [filtroData, setFiltroData] = useState({ - urgencia: searchParams.get('urgencia') || 'todas', - tipoAyuda: searchParams.get('tipoAyuda') || 'todas', - pueblo: searchParams.get('pueblo') || 'todos', +export default function ListaSolicitudes() { + const session = useSession(); + const userId = session.user?.id; + + const { + data: requests, + isLoading, + error, + } = useQuery({ + queryKey: ['help_requests', { user_id: userId, type: 'necesita' }], + queryFn: () => helpRequestService.getRequestsByUser(userId), }); - const changeDataFilter = (type: 'urgencia' | 'tipoAyuda' | 'pueblo', newFilter: string) => { - setFiltroData((prev) => ({ - ...prev, - [type]: newFilter, - })); - updateFilter(type, newFilter); - }; - - function changePage(newPage: number) { - setCurrentPage(newPage); - updateFilter('page', newPage); - } - - useEffect(() => { - async function fetchData() { - const url = process.env.NEXT_PUBLIC_BASE_URL + '/api/solicitudes/?'; - try { - setLoading(true); - setError(null); - const filter = []; - - if (filtroData.tipoAyuda !== 'todas') { - filter.push('type=' + filtroData.tipoAyuda); - } - - // Solo agregar filtro si no es "todos" - if (filtroData.pueblo !== 'todos') { - filter.push('town=' + filtroData.pueblo); - } - - // Solo agregar filtro si no es "todas" - if (filtroData.urgencia !== 'todas') { - filter.push('urgency=' + filtroData.urgencia); - } - filter.push('page=' + currentPage); - const filterUrl = url + filter.join('&'); - const response = await fetch(filterUrl); - if (!response.ok) { - console.log(`Error fetching solicitudes: ${response.status}`); - setData([]); - } else { - const { data, count } = await response.json(); - setData(data || []); - setCurrentCount(count ?? 0); - } - } catch (err) { - console.log('Error general:', err); - setError('Error de conexión.'); - } finally { - setLoading(false); - } - } - - fetchData(); - }, [filtroData, currentPage]); - - if (loading) { + if (isLoading) { return (
@@ -112,70 +31,37 @@ function Solicitudes() { ); } - if (error) { + if (error || requests === undefined) { return (
-

{error}

+

{error?.message}

); } return ( <> - {/* FILTROS */} -
-

Filtros

-
- - - +
+
+ {requests.length === 0 ? ( +
+

+ No se encontraron solicitudes de ayuda correspondientes a tu cuenta. +

+ + + + Solicitar ayuda + +
+ ) : ( + requests.map((caso) => ) + )}
-
- {data.length === 0 ? ( -
-

- No se encontraron solicitudes que coincidan con los filtros. -

-
- ) : ( - data.map((caso) => ) - )} -
-
- -
); } diff --git a/src/app/solicitudes/[id]/page.tsx b/src/app/solicitudes/[id]/page.tsx index 3192aae3..0b3d313d 100644 --- a/src/app/solicitudes/[id]/page.tsx +++ b/src/app/solicitudes/[id]/page.tsx @@ -54,7 +54,7 @@ export default function CasoDetalle() { Volver
- +
); } diff --git a/src/app/solicitudes/page.tsx b/src/app/solicitudes/page.tsx index 218fd8b7..77f8db06 100644 --- a/src/app/solicitudes/page.tsx +++ b/src/app/solicitudes/page.tsx @@ -58,7 +58,7 @@ export default function ListaSolicitudes() {
) : ( - requests.map((caso) => ) + requests.map((caso) => ) )} diff --git a/src/components/SolicitudCard.tsx b/src/components/SolicitudCard.tsx index db85c6a8..046d72ad 100644 --- a/src/components/SolicitudCard.tsx +++ b/src/components/SolicitudCard.tsx @@ -13,7 +13,7 @@ import { useState } from 'react'; import ChangeUrgencyHelpRequest from './ChangeUrgencyHelpRequest'; type SolicitudCardProps = { - caso: HelpRequestData & { special_situations: string; user_id: string }; + caso: HelpRequestData; showLink?: boolean; showEdit?: boolean; }; @@ -22,6 +22,8 @@ export default function SolicitudCard({ caso, showLink = true, showEdit = false const session = useSession(); const role = useRole(); const { getTownById } = useTowns(); + 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); const isMyRequest = session.user?.id && session.user.id === caso.user_id; @@ -124,12 +126,12 @@ export default function SolicitudCard({ caso, showLink = true, showEdit = false )} - {caso.special_situations && ( + {special_situations && ( <>
Situaciones especiales: -

{caso.special_situations}

+

{special_situations}

)} diff --git a/src/helpers/format.tsx b/src/helpers/format.tsx index 1b60354d..736a2465 100644 --- a/src/helpers/format.tsx +++ b/src/helpers/format.tsx @@ -33,6 +33,6 @@ export const getMarkerColorBySolicitud = (solicitud: HelpRequestData) => { }; export const getMarkerDescriptionBySolicitudAndTowns = (solicitud: HelpRequestData) => { return ReactDOMServer.renderToString( - , + , ); }; diff --git a/src/lib/supabase/server_role.ts b/src/lib/supabase/server_role.ts deleted file mode 100644 index 71667e2e..00000000 --- a/src/lib/supabase/server_role.ts +++ /dev/null @@ -1,30 +0,0 @@ -'use server'; - -import { createServerClient } from '@supabase/ssr'; -import { cookies } from 'next/headers'; -import { Database } from '@/types/database'; - -export async function createServerRoleClient() { - const cookieStore = await cookies(); - - return createServerClient( - process.env.NEXT_PUBLIC_SUPABASE_URL!, - process.env.SUPABASE_SERVICE_ROLE!, - { - cookies: { - getAll() { - return cookieStore.getAll(); - }, - setAll(cookiesToSet) { - try { - cookiesToSet.forEach(({ name, value, options }) => cookieStore.set(name, value, options)); - } catch { - // The `setAll` method was called from a Server Component. - // This can be ignored if you have middleware refreshing - // user sessions. - } - }, - }, - }, - ); -} diff --git a/src/types/Requests.ts b/src/types/Requests.ts index c875a3af..184276ea 100644 --- a/src/types/Requests.ts +++ b/src/types/Requests.ts @@ -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'];