Skip to content

Commit

Permalink
feat: add button to assign to a help request and show a badge with th…
Browse files Browse the repository at this point in the history
…e count
  • Loading branch information
Pinx0 committed Nov 6, 2024
1 parent 80f4abf commit da3d93d
Show file tree
Hide file tree
Showing 3 changed files with 85 additions and 53 deletions.
103 changes: 50 additions & 53 deletions src/components/AsignarSolicitudButton.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@
import { useSession } from '@/context/SessionProvider';
import { HelpRequestAssignmentData, HelpRequestData } from '@/types/Requests';
import { helpRequestService } from '@/lib/service';
import { MouseEvent, useCallback, useEffect, useState } from 'react';
import { MouseEvent } from 'react';
import { Spinner } from '@/components/Spinner';
import Link from 'next/link';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { toast } from 'sonner';

type AsignarSolicitudButtonProps = {
helpRequest: HelpRequestData;
Expand All @@ -14,69 +16,64 @@ type AsignarSolicitudButtonProps = {
export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitudButtonProps) {
const session = useSession();

const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const {
data: assignments,
isLoading,
error,
} = useQuery<HelpRequestAssignmentData[]>({
queryKey: ['help_request_assignments', { id: helpRequest.id }],
queryFn: () => helpRequestService.getAssignments(helpRequest.id),
});

const [assignments, setAssignments] = useState<HelpRequestAssignmentData[]>([]);
const queryClient = useQueryClient();

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

const fetchAssignments = useCallback(async () => {
setLoading(true);
try {
const data = await helpRequestService.getAssignments(helpRequest.id);
setAssignments(data);
} finally {
setLoading(false);
}
}, [helpRequest.id, setAssignments]);

useEffect(() => {
fetchAssignments();
}, [fetchAssignments]);

async function handleSubmit(e: MouseEvent) {
e.preventDefault();
setLoading(true);
setError(null);

if (!session) return;

try {
const assignMutation = useMutation({
mutationFn: async () => {
if (!session.user) return;
await helpRequestService.assign({
help_request_id: helpRequest.id,
user_id: session.user.id,
phone_number: session.user.user_metadata.telefono!,
});
} catch (error: any) {
console.error('Error al asignarte', error);
setError(error.message || 'Error al asignarte a esta solicitud de ayuda');
} finally {
setLoading(false);
fetchAssignments();
}
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['help_request_assignments'] });
},
onError: (e) => {
console.error('Error al asignarte a la petición de ayuda', e);
toast.error('Error al asignarte :(');
},
});

const unassignMutation = useMutation({
mutationFn: async () => {
if (!session.user) return;
if (!userAssignment) return;
await helpRequestService.unassign(userAssignment.id);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['help_request_assignments'] });
},
onError: (e) => {
console.error('Error al asignarte a la petición de ayuda', e);
toast.error('Error al asignarte :(');
},
});

async function handleSubmit(e: MouseEvent) {
e.preventDefault();
assignMutation.mutate();
}
async function handleCancel(e: MouseEvent) {
e.preventDefault();
setLoading(true);
setError(null);

if (!session) return;
if (!userAssignment) return;

try {
await helpRequestService.unassign(userAssignment.id);
} catch (error: any) {
console.error('Error al asignarte', error);
setError(error.message || 'Error al asignarte a esta solicitud de ayuda');
} finally {
setLoading(false);
fetchAssignments();
}
unassignMutation.mutate();
}

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

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

if (!session || !session.user)
return (
Expand All @@ -92,7 +89,7 @@ export default function AsignarSolicitudButton({ helpRequest }: AsignarSolicitud
onClick={handleCancel}
className={`rounded-lg text-white py-2 px-4 w-full sm:w-auto text-center bg-red-500`}
>
Cancelar ayuda :(
Cancelar mi ayuda
</button>
) : (
<button
Expand Down
2 changes: 2 additions & 0 deletions src/components/SolicitudCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useSession } from '@/context/SessionProvider';
import { HelpRequestAdditionalInfo, HelpRequestData } from '@/types/Requests';
import { Town } from '@/types/Town';
import AsignarSolicitudButton from '@/components/AsignarSolicitudButton';
import SolicitudHelpCount from '@/components/SolicitudHelpCount';

type SolicitudCardProps = {
caso: HelpRequestData;
Expand Down Expand Up @@ -53,6 +54,7 @@ export default function SolicitudCard({
{caso.name || 'Necesita Ayuda'}
</h3>
<div>
<SolicitudHelpCount id={caso.id} />
<span className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap mr-2 bg-purple-300`}>
Referencia: {caso.id}
</span>
Expand Down
33 changes: 33 additions & 0 deletions src/components/SolicitudHelpCount.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { HelpRequestAssignmentData } from '@/types/Requests';
import { useQuery } from '@tanstack/react-query';
import { helpRequestService } from '@/lib/service';
import { Spinner } from '@/components/Spinner';

type SolicitudHelpCountProps = {
id: number;
};

export default function SolicitudHelpCount({ id }: SolicitudHelpCountProps) {
const {
data: assignments,
isLoading,
error,
} = useQuery<HelpRequestAssignmentData[]>({
queryKey: ['help_request_assignments', { id: id }],
queryFn: () => helpRequestService.getAssignments(id),
});

if (isLoading) return <Spinner />;

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

const volunteers = assignments.length;

return (
<span
className={`px-3 py-1 rounded-full text-sm font-medium whitespace-nowrap mr-2 ${volunteers === 0 ? 'bg-red-300' : 'bg-green-300'}`}
>
Voluntarios: {volunteers}
</span>
);
}

0 comments on commit da3d93d

Please sign in to comment.