Skip to content

Commit

Permalink
now pulls messages in the chat
Browse files Browse the repository at this point in the history
when a chat is selected the messages are displayed
  • Loading branch information
Taseen18 committed Mar 30, 2024
1 parent 9cb4b85 commit 951f1d2
Show file tree
Hide file tree
Showing 9 changed files with 127 additions and 22 deletions.
Binary file modified backend/chat/__pycache__/db_service.cpython-311.pyc
Binary file not shown.
Binary file modified backend/chat/__pycache__/urls.cpython-311.pyc
Binary file not shown.
Binary file modified backend/chat/__pycache__/views.cpython-311.pyc
Binary file not shown.
1 change: 1 addition & 0 deletions backend/chat/authentication.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#this file is a copy from the file in authentication app. this file is not needed but im too scared to remove it.
from django.contrib.auth.models import User
from django.conf import settings
from rest_framework import authentication, exceptions
Expand Down
10 changes: 5 additions & 5 deletions backend/chat/db_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def check_user_type(user_id):

if response.data:
print("User found as a MHP.")
return "MHP"
return "mhp"
else:
print("User not found as MHP, marked as employee.")
return "employee"
Expand All @@ -35,8 +35,8 @@ def fetch_chats(user_id):
return response
return None

def fetch_messages(chat_id):
client = get_supabase_client()



def fetch_messages():
pass
response = client.table('messages').select('*').eq('chat_id', chat_id).execute()
return response
3 changes: 2 additions & 1 deletion backend/chat/urls.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from django.urls import path
from .views import GetChats
from .views import GetChats, GetMessages

urlpatterns = [
path('getChats/', GetChats.as_view(), name='get-chats'),
path('getMessages/', GetMessages.as_view(), name='get-messages'),
]
32 changes: 31 additions & 1 deletion backend/chat/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,34 @@ def get(self, request):
except Exception as e:
print("Error fetching chats")
print(e)
return JsonResponse({'error': 'Failed to fetch chats'}, status=500)
return JsonResponse({'error': 'Failed to fetch chats'}, status=500)

class GetMessages(APIView):
permission_classes = [IsAuthenticated]

def get(self, request, *args, **kwargs):
user_id = request.user.username
chat_id = request.GET.get('chat_id', None)

try:
if chat_id is not None:
messages = []
response = fetch_messages(chat_id)
for message in response.data:
messages.append({
'message_id': message['message_id'],
'sent_at': message['sent_at'],
'sender_id': message['sender_id'],
'receiver_id': message['receiver_id'],
'content': message['content'],
'chat_id': message['chat_id'],
})

print(len(messages), "messages found")
return JsonResponse({'messages': messages}, safe=False)

except Exception as e:
print("Error fethcing messages")
print(e)
return JsonResponse({'error': 'Failed to fetch messages'}, status=500)

34 changes: 34 additions & 0 deletions web/src/css/Messenger.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
.chats-page h1 {
font-size: 400%;
text-align: center; /* Centers your heading */
}

.chats-box {
display: flex;
flex-direction: column; /* Stack chats vertically */
align-items: center; /* Center-align the chat containers */
justify-content: flex-start; /* Align items to the start of the flex container */
margin-top: 20px;
width: 60vw; /* Adjusted for a wider view */
max-width: 600px; /* Maintains max-width for larger screens */
margin: 20px auto; /* Centers the box with automatic horizontal margins */
padding: 20px;
background-color: #f5f5f5; /* Light grey background */
border-radius: 10px; /* Rounded corners for the box */
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* Subtle shadow for depth */
}

.chat-container { /* Updated to match JSX className */
background-color: white; /* White background for each chat */
padding: 15px;
margin-bottom: 10px; /* Space between each chat */
width: 100%; /* Ensures it fills the chats-box */
border-radius: 5px; /* Rounded corners for each chat */
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05); /* Lighter shadow for each chat */
}

.chat-container p {
margin: 5px 0; /* Standardizes margin for paragraphs within a chat */
color: #333; /* Dark grey color for text for better readability */
}

69 changes: 54 additions & 15 deletions web/src/pages/Messenger.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import React, { useState, useEffect } from 'react';
import { useAuth } from '../lib/helper/AuthContext';
import { Link } from 'react-router-dom';
import { useNavigate } from 'react-router-dom';
import '../css/Messenger.css';

function Messenger() {
const { token } = useAuth();
const navigate = useNavigate();
const [chats, setChats] = useState([]);
const [selectedChatId, setSelectedChatId] = useState(null);
const [messages, setMessages] = useState([]);


useEffect(() => {
const fetchChats = async () => {
if (!token || !token.session.access_token) {
Expand All @@ -17,35 +20,71 @@ function Messenger() {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token.session.access_token}`,
'Authorization': `Bearer ${token.session.access_token}`,
},
});
const data = await response.json();
if (data && data.chats) {
setChats(data.chats);
} else {
// Handle any errors or empty responses
console.error('Failed to fetch chats or no chats available');
}
};

fetchChats();
}, [token]);

const fetchMessages = async (chatId) => {
if (!token || !token.session.access_token) {
console.error('Token not available');
return;
}
// Assuming your server expects the chat_id as a query parameter
const response = await fetch(`/chat/getMessages/?chat_id=${chatId}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${token.session.access_token}`,
},
});
const data = await response.json();
if (data && data.messages) {
setMessages(data.messages);
} else {
console.error('Failed to fetch messages or no messages available');
}
};


const handleChatClick = (chatId) => {
setSelectedChatId(chatId);
fetchMessages(chatId);
};

return (
<div>
<h1>Chats with Mental Health Professionals</h1>
<div>
{chats.map((chat, index) => (
<div key={index} className='chat-container'>
<p>Chat with: {chat.mhp_id}</p>
<p>Chat ID: {chat.chat_id}</p>
<p>Created At: {chat.created_at}</p>
{/* You can add more details or interaction options like opening the chat */}
<div className='chats-page'>
<h1>Your Chats</h1>
<button onClick={() => navigate('/homepage')}>Back to homepage</button>
<div className='chats-container'>
<div className='chats-box'>
{chats.map((chat, index) => (
<div key={index} className='chat-container' onClick={() => handleChatClick(chat.chat_id)}>
<p>Chat with: {chat.mhp_id}</p>
<p>Chat ID: {chat.chat_id}</p>
<p>Created At: {chat.created_at}</p>
</div>
))}
</div>
{selectedChatId && (
<div className='messages-box'>
{messages.map((message, index) => (
<div key={index} className='message-container'>
<p>{message.content}</p>
</div>
))}
</div>
))}
)}
</div>
<Link to="/">Back to Homepage</Link>
</div>
);
}
Expand Down

0 comments on commit 951f1d2

Please sign in to comment.