From 6d4c4ae367810ac3d7726cc775e050de0f684bf6 Mon Sep 17 00:00:00 2001
From: patrickwebsdev
Date: Fri, 8 Nov 2024 11:54:56 -0300
Subject: [PATCH 1/5] feature: now only get request from api
---
src/app/api/solicitudes/route.ts | 88 ++++++++++++----------
src/app/api/user/route.ts | 4 +-
src/app/casos-activos/solicitudes/page.tsx | 26 +++----
src/components/SolicitudCard.tsx | 6 +-
src/lib/supabase/server_role.ts | 30 ++++++++
5 files changed, 93 insertions(+), 61 deletions(-)
create mode 100644 src/lib/supabase/server_role.ts
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..090b35ec 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);
}
diff --git a/src/components/SolicitudCard.tsx b/src/components/SolicitudCard.tsx
index 046d72ad..f5a25824 100644
--- a/src/components/SolicitudCard.tsx
+++ b/src/components/SolicitudCard.tsx
@@ -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;
@@ -126,12 +124,12 @@ export default function SolicitudCard({ caso, showLink = true, showEdit = false
)}
- {special_situations && (
+ {caso.special_situations && (
<>
Situaciones especiales:
-
{special_situations}
+
{caso.special_situations}
>
)}
diff --git a/src/lib/supabase/server_role.ts b/src/lib/supabase/server_role.ts
new file mode 100644
index 00000000..71667e2e
--- /dev/null
+++ b/src/lib/supabase/server_role.ts
@@ -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(
+ 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.
+ }
+ },
+ },
+ },
+ );
+}
From 99fcb3283c4ea95d45a6ab93bc7041a5149047e1 Mon Sep 17 00:00:00 2001
From: patrickwebsdev
Date: Fri, 8 Nov 2024 12:10:44 -0300
Subject: [PATCH 2/5] fix: types
---
src/types/Requests.ts | 6 +++++-
1 file changed, 5 insertions(+), 1 deletion(-)
diff --git a/src/types/Requests.ts b/src/types/Requests.ts
index 184276ea..cea04e6d 100644
--- a/src/types/Requests.ts
+++ b/src/types/Requests.ts
@@ -3,7 +3,7 @@ import { Database } from './database';
export type HelpRequestType = 'necesita' | 'ofrece';
export type HelpRequestUrgencyType = 'alta' | 'media' | 'baja';
export type HelpRequestStatusType = 'pending' | 'in_progress' | 'active';
-export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'];
+export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'] & { special_situations:string, user_id: string};
export type HelpRequestUpdate = Database['public']['Tables']['help_requests']['Update'];
export type HelpRequestAssignmentData = Database['public']['Tables']['help_request_assignments']['Row'];
export type HelpRequestAssignmentInsert = Database['public']['Tables']['help_request_assignments']['Insert'];
@@ -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'];
From 780a095e11a6c27e2c946f2c619dc9195b166a6d Mon Sep 17 00:00:00 2001
From: patrickwebsdev
Date: Fri, 8 Nov 2024 12:15:41 -0300
Subject: [PATCH 3/5] fix: type
---
src/components/SolicitudCard.tsx | 2 +-
src/types/Requests.ts | 2 +-
2 files changed, 2 insertions(+), 2 deletions(-)
diff --git a/src/components/SolicitudCard.tsx b/src/components/SolicitudCard.tsx
index f5a25824..db85c6a8 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;
+ caso: HelpRequestData & { special_situations: string; user_id: string };
showLink?: boolean;
showEdit?: boolean;
};
diff --git a/src/types/Requests.ts b/src/types/Requests.ts
index cea04e6d..c875a3af 100644
--- a/src/types/Requests.ts
+++ b/src/types/Requests.ts
@@ -3,7 +3,7 @@ import { Database } from './database';
export type HelpRequestType = 'necesita' | 'ofrece';
export type HelpRequestUrgencyType = 'alta' | 'media' | 'baja';
export type HelpRequestStatusType = 'pending' | 'in_progress' | 'active';
-export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'] & { special_situations:string, user_id: string};
+export type HelpRequestData = Database['public']['Tables']['help_requests']['Row'];
export type HelpRequestUpdate = Database['public']['Tables']['help_requests']['Update'];
export type HelpRequestAssignmentData = Database['public']['Tables']['help_request_assignments']['Row'];
export type HelpRequestAssignmentInsert = Database['public']['Tables']['help_request_assignments']['Insert'];
From ba9f65d3f9cf030bffc40d0f62ba2c6785fe33b4 Mon Sep 17 00:00:00 2001
From: patrickwebsdev
Date: Fri, 8 Nov 2024 12:18:28 -0300
Subject: [PATCH 4/5] fix caso
---
src/app/casos-activos/solicitudes/page.tsx | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/app/casos-activos/solicitudes/page.tsx b/src/app/casos-activos/solicitudes/page.tsx
index 090b35ec..5a161806 100644
--- a/src/app/casos-activos/solicitudes/page.tsx
+++ b/src/app/casos-activos/solicitudes/page.tsx
@@ -170,7 +170,7 @@ function Solicitudes() {
) : (
- data.map((caso) => )
+ data.map((caso) => )
)}
From f5c6b478cfa4e1231074adeb2d60c88af0a1467a Mon Sep 17 00:00:00 2001
From: patrickwebsdev
Date: Fri, 8 Nov 2024 12:21:55 -0300
Subject: [PATCH 5/5] ...
---
src/app/solicitudes/[id]/page.tsx | 2 +-
src/app/solicitudes/page.tsx | 2 +-
src/helpers/format.tsx | 2 +-
3 files changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/app/solicitudes/[id]/page.tsx b/src/app/solicitudes/[id]/page.tsx
index 0b3d313d..3192aae3 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 77f8db06..218fd8b7 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/helpers/format.tsx b/src/helpers/format.tsx
index 736a2465..1b60354d 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(
- ,
+ ,
);
};