Skip to content

Commit

Permalink
Merge pull request #220 from pedrolivaresanchez/improve-performance-c…
Browse files Browse the repository at this point in the history
…asos-activos

Improve performance casos activos
  • Loading branch information
vsornosa1 authored Nov 18, 2024
2 parents a164e8e + a66870a commit 7e42e6e
Show file tree
Hide file tree
Showing 20 changed files with 146 additions and 133 deletions.
6 changes: 6 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 5 additions & 6 deletions src/app/casos-activos/ofertas/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,12 @@ function Ofertas() {
const [currentCount, setCurrentCount] = useState<number>(0);
const [search, setSearch] = useState<string>('');
const debouncedSearch = useDebouncedValue(search, 500);

const itemsPerPage = 10;
const numPages = (count: number) => {
return Math.ceil(count / itemsPerPage) || 0;
};

const updateFilter = useCallback(
(filter: 'ayuda' | 'pueblo' | 'search' | 'page', value: string | number) => {
const params = new URLSearchParams(searchParams.toString());
Expand All @@ -51,13 +51,13 @@ function Ofertas() {
},
[router, searchParams],
);

const [filtroData, setFiltroData] = useState({
ayuda: searchParams.get('acepta') || 'todas',
pueblo: searchParams.get('pueblo') || 'todos',
search: searchParams.get('search') || '',
});

const changeDataFilter = useCallback(
(type: 'ayuda' | 'pueblo' | 'search', newFilter: string) => {
setFiltroData((prev) => ({
Expand All @@ -72,10 +72,9 @@ function Ofertas() {
useEffect(() => {
if (debouncedSearch !== filtroData.search) {
changeDataFilter('search', debouncedSearch);
}
}
}, [debouncedSearch, changeDataFilter, filtroData.search]);


function changePage(newPage: number) {
setCurrentPage(newPage);
updateFilter('page', newPage);
Expand Down
8 changes: 4 additions & 4 deletions src/app/casos-activos/solicitudes/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import { useTowns } from '@/context/TownProvider';
import { TabNavigationCount } from '@/components/TabNavigation';
import Modal from '@/components/Modal';
import { MAP_MODAL_NAME } from '@/components/map/map';
import { HelpRequestData } from '@/types/Requests';
import { HelpRequestData, HelpRequestWAssignments } from '@/types/Requests';
import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import SolicitudList, { isStringTrue } from '@/components/solicitudes/SolicitudList';
import SolicitudMap from '@/components/solicitudes/SolicitudMap';
Expand All @@ -28,14 +28,14 @@ function getDataFiltered(data: HelpRequestData[], filters: DataFilter[]) {

type SolicitudesProps = {
count: TabNavigationCount;
data: HelpRequestData[];
data: HelpRequestWAssignments[];
};

export function Solicitudes({ data, count }: SolicitudesProps) {
const { towns } = useTowns();
const searchParams = useSearchParams();
const router = useRouter();
const [selectedMarker, setSelectedMarker] = useState<HelpRequestData | null>(null);
const [selectedMarker, setSelectedMarker] = useState<HelpRequestWAssignments | null>(null);

const [dataFiltered, setDataFiltered] = useState<HelpRequestData[]>(data);

Expand Down Expand Up @@ -104,7 +104,7 @@ export function Solicitudes({ data, count }: SolicitudesProps) {
<div className="lg:flex lg:flex-row-reverse">
<SolicitudMap data={dataFiltered} setSelectedMarker={setSelectedMarker} />
<SolicitudList
data={dataFiltered}
data={dataFiltered as HelpRequestWAssignments[]}
count={count}
filtersData={filtersData}
onDataFilterChange={changeDataFilter}
Expand Down
6 changes: 3 additions & 3 deletions src/app/casos-activos/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@ import { SupabaseClient } from '@supabase/supabase-js';
import { createClient } from '@/lib/supabase/server';
import { Database } from '@/types/database';
import { Solicitudes } from '.';
import { helpDataSelectFields, HelpRequestData } from '@/types/Requests';
import { HelpRequestWAssignments } from '@/types/Requests';
import { FiltersData } from './types';

export const dynamic = 'force-dynamic';

function parseData(data: Database['public']['Tables']['help_requests']['Row'][]): HelpRequestData[] {
function parseData(data: Database['public']['Tables']['help_requests']['Row'][]): HelpRequestWAssignments[] {
return data.map((d) => {
// Remove unused properties to reduce the payload size
const { coordinates, location, ...rest } = d;
Expand All @@ -17,7 +17,7 @@ function parseData(data: Database['public']['Tables']['help_requests']['Row'][])
// Fix the coordinates to 3 decimals so locations have a 100m precision
latitude: Number(d.latitude?.toFixed(3)),
longitude: Number(d.longitude?.toFixed(3)),
} as HelpRequestData;
} as HelpRequestWAssignments;
});
}

Expand Down
9 changes: 6 additions & 3 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { Toaster } from 'sonner';
import { PropsWithChildren } from 'react';
import { QueryClientProvider } from '@/context/QueryClientProvider';
import { RoleProvider } from '@/context/RoleProvider';
import { TownProvider } from '../context/TownProvider';

export const metadata = {
title: 'Ajuda Dana - Sistema de Coordinación',
Expand All @@ -21,9 +22,11 @@ export default async function RootLayout({ children }: PropsWithChildren) {
<SessionProvider>
<RoleProvider>
<QueryClientProvider>
<ModalProvider>
<SidebarLayout>{children}</SidebarLayout>
</ModalProvider>
<TownProvider>
<ModalProvider>
<SidebarLayout>{children}</SidebarLayout>
</ModalProvider>
</TownProvider>
</QueryClientProvider>
</RoleProvider>
</SessionProvider>
Expand Down
10 changes: 5 additions & 5 deletions src/app/solicitudes/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,21 @@ import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import { useParams } from 'next/navigation';
import SolicitudComments from '@/components/Comments/SolicitudComments';
import { useEffect, useState } from 'react';
import { SelectedHelpData } from '../../../types/Requests';
import { getOne } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '../../../types/Requests';
import { getOneWithAssignments } from '@/lib/actions';

export default function CasoDetalle() {
const [loading, setLoading] = useState<boolean>(true);
const [data, setData] = useState<SelectedHelpData | null>(null);
const [data, setData] = useState<SelectedHelpDataWAssignment | null>(null);
const { id } = useParams<{ id: string }>();

useEffect(() => {
async function fetchData() {
try {
setLoading(true);

const requestResponse = await getOne(Number(id));
setData(requestResponse as SelectedHelpData);
const requestResponse = await getOneWithAssignments(Number(id));
setData(requestResponse as SelectedHelpDataWAssignment);

setLoading(false);
} catch (err) {
Expand Down
8 changes: 4 additions & 4 deletions src/app/solicitudes/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import SolicitudCard from '@/components/solicitudes/SolicitudCard';
import { useSession } from '@/context/SessionProvider';
import Link from 'next/link';
import { useQuery } from '@tanstack/react-query';
import { SelectedHelpData } from '@/types/Requests';
import { getSolicitudesByUser } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '@/types/Requests';
import { getSolicitudesWAssignemntsByUser } from '@/lib/actions';

export const dynamic = 'force-dynamic';

Expand All @@ -18,9 +18,9 @@ export default function ListaSolicitudes() {
data: requests,
isLoading,
error,
} = useQuery<SelectedHelpData[]>({
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesByUser(userId || ''),
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
});

if (isLoading) {
Expand Down
16 changes: 8 additions & 8 deletions src/components/AsignarSolicitudButton.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
'use client';

import { useSession } from '@/context/SessionProvider';
import { HelpRequestAssignmentData, SelectedHelpData } from '@/types/Requests';
import { getAssignments, assign, unassign } from '@/lib/actions';
import { SelectedHelpData, SelectedHelpDataWAssignment } from '@/types/Requests';
import { assign, unassign, getSolicitudesWAssignemntsByUser } from '@/lib/actions';
import { MouseEvent } from 'react';
import { Spinner } from '@/components/Spinner';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
Expand All @@ -23,12 +23,12 @@ export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitud
const router = useRouter();

const {
data: assignments,
data: solicitudesUser,
isLoading,
error,
} = useQuery<HelpRequestAssignmentData[]>({
queryKey: ['help_request_assignments', { id: helpRequest.id }],
queryFn: () => getAssignments(helpRequest.id),
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
});

const queryClient = useQueryClient();
Expand Down Expand Up @@ -84,9 +84,9 @@ export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitud
}

if (isLoading) return <Spinner />;
if (error || assignments === undefined) return <></>;
if (error || solicitudesUser === undefined) return <></>;

const userAssignment = assignments.find((x) => x.user_id === session.user?.id);
const userAssignment = solicitudesUser.find((x) => x.id === helpRequest.id);
const userIsAssigned = !!userAssignment;

if (!session || !session.user)
Expand Down
2 changes: 1 addition & 1 deletion src/components/OfferCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ export default function OfferCard({ caso, showLink = true, showEdit = false, hig
</div>
<div className="px-6 py-4">
<p className="text-gray-700 first-letter:capitalize" style={{ wordBreak: 'break-word' }}>
{caso.description && getHighlightedText(caso.description, highlightedText)}
{caso.description && getHighlightedText(caso.description, highlightedText)}
</p>
</div>
<div className="flex flex-col sm:flex-row justify-between items-start md:items-end gap-4 px-6 pb-4">
Expand Down
22 changes: 12 additions & 10 deletions src/components/PhoneInfo.tsx
Original file line number Diff line number Diff line change
@@ -1,35 +1,37 @@
import { useQuery } from '@tanstack/react-query';
import { useSession } from '@/context/SessionProvider';
import { getAssignments } from '@/lib/actions';
import { SelectedHelpData } from '@/types/Requests';
import { getSolicitudesWAssignemntsByUser } from '@/lib/actions';
import { SelectedHelpDataWAssignment } from '@/types/Requests';

type PhoneInfoProps = {
caseInfo: SelectedHelpData;
caseInfo: SelectedHelpDataWAssignment;
isAdmin: boolean;
};
export default function PhoneInfo({ caseInfo, isAdmin }: PhoneInfoProps) {
const session = useSession();
const userId = session?.user?.id;

const {
data: assignments,
data: solicitudesUser,
isLoading,
error,
} = useQuery({
queryKey: ['help_request_assignments', { id: caseInfo.id }],
queryFn: () => getAssignments(caseInfo.id),
} = useQuery<SelectedHelpDataWAssignment[]>({
queryKey: ['help_requests', { user_id: userId, type: 'necesita' }],
queryFn: () => getSolicitudesWAssignemntsByUser(userId || ''),
});

if (error || isLoading) return <></>;
if (error || isLoading || !solicitudesUser) return <></>;

const userAssignment = assignments?.find((x) => x.user_id === session.user?.id);
const userAssignment = solicitudesUser.find((x) => x.id === caseInfo.id);
const userIsAssigned = !!userAssignment;

return (
<span className="break-words">
<span className="font-semibold">Contacto:</span>{' '}
{session && session.user
? isAdmin
? caseInfo.contact_info
: !!userAssignment
: !!userIsAssigned
? caseInfo.contact_info
: 'Dale al botón "Quiero ayudar" para ver sus datos de contacto.'
: 'Inicia sesion para ver este dato'}
Expand Down
9 changes: 4 additions & 5 deletions src/components/map/map.tsx
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
'use client';

import { Dispatch, FC, ReactNode, SetStateAction, useState } from 'react';
import { Dispatch, FC, SetStateAction, useState } from 'react';
import InteractiveMap, { Layer, MapLayerMouseEvent, Source } from 'react-map-gl/maplibre';
import 'maplibre-gl/dist/maplibre-gl.css';
import { useModal } from '@/context/ModalProvider';
import { HelpRequestData } from '@/types/Requests';
import { InterpolationSpecification } from 'maplibre-gl';
import { HelpRequestWAssignments } from '@/types/Requests';

export const MAP_MODAL_NAME = `map-marker`;

type MapProps = {
solicitudes?: GeoJSON.FeatureCollection<GeoJSON.Point>;
setSelectedMarker: Dispatch<SetStateAction<HelpRequestData | null>>;
setSelectedMarker: Dispatch<SetStateAction<HelpRequestWAssignments | null>>;
};

const PAIPORTA_LAT = 39.42333;
Expand All @@ -30,7 +29,7 @@ const Map: FC<MapProps> = ({ solicitudes, setSelectedMarker }) => {
const onClickHandler = (e: MapLayerMouseEvent) => {
if (e.features?.[0]) {
toggleModal(MAP_MODAL_NAME, true);
setSelectedMarker(e.features?.[0].properties as HelpRequestData);
setSelectedMarker(e.features?.[0].properties as HelpRequestWAssignments);
}
};

Expand Down
13 changes: 8 additions & 5 deletions src/components/solicitudes/SolicitudCard.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import { AlertTriangle, MapPin, MapPinned, Megaphone, Phone, Users } from 'lucide-react';
import { AlertTriangle, MapPinned, Megaphone, Phone, Users } from 'lucide-react';
import { tiposAyudaOptions } from '@/helpers/constants';
import Link from 'next/link';
import { useSession } from '@/context/SessionProvider';
import { HelpRequestAdditionalInfo, HelpRequestData, SelectedHelpData } from '@/types/Requests';
import { HelpRequestAdditionalInfo, SelectedHelpDataWAssignment } from '@/types/Requests';
import AsignarSolicitudButton from '@/components/AsignarSolicitudButton';
import SolicitudHelpCount from '@/components/solicitudes/SolicitudHelpCount';
import PhoneInfo from '@/components/PhoneInfo';
import DeleteHelpRequest from '../DeleteHelpRequest';
import { textWithEllipsis } from '@/helpers/utils';
Expand All @@ -20,7 +19,7 @@ import CRMLog from '@/components/CRMLog';
import { getHighlightedText } from '@/helpers/format';

type SolicitudCardProps = {
caso: SelectedHelpData;
caso: SelectedHelpDataWAssignment;
showLink?: boolean;
showEdit?: boolean;
format?: 'small' | 'large';
Expand Down Expand Up @@ -79,7 +78,11 @@ export default function SolicitudCard({
</div>
</div>
<div className="flex flex-row justify-center items-center gap-2">
<SolicitudHelpCount id={caso.id} />
<div
className={`flex items-center justify-center rounded-full px-4 py-2 ${caso.assignments_count === 0 ? 'bg-red-100 text-red-800' : 'bg-green-100 text-green-800'}`}
>
<span className={`text-sm font-bold`}>{caso.assignments_count} VOLUNTARIOS</span>
</div>
<div
className={`flex items-center justify-center rounded-full px-4 py-2 ${
updateStatus === 'finished'
Expand Down
38 changes: 0 additions & 38 deletions src/components/solicitudes/SolicitudHelpCount.tsx

This file was deleted.

Loading

0 comments on commit 7e42e6e

Please sign in to comment.