Skip to content

Commit

Permalink
feat: added api for request and offers
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickwebsdev committed Nov 8, 2024
1 parent 246ae0c commit 811bde1
Show file tree
Hide file tree
Showing 11 changed files with 249 additions and 103 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ NEXT_PUBLIC_BASE_URL=https://ajudadana.es
NEXT_PUBLIC_NODE_ENV=production
NEXT_PUBLIC_SUPABASE_URL=
NEXT_PUBLIC_SUPABASE_ANON_KEY=
SUPABASE_SERVICE_ROLE=
SUPABASE_GOOGLE_AUTH_ID=
SUPABASE_GOOGLE_AUTH_SECRET=
API_KEY=
44 changes: 44 additions & 0 deletions src/app/api/mapa/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { NextRequest } from 'next/server';
import { createServerRoleClient } from '@/lib/supabase/server_role';

export async function GET(req: NextRequest) {
const url = new URL(req.url);
const searchParams: any = url.searchParams;

const help_type = searchParams.get('type') || null;
const urgency = searchParams.get('urgency') || null;
const acepta = searchParams.get('acepta') || null;

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, user_id, latitude, longitude, urgency')
.eq('type', 'necesita');

if (help_type !== null) {
query.contains('help_type', [help_type]);
}
if (urgency !== null) {
query.eq('urgency', urgency);
}

query.neq('status', 'finished');

const { data, error } = await query.order('created_at', { ascending: false });

if (acepta !== 'todos') {
query.contains('accepted_items', [acepta]);
}

if (error) {
return Response.json({ error });
} else {
return Response.json({ data });
}
return Response.json({ message: 'Error' });
}
52 changes: 39 additions & 13 deletions src/app/api/ofertas/route.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
import { createClient } from '@/lib/supabase/server';
import { NextRequest } from 'next/server';
import { createServerRoleClient } from '@/lib/supabase/server_role';

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
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 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')
.eq('type', 'ofrece')
.or(`contact_info.ilike.%${email}%,additional_info.cs.${JSON.stringify({ email: email })}`);
return Response.json({ registeredPost });
.select(
'id, created_at,name,location,description,contact_info,additional_info->experience,status,resources,help_type,town_id,other_help',
{ count: 'exact' },
)
.eq('type', 'ofrece');

if (help_type !== null) {
query.contains('help_type', [help_type]);
}

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 });
}
const countResponse = count ?? 0;
return Response.json({ data, count: countResponse });
}
27 changes: 27 additions & 0 deletions src/app/api/solicitudes/[id]/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { createServerRoleClient } from '@/lib/supabase/server_role';
import { NextRequest } from 'next/server';

export async function GET(request: NextRequest, { params }: { params: { id: string } }) {
const id = params.id;

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 { data, error } = await supabase
.from('help_requests')
.select(
'id, created_at, name, location, description, urgency, number_of_people, contact_info, additional_info->special_situations, status, resources, latitude, longitude, coordinates, help_type, people_needed, other_help,town_id',
{ count: 'exact' },
)
.eq('id', id)
.limit(1)
.select();

if (error) {
return Response.json({ error });
}
return Response.json({ data });
}
84 changes: 44 additions & 40 deletions src/app/api/solicitudes/route.ts
Original file line number Diff line number Diff line change
@@ -1,48 +1,52 @@
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();
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') || null;
const town_id = searchParams.get('town') || null;
const urgency = searchParams.get('urgency') || null;
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'});
}
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, latitude, longitude, coordinates, help_type, people_needed, other_help,town_id',
{ 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 });
}
const countResponse = count ?? 0;
return Response.json({ data, count: countResponse });
}
49 changes: 18 additions & 31 deletions src/app/casos-activos/mapa/page.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
'use client';

import { useState, useEffect, Suspense } from 'react';
import { supabase } from '@/lib/supabase/client';
import SolicitudCard from '@/components/SolicitudCard';
import { useRouter, useSearchParams } from 'next/navigation';
import { tiposAyudaOptions } from '@/helpers/constants';
import Map, { PinMapa } from '@/components/map/map';
import PickupPoint from '@/components/PickupPoint';

export const dynamic = 'force-dynamic';
import SolicitudCardMap from '@/components/SolicitudCardMap';

