Skip to content

Commit

Permalink
Merge pull request #171 from pedrolivaresanchez/feature/solicitudes-a…
Browse files Browse the repository at this point in the history
…pi-backend

feature: now only get request from api
  • Loading branch information
patrickwebsdev authored Nov 8, 2024
2 parents b6c92a4 + f5c6b47 commit 246ae0c
Show file tree
Hide file tree
Showing 9 changed files with 102 additions and 66 deletions.
88 changes: 48 additions & 40 deletions src/app/api/solicitudes/route.ts
Original file line number Diff line number Diff line change
@@ -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'});
}
4 changes: 2 additions & 2 deletions src/app/api/user/route.ts
Original file line number Diff line number Diff line change
@@ -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 });
Expand Down
28 changes: 12 additions & 16 deletions src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down Expand Up @@ -174,7 +170,7 @@ function Solicitudes() {
</p>
</div>
) : (
data.map((caso) => <SolicitudCard showLink={true} showEdit={true} key={caso.id} caso={caso} />)
data.map((caso) => <SolicitudCard showLink={true} showEdit={true} key={caso.id} caso={caso as any} />)
)}
</div>
<div className="flex items-center justify-center">
Expand Down
2 changes: 1 addition & 1 deletion src/app/solicitudes/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default function CasoDetalle() {
Volver
</button>
</div>
<SolicitudCard caso={request} showLink={false} showEdit={true} />
<SolicitudCard caso={request as any} showLink={false} showEdit={true} />
</div>
);
}
2 changes: 1 addition & 1 deletion src/app/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ export default function ListaSolicitudes() {
</Link>
</div>
) : (
requests.map((caso) => <SolicitudCard showLink={true} showEdit={true} key={caso.id} caso={caso} />)
requests.map((caso) => <SolicitudCard showLink={true} showEdit={true} key={caso.id} caso={caso as any} />)
)}
</div>
</div>
Expand Down
8 changes: 3 additions & 5 deletions src/components/SolicitudCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { useState } from 'react';
import ChangeUrgencyHelpRequest from './ChangeUrgencyHelpRequest';

type SolicitudCardProps = {
caso: HelpRequestData;
caso: HelpRequestData & { special_situations: string; user_id: string };
showLink?: boolean;
showEdit?: boolean;
};
Expand All @@ -22,8 +22,6 @@ 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;
Expand Down Expand Up @@ -126,12 +124,12 @@ export default function SolicitudCard({ caso, showLink = true, showEdit = false
</span>
</div>
)}
{special_situations && (
{caso.special_situations && (
<>
<hr />
<div className="pt-2">
<span className="font-semibold block mb-1">Situaciones especiales:</span>
<p className="text-gray-700 break-words">{special_situations}</p>
<p className="text-gray-700 break-words">{caso.special_situations}</p>
</div>
</>
)}
Expand Down
2 changes: 1 addition & 1 deletion src/helpers/format.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,6 @@ export const getMarkerColorBySolicitud = (solicitud: HelpRequestData) => {
};
export const getMarkerDescriptionBySolicitudAndTowns = (solicitud: HelpRequestData) => {
return ReactDOMServer.renderToString(
<SolicitudCard key={solicitud.id} caso={solicitud} showEdit={false} showLink={true} />,
<SolicitudCard key={solicitud.id} caso={solicitud as any} showEdit={false} showLink={true} />,
);
};
30 changes: 30 additions & 0 deletions src/lib/supabase/server_role.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
'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<Database>(
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.
}
},
},
},
);
}
4 changes: 4 additions & 0 deletions src/types/Requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,7 @@ 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'];

0 comments on commit 246ae0c

Please sign in to comment.