feat(invite Match to bar / create chat on match): Modal to invite match to bar/ create chat on match

This commit is contained in:
Laurian-Dufrechou
2023-05-18 17:03:45 +02:00
parent 5b2e9ebafc
commit 8e021a833d
15 changed files with 598 additions and 231 deletions
+8 -3
View File
@@ -2,12 +2,17 @@ import { MdError } from "react-icons/md";
import { Button, Text, VStack } from "@chakra-ui/react";
import { useRouter } from "next/router";
export default function LoadingPage() {
export default function ErrorGeolocation() {
const router = useRouter();
return (
<VStack justifyContent="center" alignItems="center" height="100vh"
width="100vw" bg="gray.100">
<VStack
justifyContent="center"
alignItems="center"
height="100vh"
width="100vw"
bg="gray.100"
>
<MdError color="purple.500" size="50%" />
<Text color="purple.500" fontSize="2xl" fontWeight="bold">
Veillez à autoriser la géolocalisation
@@ -49,7 +49,7 @@ export default function LeftPanel(props) {
</Flex>
<Divider mb={"1rem"} />
<Text as="i" fontWeight={"bold"}>
&quot;{user.bio}&quot;
{user.bio && `"${user.bio}"`}
</Text>
</Box>
</Box>
@@ -14,7 +14,6 @@ import {
Text,
useDisclosure,
} from "@chakra-ui/react";
import { SetStateAction } from "react";
import { useQuery } from "@tanstack/react-query";
import { User } from "@prisma/client";
import Carousel from "@/components/Carousel";
@@ -111,7 +110,7 @@ export default function ModalMatch({ notif, loggedUser }: modalMatchProps) {
</Text>
</Box>
<Box>
<Heading size={"sm"} fontWeight={"bold"}>
<Heading size={"sm"} mt={4} fontWeight={"bold"}>
Passions :
</Heading>
{passionLoading ? (
@@ -0,0 +1,83 @@
import {
Box,
Card,
CardBody,
chakra,
Flex,
GridItem,
Image,
Spacer,
Text,
useRadio,
} from "@chakra-ui/react";
import { Notification } from "@prisma/client";
import { useQuery } from "@tanstack/react-query";
type CardMatchedUserProps = {
notif: Notification;
};
export default function CardMatchedUser({
notif,
...radioProps
}: CardMatchedUserProps) {
const {
isLoading,
isError,
data: matchedUser,
error,
} = useQuery({
refetchOnWindowFocus: false,
queryKey: ["matchUser", notif.MatchedUserID],
queryFn: async () => {
return fetch(`/api/users/${notif.MatchedUserID}?include=Chat`)
.then((res) => {
return res.json();
})
.catch((err) => {
return err;
});
},
});
const { state, getInputProps, getRadioProps, htmlProps, getLabelProps } =
useRadio(radioProps);
return (
<>
{!isLoading ? (
<chakra.label {...htmlProps} cursor="pointer">
<input {...getInputProps()} hidden />
<GridItem height={"100%"}>
<Card
{...getRadioProps()}
height={"100%"}
outline={state.isChecked ? "3px solid" : "none"}
outlineColor={state.isChecked ? "purple.500" : "none"}
bg={state.isChecked ? "purple.50" : "white"}
>
<CardBody>
<Flex
height={"100%"}
direction={"column"}
gap={"1rem"}
justifyContent={"space-between"}
{...getLabelProps()}
>
<Image src={matchedUser.images[0]}></Image>
<Text
align={"center"}
fontSize={"1.5rem"}
fontWeight={"bold"}
>
{matchedUser.firstName} {matchedUser.lastName}
</Text>
</Flex>
</CardBody>
</Card>
</GridItem>
</chakra.label>
) : null}
</>
);
}
+50 -45
View File
@@ -1,60 +1,65 @@
import {MapContainer, TileLayer, Marker, Popup} from 'react-leaflet';
import {Flex, Text, useToast} from '@chakra-ui/react';
import MarkerClusterGroup
from '@christopherpickering/react-leaflet-markercluster';
import { MapContainer, TileLayer, Marker, useMapEvents } from "react-leaflet";
import { Flex, Text, useToast } from "@chakra-ui/react";
import MarkerClusterGroup from "@christopherpickering/react-leaflet-markercluster";
import L from "leaflet";
import { memo, useState } from "react";
import '@christopherpickering/react-leaflet-markercluster/dist/styles.min.css';
import "@christopherpickering/react-leaflet-markercluster/dist/styles.min.css";
import MarkerBar from './MarkerBar';
import 'leaflet/dist/leaflet.css';
import MarkerBar from "./MarkerBar";
import "leaflet/dist/leaflet.css";
export default function MapComponent(props: any) {
const {location, listBars} = props;
const { location, listBars } = props;
const toast = useToast({position: 'bottom'});
const toast = useToast({ position: "bottom" });
const idToastError = 'error_location';
const idToastError = "error_location";
const userIcon = new L.Icon({
iconUrl: 'logo.svg',
iconUrl: "logo.svg",
iconSize: [35, 35],
});
return (
<>
{location[0] === null || location[1] === null ? (
<>
{!toast.isActive(idToastError) &&
toast({
title: 'Erreur',
id: idToastError,
description: 'Veuillez autoriser la localisation',
status: 'error',
isClosable: false,
duration: 100000,
})}
<Text color="purple.500" fontSize="2xl" fontWeight="bold">
Veuillez autoriser la localisation
</Text>
</>
) : (
<Flex>
<MapContainer center={location} zoom={13} minZoom={8}
zoomControl={false}
style={{width: '100vw', height: '100vw'}}>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
/>
{/* Pour le user */}
<Marker icon={userIcon} position={location}></Marker>
<>
{location[0] === null || location[1] === null ? (
<>
{!toast.isActive(idToastError) &&
toast({
title: "Erreur",
id: idToastError,
description: "Veuillez autoriser la localisation",
status: "error",
isClosable: false,
duration: 100000,
})}
<Text color="purple.500" fontSize="2xl" fontWeight="bold">
Veuillez autoriser la localisation
</Text>
</>
) : (
<MapContainer
center={location}
zoom={13}
minZoom={8}
zoomControl={false}
style={{ width: "100vw", height: "100vw" }}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
attribution='&copy; <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'
/>
{/* Pour le user */}
<Marker icon={userIcon} position={location}></Marker>
<MarkerClusterGroup chunkedLoading showCoverageOnHover={false}>
{listBars.map((bar: any, index: number) => <MarkerBar key={index} bar={bar}/>)}
</MarkerClusterGroup>
</MapContainer>
</Flex>
)}
</>
<MarkerClusterGroup chunkedLoading showCoverageOnHover={false}>
{listBars.map((bar: any, index: number) => (
<MarkerBar key={index} bar={bar} />
))}
</MarkerClusterGroup>
</MapContainer>
)}
</>
);
}
+13 -8
View File
@@ -1,11 +1,14 @@
import { Marker, Popup } from "react-leaflet";
import "leaflet/dist/leaflet.css";
import { Box, Button, Text } from "@chakra-ui/react";
import { Box, Button, Text, useDisclosure } from "@chakra-ui/react";
import ModalInviteBar from "./ModalInviteBar";
import L, { LatLngTuple } from "leaflet";
export default function MarkerBar(props) {
export default function MarkerBar(props: any) {
const { bar } = props;
//changer l'icon
const { isOpen, onClose, onOpen } = useDisclosure();
const barIcon = new L.Icon({
iconUrl: "drink_cocktail.png",
iconSize: [35, 35],
@@ -13,17 +16,19 @@ export default function MarkerBar(props) {
backgroundColor: "purple",
});
const location = [bar.geo_point_2d.lat, bar.geo_point_2d.lon];
const location = [bar.geo_point_2d.lat, bar.geo_point_2d.lon] as LatLngTuple;
//mettre un tooltip...
return (
<Marker icon={barIcon} position={location}>
<Popup>
<Box alignItems={"center"}>
<Box align={"center"}>
<Text fontSize={"1rem"} fontWeight={"bold"} align={"center"}>
{bar.name || '"Nom du bar"'}
{bar.name}
</Text>
<Button variant={"outline"}>Inviter un match</Button>
<Button variant={"outline"} onClick={onOpen}>
Inviter un match
</Button>
<ModalInviteBar bar={bar} isOpen={isOpen} onClose={onClose} />
</Box>
</Popup>
</Marker>
@@ -0,0 +1,161 @@
import {
Box,
Button,
Card,
CardBody,
Flex,
Grid,
GridItem,
Modal,
ModalBody,
ModalCloseButton,
ModalContent,
ModalFooter,
ModalHeader,
Text,
useRadio,
useRadioGroup,
useToast,
} from "@chakra-ui/react";
import { Notification, NotificationType, User } from "@prisma/client";
import { useMutation, useQuery } from "@tanstack/react-query";
import { useSession } from "next-auth/react";
import type { Session } from "@/models/auth/Session";
import CardMatchedUser from "./CardMatchedUser";
import { Router } from "next/router";
import { log } from "console";
type ModalInviteBarProps = {
isOpen: boolean;
onClose: () => void;
bar: any;
};
export default function ModalInviteBar({
isOpen,
onClose,
bar,
}: ModalInviteBarProps) {
const { data: session, status } = useSession();
const toast = useToast();
const { value, getRadioProps, getRootProps } = useRadioGroup({
defaultValue: "-1",
});
const inviteToBar = useMutation({
mutationFn: async (id) => {
const inviteOptions = {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
idUser: id,
idUserMatched: value,
bar: bar,
}),
};
try {
const res = await fetch(`/api/user/inviteToBar`, inviteOptions);
const response = await res.json();
return response;
} catch (err) {
return err;
}
},
onSuccess: (data) => {
if (data.error) {
toast({
title: "Erreur",
description: "Une erreur est survenue",
status: "error",
duration: 2000,
});
return;
}
console.log(data);
},
});
const {
isLoading,
isError,
data: notificationMatch,
error,
} = useQuery({
queryKey: ["notificationMatch"],
enabled: status === "authenticated",
queryFn: async () => {
const { user } = session as unknown as Session;
return fetch(
`/api/notifications?where={"$and":{"UserID":"${user.id}", "type":"${NotificationType.NEW_MATCH}"}}`
)
.then((res) => {
return res.json();
})
.catch((err) => {
return err;
});
},
});
console.log(bar);
return (
<>
<Modal
blockScrollOnMount={false}
size={"2xl"}
isOpen={isOpen}
onClose={onClose}
scrollBehavior={"inside"}
>
<ModalContent>
<ModalHeader display={"flex"} alignItems={"center"} gap={2}>
Inviter au bar : {bar.name}
<Box as="span" fontSize={"3xl"}>
🍻
</Box>
</ModalHeader>
<ModalBody>
<Grid
{...getRootProps()}
templateColumns={`repeat(${notificationMatch?.length}, 1fr)`}
gap={6}
>
{!isError && !error
? notificationMatch?.map((notif: Notification) => {
return (
<CardMatchedUser
key={notif.MatchedUserID}
notif={notif}
{...getRadioProps({ value: notif.MatchedUserID })}
/>
);
})
: null}
</Grid>
</ModalBody>
<ModalFooter>
<Button
mr={3}
isDisabled={value === "-1"}
onClick={() => {
const { user } = session as unknown as Session;
inviteToBar.mutate(user.id);
onClose();
// Router.push("/chat");
}}
>
Inviter
</Button>
<Button variant="ghost" onClick={onClose}>
Annuler
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
);
}
@@ -14,64 +14,62 @@ import {
ModalOverlay,
useDisclosure,
useToast,
} from '@chakra-ui/react';
import {useQueryClient} from '@tanstack/react-query';
import {useState} from 'react';
import {RiEditBoxLine} from 'react-icons/ri';
} from "@chakra-ui/react";
import { useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { RiEditBoxLine } from "react-icons/ri";
export default function ModalModifyImages(props) {
const {isOpen, onOpen, onClose} = useDisclosure();
const {images, user, userData, setUserData} = props;
const { isOpen, onOpen, onClose } = useDisclosure();
const { images, user, userData, setUserData } = props;
const [listImage, setlistImage] = useState(images);
const toast = useToast({position: 'top', isClosable: true});
const toast = useToast({ position: "top", isClosable: true });
const client = useQueryClient();
const uploadImage = async (file) => {
const body = new FormData();
body.append('file', file);
body.append("file", file);
const imagePostOptions = {
method: 'POST',
method: "POST",
body,
};
const imagePatchOptions = {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
images: [...listImage, `imageUsers/${file.name}`],
}),
};
fetch(`/api/file/uploadFile`, imagePostOptions)
.then(res => {
fetch(`/api/users/${user.id}`, imagePatchOptions)
.then(res => {
toast({
title: `Ajout d'image effectué`,
status: 'success',
isClosable: true,
});
setlistImage([...listImage, `imageUsers/${file.name}`]);
// router.reload();
})
.catch(() => {
setIsLoading(false);
toast({
title: `Erreur lors de l'ajout des images`,
status: 'error',
isClosable: true,
});
});
})
.catch(err => {
toast({
title: `Erreur lors de l'ajout des images`,
status: 'error',
isClosable: true,
.then((res) => {
fetch(`/api/users/${user.id}`, imagePatchOptions)
.then((res) => {
toast({
title: `Ajout d'image effectué`,
status: "success",
isClosable: true,
});
setlistImage([...listImage, `imageUsers/${file.name}`]);
})
.catch(() => {
toast({
title: `Erreur lors de l'ajout des images`,
status: "error",
isClosable: true,
});
});
console.log(err);
})
.catch((err) => {
toast({
title: `Erreur lors de l'ajout des images`,
status: "error",
isClosable: true,
});
console.log(err);
});
};
const deleteImage = async (fileName) => {
@@ -84,97 +82,112 @@ export default function ModalModifyImages(props) {
}
const imageDeleteOptions = {
method: 'DELETE',
body: JSON.stringify({fileName: fileName.split('/').pop()}),
method: "DELETE",
body: JSON.stringify({ fileName: fileName.split("/").pop() }),
};
fetch(`/api/file/deleteFile`, imageDeleteOptions).then((res) => {
const imagePatchOptions = {
method: 'PUT',
headers: {'Content-Type': 'application/json'},
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
images: [...listImage],
}),
};
fetch(`/api/users/${user.id}`, imagePatchOptions)
.then((res) => {
toast({
title: `Suppression d'image effectué`,
status: 'success',
isClosable: true,
});
})
.catch(() => {
toast({
title: `Erreur lors de la suppression des images`,
status: 'error',
isClosable: true,
});
.then((res) => {
toast({
title: `Suppression d'image effectué`,
status: "success",
isClosable: true,
});
})
.catch(() => {
toast({
title: `Erreur lors de la suppression des images`,
status: "error",
isClosable: true,
});
});
});
};
return (
<>
<Button onClick={onOpen} leftIcon={<RiEditBoxLine/>}>
Modifier les images
</Button>
<>
<Button onClick={onOpen} leftIcon={<RiEditBoxLine />}>
Modifier les images
</Button>
<Modal blockScrollOnMount={false} size={'4xl'} isOpen={isOpen}
onClose={onClose} scrollBehavior={'inside'}>
<ModalOverlay/>
<ModalContent>
<ModalHeader>Modification des images</ModalHeader>
<ModalCloseButton/>
<ModalBody>
<Grid templateColumns={`repeat(${listImage.length + 1}, 1fr)`}
gap={5}>
{listImage.map((image, index) => (
<GridItem key={index}>
<Flex direction={'column'} gap={'1rem'}>
<Image src={image}/>
<Button id={index.toString()} colorScheme={'red'}
onClick={() =>
deleteImage(`${listImage[index]}`)}>
Supprimer l'image
</Button>
</Flex>
</GridItem>
))}
{listImage.length < 5 && (
<GridItem width={'100%'}>
<Input type={'file'} height={'100%'}
accept={'image/png, image/jpeg, image/webp'}
onInput={({target}) => {
const date = new Date();
const time = date.getTime();
<Modal
blockScrollOnMount={false}
size={"4xl"}
isOpen={isOpen}
onClose={onClose}
scrollBehavior={"inside"}
>
<ModalOverlay />
<ModalContent>
<ModalHeader>Modification des images</ModalHeader>
<ModalCloseButton />
<ModalBody>
<Grid
templateColumns={`repeat(${listImage.length + 1}, 1fr)`}
gap={5}
>
{listImage.map((image, index) => (
<GridItem key={index}>
<Flex direction={"column"} gap={"1rem"}>
<Image src={image} />
<Button
id={index.toString()}
colorScheme={"red"}
onClick={() => deleteImage(`${listImage[index]}`)}
>
Supprimer l'image
</Button>
</Flex>
</GridItem>
))}
{listImage.length < 5 && (
<GridItem width={"100%"}>
<Input
type={"file"}
height={"100%"}
accept={"image/png, image/jpeg, image/webp"}
onInput={({ target }) => {
const date = new Date();
const time = date.getTime();
const file = target.files[0];
const extension = file.name.split('.').pop();
const newFile = new File(
[file],
`${user.id}_${time}.${extension}`,
{
type: file.type,
},
);
uploadImage(newFile);
}}/>
</GridItem>
)}
</Grid>
</ModalBody>
const file = target.files[0];
const extension = file.name.split(".").pop();
const newFile = new File(
[file],
`${user.id}_${time}.${extension}`,
{
type: file.type,
}
);
uploadImage(newFile);
}}
/>
</GridItem>
)}
</Grid>
</ModalBody>
<ModalFooter>
<Button mr={3} onClick={() => {
client.invalidateQueries('user');
<ModalFooter>
<Button
mr={3}
onClick={() => {
client.invalidateQueries("user");
onClose();
}}>
Save
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
}}
>
Save
</Button>
</ModalFooter>
</ModalContent>
</Modal>
</>
);
}