export default function MapaPage() {
return (
Expand Down Expand Up @@ -55,7 +52,7 @@ function Mapa() {
latitude: request.latitude ?? 0,
longitude: request.longitude ?? 0,
id: request.id,
popup: <SolicitudCard showLink={true} showEdit={false} caso={request} />,
popup: <SolicitudCardMap caso={request.id} />,
};
}

Expand All @@ -70,44 +67,34 @@ function Mapa() {
}

async function fetchData() {
const url = process.env.NEXT_PUBLIC_BASE_URL + '/api/mapa/?';
try {
setLoading(true);
setError(null);
const filter = [];

// Comenzamos la consulta
const query = supabase.from('help_requests').select('*').eq('type', 'necesita');
if (filtroData.tipoAyuda !== 'todas') {
query.contains('help_type', [filtroData.tipoAyuda]);
filter.push('type=' + filtroData.tipoAyuda);
}
if (filtroData.pueblo !== 'todos') {
filter.push('town=' + filtroData.pueblo);
}
if (filtroData.urgencia !== 'todas') {
query.eq('urgency', filtroData.urgencia);
filter.push('urgency=' + filtroData.urgencia);
}

query.neq('status', 'finished');

const { data, error } = await query.order('created_at', { ascending: false });

const pickupQuery = supabase.from('collection_points').select('*', { count: 'exact' });
if (filtroData.acepta !== 'todos') {
query.contains('accepted_items', [filtroData.acepta]);
if (filtroData.acepta !== 'todas') {
filter.push('acepta=' + filtroData.acepta);
}

const { data: pickupData, error: pickupError } = await pickupQuery.order('created_at', { ascending: false });

let allData = [];
if (error) {
console.log('Error fetching solicitudes:', error);
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();
const markers = data.map(transformHelpRequestToMarker);
allData.push(...(markers || []));
}
if (pickupError) {
console.log('Error fetching pickup points:', pickupError);
} else {
const pickupMarkers = pickupData.map(transformPickupRequestToMarker);
allData.push(...(pickupMarkers || []));
setData(markers || []);
}
setData(allData);
} catch (err) {
console.log('Error general:', err);
setError('Error de conexión.');
Expand Down
23 changes: 9 additions & 14 deletions src/app/casos-activos/ofertas/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -60,28 +60,23 @@ function Ofertas() {

useEffect(() => {
async function fetchData() {
const url = process.env.NEXT_PUBLIC_BASE_URL + '/api/ofertas/?';
try {
setLoading(true);
setError(null);
const filter = [];

// Comenzamos la consulta
const query = supabase.from('help_requests').select('*', { count: 'exact' }).eq('type', 'ofrece');

// Solo agregar filtro si no es "todos"
if (filtroData.ayuda !== 'todas') {
query.contains('help_type', [filtroData.ayuda]);
filter.push('type=' + filtroData.ayuda);
}

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
4 changes: 2 additions & 2 deletions src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,12 +70,12 @@ function Solicitudes() {
const filter = [];

if (filtroData.tipoAyuda !== 'todas') {
filter.push('helptype=' + filtroData.tipoAyuda);
filter.push('type=' + filtroData.tipoAyuda);
}

// Solo agregar filtro si no es "todos"
if (filtroData.pueblo !== 'todos') {
filter.push('town_id=' + filtroData.pueblo);
filter.push('town=' + filtroData.pueblo);
}

// Solo agregar filtro si no es "todas"
Expand Down
11 changes: 10 additions & 1 deletion src/components/OfferCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { HelpRequestData } from '@/types/Requests';
import { useTowns } from '@/context/TownProvider';

type OfferCardProps = {
caso: HelpRequestData;
caso: HelpRequestData & { experience?: string };
showLink?: boolean;
};
export default function OfferCard({ caso, showLink = true }: OfferCardProps) {
Expand Down Expand Up @@ -98,6 +98,15 @@ export default function OfferCard({ caso, showLink = true }: OfferCardProps) {
</span>
</div>
)}
{caso.experience && (
<div className="flex items-start gap-2">
<Megaphone className="h-4 w-4 text-gray-500 flex-shrink-0 mt-1" />
<span className="break-words">
<span className="font-semibold">Experiencia:</span>
{' ' + caso.experience}
</span>
</div>
)}
</div>
</div>
<div className="flex flex-col items-start justify-between border-t border-gray-900/10 sm:flex-row sm:items-center px-6 py-4">
Expand Down
Loading

0 comments on commit 811bde1

Please sign in to comment.