diff --git a/src/app/api/solicitudes/route.ts b/src/app/api/solicitudes/route.ts index 1636fc06..9946c292 100644 --- a/src/app/api/solicitudes/route.ts +++ b/src/app/api/solicitudes/route.ts @@ -1,40 +1,48 @@ -import { NextRequest, NextResponse } from 'next/server'; -import { createClient } from '@/lib/supabase/server'; - -export async function GET() { - const supabase = await createClient(); - const { data, error } = await supabase.auth.getUser(); - if (error || !data?.user) { - return Response.json({ message: 'Not logged.', error }); - } - const email = data.user.email; - const registeredPost = await supabase - .from('help_requests') - .select('*') - .eq('type', 'necesita') - .or(`contact_info.ilike.%${email}%,additional_info.cs.${JSON.stringify({ email: email })}`); - return Response.json({ registeredPost }); -} - -export async function POST(request: NextRequest) { - try { - // Obtener los datos del formulario (multipart/form-data) - const formData = await request.formData(); - - // Obtener el ID desde el form-data - const id = formData.get('id'); // Asumiendo que el campo 'id' se llama 'id' - - // Verificar que el ID esté presente - if (!id) { - return NextResponse.json({ error: 'El campo "id" es requerido' }, { status: 400 }); - } - - return NextResponse.json({ - message: 'Datos recibidos correctamente', - id: id, - }); - } catch (error) { - console.error('Error procesando la solicitud:', error); - return NextResponse.json({ error: 'Error al procesar la solicitud' }, { status: 500 }); - } -} +import { NextRequest } from 'next/server'; +import { createServerRoleClient } from '@/lib/supabase/server_role'; + + export async function GET(req: NextRequest) { + // Acceder a los parámetros de búsqueda + const url = new URL(req.url); + const searchParams: any = url.searchParams; + + const help_type = searchParams.get('type'); + const town_id = searchParams.get('town'); + const urgency = searchParams.get('urgency'); + const currentPage = searchParams.get('page') ?? 1 ; + const itemsPerPage = 10; + + const supabase = await createServerRoleClient(); + // const { data: dataUser, error: errorUser } = await supabase.auth.getUser(); + // if (errorUser || !dataUser?.user) { + // return Response.json({ message: 'Not logged.', errorUser }); + // } + + const query = supabase.from('help_requests').select('id, created_at, name, location, description, urgency, number_of_people, contact_info, additional_info->special_situations, status, resources, help_type, people_needed, other_help', { count: 'exact' }).eq('type', 'necesita'); + + if (help_type !== null) { + query.contains('help_type', [help_type]); + } + + if (town_id !== null) { + query.eq('town_id', town_id); + } + + if (urgency !== null) { + query.eq('urgency', urgency); + } + + query.neq('status', 'finished'); + + const { data, count, error } = await query + .range((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage - 1) + .order('created_at', { ascending: false }); + + if (error) { + return Response.json({error}) + } else { + const countResponse = count ?? 0; + return Response.json({data, count: countResponse }); + } + return Response.json({message: 'Error'}); +} \ No newline at end of file diff --git a/src/app/api/user/route.ts b/src/app/api/user/route.ts index ef9bc0d0..54d3769c 100644 --- a/src/app/api/user/route.ts +++ b/src/app/api/user/route.ts @@ -1,7 +1,7 @@ -import { createClient } from '@/lib/supabase/server'; +import { createServerRoleClient } from '@/lib/supabase/server_role'; export async function GET() { - const supabase = await createClient(); + const supabase = await createServerRoleClient(); 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 725493eb..5a161806 100644 --- a/src/app/casos-activos/solicitudes/page.tsx +++ b/src/app/casos-activos/solicitudes/page.tsx @@ -63,37 +63,33 @@ function Solicitudes() { useEffect(() => { async function fetchData() { + const url = process.env.NEXT_PUBLIC_BASE_URL + '/api/solicitudes/?'; try { setLoading(true); setError(null); + const filter = []; - // Comenzamos la consulta - const query = supabase.from('help_requests').select('*', { count: 'exact' }).eq('type', 'necesita'); - - // Solo agregar filtro si no es "todos" if (filtroData.tipoAyuda !== 'todas') { - query.contains('help_type', [filtroData.tipoAyuda]); + filter.push('helptype=' + filtroData.tipoAyuda); } // Solo agregar filtro si no es "todos" if (filtroData.pueblo !== 'todos') { - query.eq('town_id', filtroData.pueblo); + filter.push('town_id=' + filtroData.pueblo); } // Solo agregar filtro si no es "todas" if (filtroData.urgencia !== 'todas') { - query.eq('urgency', filtroData.urgencia); + filter.push('urgency=' + filtroData.urgencia); } - query.neq('status', 'finished'); - // Ejecutar la consulta con paginación - const { data, count, error } = await query - .range((currentPage - 1) * itemsPerPage, currentPage * itemsPerPage - 1) - .order('created_at', { ascending: false }); - - if (error) { - console.log('Error fetching solicitudes:', error); + 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); } @@ -174,7 +170,7 @@ function Solicitudes() {
) : ( - data.map((caso) =>{special_situations}
+{caso.special_situations}