From 650a1fe5c81a4e0ce0930a89badf77e1ef5fccee Mon Sep 17 00:00:00 2001 From: Aamil13 Date: Sat, 13 Jul 2024 16:07:29 +0530 Subject: [PATCH] implemented socketio for notification and community-group-user role change --- package-lock.json | 67 +++++++- package.json | 1 + src/app/community/[id]/page.tsx | 36 +++- src/components/Navbar/Navbar.tsx | 153 ++++++++++++----- src/components/Navbar/constant.ts | 8 + .../Notifiaction/AssignNotification.tsx | 43 +++++ .../Notifiaction/CommentNotification.tsx | 43 +++++ .../Notifiaction/InviteNotification.tsx | 59 +++++++ src/components/Timeline/Post.tsx | 13 +- src/components/Timeline/PostInput.tsx | 2 +- .../AssignGroupModerators.tsx | 92 ++++++++++ .../communityUniversity/GroupInfo.tsx | 160 +++++++++--------- src/services/community-university.ts | 48 +++++- src/services/edit-profile.ts | 2 +- src/services/notification.ts | 7 +- src/services/user.ts | 27 +++ src/store/userSlice/userSlice.ts | 22 ++- src/store/userSlice/userType.ts | 1 + 18 files changed, 646 insertions(+), 138 deletions(-) create mode 100644 src/components/Notifiaction/AssignNotification.tsx create mode 100644 src/components/Notifiaction/CommentNotification.tsx create mode 100644 src/components/Notifiaction/InviteNotification.tsx create mode 100644 src/components/communityUniversity/AssignGroupModerators.tsx create mode 100644 src/services/user.ts diff --git a/package-lock.json b/package-lock.json index 53a26da0..70af92d2 100644 --- a/package-lock.json +++ b/package-lock.json @@ -48,6 +48,7 @@ "react-share": "^5.1.0", "react-type-animation": "^3.2.0", "sharp": "^0.33.4", + "socket.io-client": "^4.7.5", "storybook-addon-apollo-client": "^5.0.0", "swiper": "^11.0.7", "tailwind-merge": "^2.3.0", @@ -4466,6 +4467,11 @@ "@sinonjs/commons": "^3.0.0" } }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==" + }, "node_modules/@storybook/addon-actions": { "version": "7.4.4", "resolved": "https://registry.npmjs.org/@storybook/addon-actions/-/addon-actions-7.4.4.tgz", @@ -10997,6 +11003,26 @@ "objectorarray": "^1.0.5" } }, + "node_modules/engine.io-client": { + "version": "6.5.4", + "resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.5.4.tgz", + "integrity": "sha512-GeZeeRjpD2qf49cZQ0Wvh/8NJNfeXkXXcoGh+F77oEAgo9gUHwT1fCRxSNU+YEEaysOJTnsFHmM5oAcPy4ntvQ==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1", + "xmlhttprequest-ssl": "~2.0.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.2.tgz", + "integrity": "sha512-RcyUFKA93/CXH20l4SoVvzZfrSDMOTUS3bWVpTt2FuFP+XYrL8i8oonHP7WInRyVHXh0n/ORtoeiE1os+8qkSw==", + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/enhanced-resolve": { "version": "5.15.0", "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.15.0.tgz", @@ -19897,6 +19923,32 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/socket.io-client": { + "version": "4.7.5", + "resolved": "https://registry.npmjs.org/socket.io-client/-/socket.io-client-4.7.5.tgz", + "integrity": "sha512-sJ/tqHOCe7Z50JCBCXrsY3I2k03iOiUe+tj1OmKeD2lXPiGH/RUCdTZFoqVyN7l1MnpIzPrGtLcijffmeouNlQ==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.2", + "engine.io-client": "~6.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/socket.io-parser": { + "version": "4.2.4", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", + "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.1" + }, + "engines": { + "node": ">=10.0.0" + } + }, "node_modules/source-list-map": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/source-list-map/-/source-list-map-2.0.1.tgz", @@ -22478,10 +22530,9 @@ } }, "node_modules/ws": { - "version": "8.14.2", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.14.2.tgz", - "integrity": "sha512-wEBG1ftX4jcglPxgFCMJmZ2PLtSbJ2Peg6TmpJFTbe9GZYOQCDPdMYu/Tm0/bGZkw8paZnJY45J4K2PZrLYq8g==", - "dev": true, + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "engines": { "node": ">=10.0.0" }, @@ -22513,6 +22564,14 @@ "integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==", "dev": true }, + "node_modules/xmlhttprequest-ssl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/xmlhttprequest-ssl/-/xmlhttprequest-ssl-2.0.0.tgz", + "integrity": "sha512-QKxVRxiRACQcVuQEYFsI1hhkrMlrXHPegbbd1yn9UHOmRxY+si12nQYzri3vbzt8VdTTRviqcKxcyllFas5z2A==", + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/xtend": { "version": "4.0.2", "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", diff --git a/package.json b/package.json index c43def2d..5e632024 100644 --- a/package.json +++ b/package.json @@ -66,6 +66,7 @@ "react-share": "^5.1.0", "react-type-animation": "^3.2.0", "sharp": "^0.33.4", + "socket.io-client": "^4.7.5", "storybook-addon-apollo-client": "^5.0.0", "swiper": "^11.0.7", "tailwind-merge": "^2.3.0", diff --git a/src/app/community/[id]/page.tsx b/src/app/community/[id]/page.tsx index bc6ac0b8..e09f8dd2 100644 --- a/src/app/community/[id]/page.tsx +++ b/src/app/community/[id]/page.tsx @@ -13,7 +13,7 @@ import { useGetCommunity, useGetCommunityGroupPost, useGetCommunityGroups } from import { useUniStore } from '@/store/store' import { ModalContentType } from '@/types/global' import { useParams } from 'next/navigation' -import React, { useState } from 'react' +import React, { useEffect, useState } from 'react' import { IoIosArrowDown } from 'react-icons/io' import Navbar from '@/components/Timeline/Navbar' @@ -27,7 +27,7 @@ const roberta = { const Page = () => { const [isModalOpen, setIsModalOpen] = useState(false) const [modalContentType, setModalContentType] = useState() - + const [currUserGroupRole, setCurrUserGroupRole] = useState('') const { id } = useParams<{ id: string }>() const { data } = useGetCommunity(id) const { userData, userProfileData } = useUniStore() @@ -50,7 +50,26 @@ const Page = () => { return null } } + // console.log('curr', communityGroupPost) + + useEffect(() => { + const findGroupRole = (communities: any) => { + return communities?.some((community: any) => { + return community.communityGroups.some((group: any) => { + if (group.communityGroupId === currSelectedGroup?._id) { + setCurrUserGroupRole(group.role) + return true + } + return false + }) + }) + } + if (!findGroupRole(userData.userVerifiedCommunities)) { + findGroupRole(userData.userUnVerifiedCommunities) + } + }, [currSelectedGroup, userData]) + // console.log('role', currUserGroupRole, currSelectedGroup?.adminUserId?._id, userData?.id) return ( <> setIsModalOpen(false)}> @@ -83,24 +102,27 @@ const Page = () => { ) : (
- {currSelectedGroup?.adminUserId?._id == userData?.id && ( + {currUserGroupRole === 'Admin' || currUserGroupRole === 'Moderator' ? ( + ) : ( + '' )}
{communityGroupPost?.communityPosts.map((item: any) => (
{ const [isMobile] = useState(false) const [width] = useWindowSize() @@ -42,13 +50,31 @@ const Navbar: React.FC = () => { const [activeItem, setActiveItem] = useState('') // eslint-disable-next-line no-unused-vars const [, , deleteCookie] = useCookie('uni_user_token') - const { userProfileData, userData, resetUserData, resetUserProfileData, resetUserFollowingData } = useUniStore() + const { + userProfileData, + userData, + resetUserData, + resetUserProfileData, + resetUserFollowingData, + setUserUnVerifiedCommunities, + setUserVerifiedCommunities, + } = useUniStore() const router = useRouter() // console.log(cookieValue) - const { data: notificationData } = useGetNotification() - const { mutate: joinGroup } = useJoinCommunityGroup() - const { mutate: updateIsSeen } = useUpdateIsSeenCommunityGroupNotification() + const { data: notificationData, refetch: refetchNotification } = useGetNotification() + const { refetch: refetchUserData, data: RefetcheduserData } = useGetUserData() + const [isRefetched, setIsRefetched] = useState(false) + const [isNotificationOpen, setIsNotificationOpen] = useState(false) // console.log('noti', notificationData) + // console.log('RefetcheduserData', RefetcheduserData) + + useEffect(() => { + if (isRefetched) { + setUserUnVerifiedCommunities(RefetcheduserData?.user?.userUnVerifiedCommunities) + setUserVerifiedCommunities(RefetcheduserData?.user?.userVerifiedCommunities) + setIsRefetched(false) + } + }, [RefetcheduserData]) useEffect(() => { // console.log('cookieValue', cookieValue) @@ -75,48 +101,95 @@ const Navbar: React.FC = () => { } }, [width]) - const handleJoinGroup = (data: any) => { - const dataToPush = { - groupId: data.communityGroupId._id, - id: data._id, - } - // console.log('nData', dataToPush) - joinGroup(dataToPush) - } + //socket.io + + let socket: Socket + + useEffect(() => { + socket = io('http://localhost:9000') + + // console.log(socket) - const handleIsSeenGroup = (data: any) => { - const dataToPush = { - // groupId: data.communityGroupId._id, - id: data._id, + socket.on('connect', () => { + console.log('Connected to the server') + }) + + socket.on('disconnect', () => { + console.log('Disconnected from the server') + }) + + socket.on(`notification_${userData.id}`, (notification: notification) => { + // console.log(notification) + // console.log('sss', notification.message) + + if (notification.message == 'You have a been assigned') { + refetchUserData() + // console.log(); + setIsRefetched(true) + } + refetchNotification() + }) + + return () => { + socket.disconnect() } - // console.log('nData', dataToPush) - updateIsSeen(dataToPush) - } + }, [userData.id]) const LoggedInMenu = () => { return (
- + setIsNotificationOpen(!isNotificationOpen)}> - - - - {notificationData?.map((item: any) => ( -
-

- You Received an invite from {item?.adminId?.firstName} to Join Group +

+ + {notificationData?.length ? ( +

+ {notificationData?.length > 9 ? '9+' : notificationData?.length}

-
- - -
-
- ))} + ) : ( + '' + )} +
+ + + {notificationData?.length ? ( + notificationData?.map((item: any) => + item.type == notificationRoleAccess.GROUP_INVITE ? ( + + ) : item.type == notificationRoleAccess.COMMENT ? ( + + ) : item.type == notificationRoleAccess.ASSIGN ? ( + + ) : ( + '' + ) + ) + ) : ( +

No Notification

+ )}
{/* notificaton End */} diff --git a/src/components/Navbar/constant.ts b/src/components/Navbar/constant.ts index 15ba6b13..2d0f745c 100644 --- a/src/components/Navbar/constant.ts +++ b/src/components/Navbar/constant.ts @@ -55,3 +55,11 @@ export const menuContent = [ display: 'lap', }, ] + +export const notificationRoleAccess = { + GROUP_INVITE: 'GROUP_INVITE', + REPLY: 'REPLY', + FOLLOW: 'FOLLOW', + ASSIGN: 'ASSIGN', + COMMENT: 'COMMENT', +} diff --git a/src/components/Notifiaction/AssignNotification.tsx b/src/components/Notifiaction/AssignNotification.tsx new file mode 100644 index 00000000..cd62673a --- /dev/null +++ b/src/components/Notifiaction/AssignNotification.tsx @@ -0,0 +1,43 @@ +import { useUpdateIsSeenCommunityGroupNotification } from '@/services/notification' +import React from 'react' +import dayjs from 'dayjs' +import relativeTime from 'dayjs/plugin/relativeTime' + +dayjs.extend(relativeTime) +type Props = { + id: string + senderName: string + message: string + communityGroupId: string + createdAt: string +} + +const AssignNotification = ({ id, senderName, communityGroupId, message, createdAt }: Props) => { + const { mutate: updateIsSeen } = useUpdateIsSeenCommunityGroupNotification() + console.log('postId', communityGroupId) + + const handleIsSeenGroup = (id: string) => { + const dataToPush = { + // groupId: data.communityGroupId._id, + id: id, + } + // console.log('nData', dataToPush) + updateIsSeen(dataToPush) + } + + return ( +
+

+ {senderName} {message} +

+
+

{dayjs(new Date(createdAt).toString()).fromNow()}

+ +
+
+ ) +} + +export default AssignNotification diff --git a/src/components/Notifiaction/CommentNotification.tsx b/src/components/Notifiaction/CommentNotification.tsx new file mode 100644 index 00000000..8168b949 --- /dev/null +++ b/src/components/Notifiaction/CommentNotification.tsx @@ -0,0 +1,43 @@ +import React from 'react' +import { useUpdateIsSeenCommunityGroupNotification } from '@/services/notification' +import dayjs from 'dayjs' +import relativeTime from 'dayjs/plugin/relativeTime' + +dayjs.extend(relativeTime) + +type Props = { + id: string + senderName: string + message: string + communityPostId: string + createdAt: string +} + +const CommentNotification = ({ id, senderName, communityPostId, message, createdAt }: Props) => { + const { mutate: updateIsSeen } = useUpdateIsSeenCommunityGroupNotification() + console.log('postId', communityPostId) + + const handleIsSeenGroup = (id: string) => { + const dataToPush = { + // groupId: data.communityGroupId._id, + id: id, + } + // console.log('nData', dataToPush) + updateIsSeen(dataToPush) + } + return ( +
+

+ {senderName} {message} +

+
+

{dayjs(new Date(createdAt).toString()).fromNow()}

+ +
+
+ ) +} + +export default CommentNotification diff --git a/src/components/Notifiaction/InviteNotification.tsx b/src/components/Notifiaction/InviteNotification.tsx new file mode 100644 index 00000000..41778d68 --- /dev/null +++ b/src/components/Notifiaction/InviteNotification.tsx @@ -0,0 +1,59 @@ +import React from 'react' +import { useJoinCommunityGroup, useUpdateIsSeenCommunityGroupNotification } from '@/services/notification' + +import dayjs from 'dayjs' +import relativeTime from 'dayjs/plugin/relativeTime' + +dayjs.extend(relativeTime) +type Props = { + id: string + senderName: string + groupName: string + message: string + groupId: string + createdAt: string +} + +const InviteNotification = ({ id, groupId, senderName, groupName, message, createdAt }: Props) => { + const { mutate: joinGroup } = useJoinCommunityGroup() + const { mutate: updateIsSeen } = useUpdateIsSeenCommunityGroupNotification() + + const handleJoinGroup = (groupId: string, id: string) => { + const dataToPush = { + groupId: groupId, + id: id, + } + // console.log('nData', dataToPush) + joinGroup(dataToPush) + } + + const handleIsSeenGroup = (id: string) => { + const dataToPush = { + // groupId: data.communityGroupId._id, + id: id, + } + // console.log('nData', dataToPush) + updateIsSeen(dataToPush) + } + + return ( +
+

+ {message} {groupName} from {senderName} +

+
+

{dayjs(new Date(createdAt).toString()).fromNow()}

+ <> + + + +
+
+ ) +} + +export default InviteNotification diff --git a/src/components/Timeline/Post.tsx b/src/components/Timeline/Post.tsx index 2f7adbf2..3d977fd8 100644 --- a/src/components/Timeline/Post.tsx +++ b/src/components/Timeline/Post.tsx @@ -57,6 +57,7 @@ interface PostProps { isUniversity?: boolean postID?: string profileDp?: string + adminId: string } const PostOptions = () => { @@ -150,6 +151,7 @@ const Post: React.FC = ({ isUniversity, postID, profileDp, + adminId, }) => { const { mutate: LikeUnlikePost } = useLikeUnilikeGroupPost() const { mutate: CreateComment } = useCreateGroupPostComment() @@ -159,6 +161,7 @@ const Post: React.FC = ({ const [showCommentSec, setShowCommentsec] = useState(false) const { userData } = useUniStore() + // console.log('add', adminId) const LikesUserId: string[] = Array.isArray(likes) ? likes.map((item) => item.userId) : [] const handlePostComment = async () => { @@ -172,12 +175,14 @@ const Post: React.FC = ({ postID: postID, content: comment, imageUrl: { imageUrl: imagedata?.imageUrl, publicId: imagedata?.publicId }, + adminId, } CreateComment(data) } else { const data = { postID: postID, content: comment, + adminId, } CreateComment(data) } @@ -199,10 +204,14 @@ const Post: React.FC = ({ {/* User Info */}
- {`${user}'s + {avatar ? ( + {`${user}'s + ) : ( +
+ )}

{user}

-

{university}

+

{university ? university : 'not available'}

{!year.includes('undefined') ? year : ''}

diff --git a/src/components/Timeline/PostInput.tsx b/src/components/Timeline/PostInput.tsx index abc395c8..71acdeb6 100644 --- a/src/components/Timeline/PostInput.tsx +++ b/src/components/Timeline/PostInput.tsx @@ -78,7 +78,7 @@ const PostInput: React.FC = ({ setIsModalOpen, setModalContentTy )}
- setImageValue(e.target.files[0])} /> + setImageValue(e.target.files[0])} /> diff --git a/src/components/communityUniversity/AssignGroupModerators.tsx b/src/components/communityUniversity/AssignGroupModerators.tsx new file mode 100644 index 00000000..8007c9f7 --- /dev/null +++ b/src/components/communityUniversity/AssignGroupModerators.tsx @@ -0,0 +1,92 @@ +import { useGetCommunityGroupUsers, useUserGroupRole } from '@/services/community-university' +import React, { useState } from 'react' +import { RxCross2 } from 'react-icons/rx' +type Props = { + setAssignUsers: (value: boolean) => void + assignUsers: boolean + id: string +} + +const AssignGroupModerators = ({ setAssignUsers, assignUsers, id }: Props) => { + const [searchInput, setSearchInput] = useState('') + const { data } = useGetCommunityGroupUsers(id, assignUsers, 'Public', searchInput) + const { mutate: userGroupRole } = useUserGroupRole() + console.log('groupUsers', data) + + const handleChange = (e: any, communityGroupId: string, id: string) => { + console.log(e.target.value, communityGroupId) + const data = { + role: e.target.value, + communityGroupId: communityGroupId, + id: id, + } + userGroupRole(data) + } + return ( + <> + {assignUsers && ( + <> +
+ +
+
+
+

Add Community members

+ setAssignUsers(false)} size={24} color="#737373" /> +
+ {/* search */} +
+ + + + setSearchInput(e.target.value)} + value={searchInput} + type="text" + placeholder="Search users by name" + className="w-full pl-12 pr-3 py-2 text-gray-500 bg-transparent outline-none border border-neutral-300 rounded-2xl" + /> +
+ {/* uses */} + {data?.user?.map((item: any) => ( +
+
+ {item?.profile?.profile_dp?.imageUrl ? ( + + ) : ( +
+ )} +
+

{item?.firstName}

+

{item?.profile?.university_name ? item?.profile?.university_name : 'Not Availaible'}

+

+ {item?.profile?.study_year} {item?.profile?.study_year ? 'Year' : ''} {item?.profile?.degree} +

+
+
+ {/* */} + +
+ ))} +
+ + )} + + ) +} + +export default AssignGroupModerators diff --git a/src/components/communityUniversity/GroupInfo.tsx b/src/components/communityUniversity/GroupInfo.tsx index 1f8120c7..5cc24635 100644 --- a/src/components/communityUniversity/GroupInfo.tsx +++ b/src/components/communityUniversity/GroupInfo.tsx @@ -5,6 +5,7 @@ import React, { useEffect, useMemo, useState } from 'react' import { FaLock } from 'react-icons/fa' import { CiImageOn } from 'react-icons/ci' import { IoMdSettings } from 'react-icons/io' +import AssignGroupModerators from './AssignGroupModerators' const GroupInfo = ({ data, isJoinedinCommunity, setIsJoinedInGroup, isJoinedInGroup }: any) => { const { mutate: JoinCommunityGroup } = useJoinCommunityGroup() @@ -14,7 +15,7 @@ const GroupInfo = ({ data, isJoinedinCommunity, setIsJoinedInGroup, isJoinedInGr const [logoImage, setLogoImage] = useState('') const [tempImg, setTempImg] = useState('') const [uploadFunc, setUploadFunc] = useState('') - + const [assignUsers, setAssignUsers] = useState(false) const userVerifiedCommunityGroupIds = useMemo(() => { return userData?.userVerifiedCommunities?.flatMap((x) => x.communityGroups.map((y) => y.communityGroupId.toString())) || [] }, [userData]) @@ -82,92 +83,95 @@ const GroupInfo = ({ data, isJoinedinCommunity, setIsJoinedInGroup, isJoinedInGr } return ( -
- {/* top section */} -
- {coverImage ? ( - <> - bg -
-
+ <> + +
+ {/* top section */} +
+ {coverImage ? ( + <> + bg +
+
+ handleCoverImageUpload(e)} /> + +
+
+ + ) : ( + <> +
+
handleCoverImageUpload(e)} />
+ + )} + {logoImage ? ( +
+ dp +
+ handleLogoImageUpload(e)} /> + +
- - ) : ( - <> -
-
- handleCoverImageUpload(e)} /> - -
- - )} - {logoImage ? ( -
- dp -
- handleLogoImageUpload(e)} /> - + ) : ( +
+
+ handleLogoImageUpload(e)} /> + +
-
- ) : ( -
-
- handleLogoImageUpload(e)} /> - + )} +
+ {/* name */} +
+
+
+ {data?.title} {data?.communityGroupType == 'private' && } +
+

+ {data?.description ? data?.description : 'No Description'} + {/* Undergraduate research group at the department of chemistry at Loreum’s . */} +

+

{data?.memberCount} Members

+
+

{data?.memberCount} Members

+ {data?.adminUserId?._id == userData.id ? ( + + ) : ( + + )}
- )} -
- {/* name */} -
-
-
- {data?.title} {data?.communityGroupType == 'private' && } -
-

- {data?.description ? data?.description : 'No Description'} - {/* Undergraduate research group at the department of chemistry at Loreum’s . */} -

-

{data?.memberCount} Members

-
-

{data?.memberCount} Members

- {data?.adminUserId?._id == userData.id ? ( - - ) : ( - - )} -
+ {data?.adminUserId?._id == userData.id ? ( + + ) : ( + + )}
- {data?.adminUserId?._id == userData.id ? ( - - ) : ( - - )}
-
+ ) } diff --git a/src/services/community-university.ts b/src/services/community-university.ts index 08bd0e87..8b5db71e 100644 --- a/src/services/community-university.ts +++ b/src/services/community-university.ts @@ -25,11 +25,23 @@ export async function getCommunityUsers(communityId: string, privacy: string, na return response } +export async function getCommunityGroupUsers(communityGroupId: string, privacy: string, name: string, token: any) { + const response: any = await client(`/users/communityGroupUsers/${communityGroupId}?privacy=${privacy}&&name=${name}`, { + headers: { Authorization: `Bearer ${token}` }, + }) + return response +} + export async function LeaveCommunity(communityId: string, token: any) { const response = await client(`/users/leave/${communityId}`, { method: 'PUT', headers: { Authorization: `Bearer ${token}` } }) return response } +export async function changeUserGroupRole(data: any, token: any) { + const response = await client(`/users/user/GroupRole`, { method: 'PUT', headers: { Authorization: `Bearer ${token}` }, data }) + return response +} + export async function getAllCommunityGroups(communityId: string, token: any) { const response: any = await client(`/communitygroup/${communityId}`, { headers: { Authorization: `Bearer ${token}` } }) return response @@ -176,12 +188,13 @@ export const useJoinCommunityGroup = () => { export const useCreateCommunityGroup = () => { const [cookieValue] = useCookie('uni_user_token') const queryClient = useQueryClient() + const { setUserData } = useUniStore() return useMutation({ mutationFn: ({ communityId, data }: any) => CreateCommunityGroup(communityId, cookieValue, data), onSuccess: (response: any) => { console.log(response) - + setUserData(response.userData) queryClient.invalidateQueries({ queryKey: ['communityGroups'] }) }, onError: (res: any) => { @@ -301,3 +314,36 @@ export function useGetCommunityUsers(communityId: string, isopen: boolean, priva return { isLoading, data, error: errorMessage } } + +export function useGetCommunityGroupUsers(communityGroupId: string, isopen: boolean, privacy: string, name: string) { + const [cookieValue] = useCookie('uni_user_token') + const { isLoading, data, error } = useQuery({ + enabled: isopen, + queryKey: ['communityGroupUsers', communityGroupId, privacy, name], + queryFn: () => getCommunityGroupUsers(communityGroupId, privacy, name, cookieValue), + }) + + let errorMessage = null + if (axios.isAxiosError(error) && error.response) { + errorMessage = error.response.data + } + + return { isLoading, data, error: errorMessage } +} + +export const useUserGroupRole = () => { + const [cookieValue] = useCookie('uni_user_token') + const queryClient = useQueryClient() + return useMutation({ + mutationFn: (data: any) => changeUserGroupRole(data, cookieValue), + + onSuccess: (response: any) => { + console.log(response) + + queryClient.invalidateQueries({ queryKey: ['communityGroupUsers'] }) + }, + onError: (res: any) => { + console.log(res.response.data.message, 'res') + }, + }) +} diff --git a/src/services/edit-profile.ts b/src/services/edit-profile.ts index 7abb253b..40233114 100644 --- a/src/services/edit-profile.ts +++ b/src/services/edit-profile.ts @@ -3,7 +3,7 @@ import { client } from './api-Client' import { useUniStore } from '@/store/store' const editProfile = async (data: any, id: string) => { - const res = await client(`userprofile/${id}`, { method: 'PUT', data }) + const res = await client(`/userprofile/${id}`, { method: 'PUT', data }) return res } diff --git a/src/services/notification.ts b/src/services/notification.ts index 16c6865e..d5655daa 100644 --- a/src/services/notification.ts +++ b/src/services/notification.ts @@ -2,6 +2,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { client } from './api-Client' import axios from 'axios' import useCookie from '@/hooks/useCookie' +import { useUniStore } from '@/store/store' export async function getUserNotification(token: any) { const response = await client(`/notification/`, { headers: { Authorization: `Bearer ${token}` } }) @@ -21,7 +22,7 @@ export async function UpdateCommunityGroup(data: any, token: any) { export function useGetNotification() { const [cookieValue] = useCookie('uni_user_token') - const { isLoading, data, error } = useQuery({ + const { isLoading, data, error, refetch } = useQuery({ queryKey: ['notification'], queryFn: () => getUserNotification(cookieValue), enabled: !!cookieValue, @@ -32,17 +33,19 @@ export function useGetNotification() { errorMessage = error.response.data } - return { isLoading, data, error: errorMessage } + return { isLoading, data, error: errorMessage, refetch } } export const useJoinCommunityGroup = () => { const [cookieValue] = useCookie('uni_user_token') + const { setUserData } = useUniStore() const queryClient = useQueryClient() return useMutation({ mutationFn: (data: any) => JoinCommunityGroup(data, cookieValue), onSuccess: (response: any) => { console.log(response) + setUserData(response.user) queryClient.invalidateQueries({ queryKey: ['notification'] }) }, onError: (res: any) => { diff --git a/src/services/user.ts b/src/services/user.ts new file mode 100644 index 00000000..10bd562d --- /dev/null +++ b/src/services/user.ts @@ -0,0 +1,27 @@ +import useCookie from '@/hooks/useCookie' +import { useQuery } from '@tanstack/react-query' +import { client } from './api-Client' +import axios from 'axios' +import { useUniStore } from '@/store/store' + +export async function getUserData(token: any, id: string) { + const response: any = await client(`/users/${id}`, { headers: { Authorization: `Bearer ${token}` } }) + return response +} + +export function useGetUserData() { + const [cookieValue] = useCookie('uni_user_token') + const { userData } = useUniStore() + const { isLoading, data, error, refetch } = useQuery({ + queryKey: ['getRefetchUserData'], + queryFn: () => getUserData(cookieValue, userData.id), + enabled: !!cookieValue, + }) + + let errorMessage = null + if (axios.isAxiosError(error) && error.response) { + errorMessage = error.response.data + } + + return { isLoading, data, error: errorMessage, refetch } +} diff --git a/src/store/userSlice/userSlice.ts b/src/store/userSlice/userSlice.ts index 9217b3ac..4b6a7daf 100644 --- a/src/store/userSlice/userSlice.ts +++ b/src/store/userSlice/userSlice.ts @@ -8,6 +8,8 @@ type userState = { type userAction = { setUserData: (userData: userType) => void resetUserData: () => void + setUserVerifiedCommunities: (communities: userType['userVerifiedCommunities']) => void + setUserUnVerifiedCommunities: (communities: userType['userUnVerifiedCommunities']) => void } const initialState: userState = { @@ -22,8 +24,10 @@ const initialState: userState = { role: '', isEmailVerified: false, // createdAt: '', - userVerifiedCommunities: [{ communityId: '', communityName: '', communityGroups: [{ communityGroupName: '', communityGroupId: '' }] }], - userUnVerifiedCommunities: [{ communityId: '', communityName: '', communityGroups: [{ communityGroupName: '', communityGroupId: '' }] }], + userVerifiedCommunities: [{ communityId: '', communityName: '', communityGroups: [{ communityGroupName: '', communityGroupId: '', role: '' }] }], + userUnVerifiedCommunities: [ + { communityId: '', communityName: '', communityGroups: [{ communityGroupName: '', communityGroupId: '', role: '' }] }, + ], }, } @@ -33,4 +37,18 @@ export const createUserSlice: StateCreator = (set) => ({ userData: initialState.userData, setUserData: (userData: userType) => set({ userData }), resetUserData: () => set(initialState), + setUserVerifiedCommunities: (communities) => + set((state) => ({ + userData: { + ...state.userData, + userVerifiedCommunities: communities, + }, + })), + setUserUnVerifiedCommunities: (communities) => + set((state) => ({ + userData: { + ...state.userData, + userUnVerifiedCommunities: communities, + }, + })), }) diff --git a/src/store/userSlice/userType.ts b/src/store/userSlice/userType.ts index aaa8b4e1..18fafc37 100644 --- a/src/store/userSlice/userType.ts +++ b/src/store/userSlice/userType.ts @@ -1,6 +1,7 @@ interface communityGroupsInterface { communityGroupName: string communityGroupId: string + role: string } interface verifiedInterface {