From 92ae578bdb5defbd7d86504939058a6ffbbd4529 Mon Sep 17 00:00:00 2001 From: ayush Date: Mon, 13 Jan 2025 11:23:59 +0545 Subject: [PATCH] ayush --- .../show/[id]/_partials/CourseDiscussion.tsx | 244 +++++++----------- .../show/[id]/_partials/CourseMedia.tsx | 1 + 2 files changed, 88 insertions(+), 157 deletions(-) diff --git a/frontend/edu-connect/src/app/courses/show/[id]/_partials/CourseDiscussion.tsx b/frontend/edu-connect/src/app/courses/show/[id]/_partials/CourseDiscussion.tsx index 3c950b5..f7289d7 100644 --- a/frontend/edu-connect/src/app/courses/show/[id]/_partials/CourseDiscussion.tsx +++ b/frontend/edu-connect/src/app/courses/show/[id]/_partials/CourseDiscussion.tsx @@ -8,28 +8,26 @@ import { ScrollArea } from "@/components/ui/scroll-area"; import { MessageCircle, Reply, X } from "lucide-react"; import { APP_BASE_URL } from '@/utils/constants'; import { getEduConnectAccessToken } from '@/helpers/token.helper'; - -// Types -interface Reply { - id: number; - user: string; - avatar: string; - content: string; +import { usePathname } from 'next/navigation'; +import { fetchHeader } from '@/helpers/fetch.helper'; + +// Updated Types +interface Message { + id: string; + isSelf: number; + text: string; timestamp: string; + userId: string; + username: string; } -interface Discussion { - id: number; - user: string; - avatar: string; - content: string; - likes: number; - replies: Reply[]; - timestamp: string; +interface ApiResponse { + count: number; + messages: Message[]; } interface PageData { - discussions: Discussion[]; + messages: Message[]; hasMore: boolean; } @@ -39,20 +37,20 @@ interface DiscussionSectionProps { // Key generator for SWR const getKey = (courseUuid: string) => (pageIndex: number, previousPageData: PageData | null) => { - if (previousPageData && !previousPageData.discussions.length) return null; - return `${APP_BASE_URL}/api/chat/get?page=${pageIndex}`; + if (previousPageData && !previousPageData.messages.length) return null; + return `${APP_BASE_URL}/api/chat/get`; }; -// Fetcher function +// Updated fetcher function const fetcher = async (url: string, courseUuid: string): Promise => { const formData = new FormData(); - formData.append('course_uuid', courseUuid); + formData.append('course_id', courseUuid); const response = await fetch(url, { method: 'POST', - body: formData , - headers : { - Authorization : `Bearer ${getEduConnectAccessToken()}` + body: formData, + headers: { + Authorization: `Bearer ${getEduConnectAccessToken()}` } }); @@ -60,21 +58,22 @@ const fetcher = async (url: string, courseUuid: string): Promise => { throw new Error('Failed to fetch discussions'); } - const data = await response.json(); + const data: ApiResponse = await response.json(); return { - discussions: data.discussions.map((discussion: any) => ({ - ...discussion, - timestamp: new Date(discussion.timestamp).toLocaleString() + messages: data.messages.map(message => ({ + ...message, + timestamp: new Date(message.timestamp).toLocaleString() })), - hasMore: data.hasMore + hasMore: data.count > data.messages.length }; }; const EnhancedDiscussionSection: React.FC = ({ courseUuid }) => { const [comment, setComment] = useState(''); - const [replyingTo, setReplyingTo] = useState<{ commentId: number; userName: string } | null>(null); + const [replyingTo, setReplyingTo] = useState(null); const loadingRef = useRef(null); - const containerRef = useRef(null); + const pathname = usePathname(); + const id = pathname.split('/')?.at(-1); const { data, @@ -85,7 +84,7 @@ const EnhancedDiscussionSection: React.FC = ({ courseUui mutate } = useSWRInfinite( getKey(courseUuid), - (url) => fetcher(url, courseUuid), + (url) => fetcher(url, id!), { revalidateFirstPage: false, revalidateOnFocus: false, @@ -93,7 +92,7 @@ const EnhancedDiscussionSection: React.FC = ({ courseUui } ); - const allDiscussions = data ? data.flatMap(page => page.discussions) : []; + const allMessages = data ? data.flatMap(page => page.messages) : []; const hasMore = data ? data[data.length - 1]?.hasMore : true; const isLoadingMore = !data && !error || (size > 0 && data && typeof data[size - 1] === "undefined"); @@ -115,137 +114,79 @@ const EnhancedDiscussionSection: React.FC = ({ courseUui return () => observer.disconnect(); }, [hasMore, isValidating, setSize, size]); - const handleSubmit = async () => { - if (comment.trim()) { - const formData = new FormData(); - formData.append('course_uuid', courseUuid); - formData.append('content', comment); - if (replyingTo) { - formData.append('parent_id', replyingTo.commentId.toString()); - } + const handleSubmit = async () => { + if (comment.trim()) { + const formData = new FormData(); + formData.append('course_id', courseUuid); + formData.append('message', comment); + // if (replyingTo) { + // formData.append('parent_id', replyingTo.commentId.toString()); + // } + + try { + const response = await fetch(`${APP_BASE_URL}/api/chat/send`, { + method: 'POST', + body: formData, + headers : fetchHeader() + }); - try { - const response = await fetch('/api/chat/post', { - method: 'POST', - body: formData - }); + if (!response.ok) { + throw new Error('Failed to post comment'); + } - if (!response.ok) { - throw new Error('Failed to post comment'); - } - const newComment = await response.json(); + // Optimistically update the UI + - // Optimistically update the UI - const updatedData = [...(data || [])]; - if (replyingTo) { - // Update the discussion with the new reply - updatedData.forEach(page => { - page.discussions = page.discussions.map(discussion => { - if (discussion.id === replyingTo.commentId) { - return { - ...discussion, - replies: [...discussion.replies, { - ...newComment, - timestamp: 'Just now' - }] - }; - } - return discussion; - }); - }); - } else { - // Add new top-level comment - if (updatedData[0]) { - updatedData[0].discussions = [{ - ...newComment, - replies: [], - timestamp: 'Just now' - }, ...updatedData[0].discussions]; - } + await mutate(); + setComment(''); + setReplyingTo(null); + } catch (error) { + console.error('Failed to post comment:', error); + // You might want to show an error message to the user here } - - await mutate(updatedData, false); - setComment(''); - setReplyingTo(null); - } catch (error) { - console.error('Failed to post comment:', error); - // You might want to show an error message to the user here } + }; + + const handleReply = (commentId: number, userName: string) => { + setReplyingTo({ commentId, userName }); + setComment(`@${userName} `); + }; + + const cancelReply = () => { + setReplyingTo(null); + setComment(''); + }; + + if (error) { + return ( +
+ Error loading discussions. Please try again later. +
+ ); } - }; - - const handleReply = (commentId: number, userName: string) => { - setReplyingTo({ commentId, userName }); - setComment(`@${userName} `); - }; - - const cancelReply = () => { - setReplyingTo(null); - setComment(''); - }; - - if (error) { - return ( -
- Error loading discussions. Please try again later. -
- ); - } + // Rest of your component implementation remains similar, just update the rendering logic: return (
- {allDiscussions.map((discussion) => ( - + {allMessages.map((message) => ( +
- - {discussion.user[0]} + + {message.username[0]}
- {discussion.user} - {discussion.timestamp} -
-

{discussion.content}

-
- -
- - {discussion.replies.length} replies -
+ {message.username} + {message.timestamp}
+

{message.text}

- - {discussion.replies.length > 0 && ( -
- {discussion.replies.map((reply) => ( -
- - - {reply.user[0]} - -
-
- {reply.user} - {reply.timestamp} -
-

{reply.content}

-
-
- ))} -
- )}
))} @@ -254,8 +195,8 @@ const EnhancedDiscussionSection: React.FC = ({ courseUui {isLoadingMore && (
)} - {!hasMore && allDiscussions.length > 0 && ( -
No more discussions
+ {!hasMore && allMessages.length > 0 && ( +
No more messages
)}
@@ -268,26 +209,15 @@ const EnhancedDiscussionSection: React.FC = ({ courseUui U
- {replyingTo && ( -
- Replying to {replyingTo.userName} - -
- )}