bug fixed

This commit is contained in:
slawk0
2024-11-29 23:43:48 +01:00
parent 2322568df3
commit b024810af7
6 changed files with 101 additions and 69 deletions

View File

@@ -26,27 +26,17 @@ function ContactForm({ InitializeContact, setContactsList }: ContactFormProps) {
return prevContacts;
});
const response: AxiosResponse<{
user_id: number;
id: number;
}> = await axiosClient.post(`/api/chat/contact/${contact}`);
const response: AxiosResponse<ContactsProps> = await axiosClient.post(
`/api/chat/contact/${contact}`,
);
console.log(response.data);
const { user_id, id } = response.data;
console.log('contact post response: ', response.data);
console.log('sdfjkljklsdfjklfdjklsdfjklsdf', response.data);
InitializeContact(contact);
InitializeContact(response.data);
setContactsList((prevContacts) => {
if (!prevContacts.some((c) => c.username === contact)) {
return [
...prevContacts,
{
username: contact,
read: true,
user_id: user_id,
id: id,
},
];
return [...prevContacts, response.data];
}
return prevContacts;
});

View File

@@ -1,4 +1,4 @@
import React, { useEffect, useRef, useState } from 'react';
import React, { useEffect } from 'react';
import { getContactsList } from '../../api/contactsApi.tsx';
import { ChatMessages, ContactsProps } from '../../pages/Chat.tsx';
import { axiosClient } from '../../App.tsx';
@@ -74,10 +74,10 @@ function ContactsList({
InitializeContact(contact);
updateContactStatus(contact, true);
}}
key={contact.conversation_id}
key={contact.id || contact.group_id}
>
<span className="flex-shrink-0">
{/*user_id: {contact.user_id}, contact id: {contact.id}, username:*/}
{/*user_id: {contact.user_id}, contact id: {contact.id}, group_id: {contact.group_id} username: */}
{contact.username}
</span>

View File

@@ -15,7 +15,7 @@ type Input = {
};
type MessageFormProps = {
contactUsername: ContactsProps | null;
contactUsername: ContactsProps;
setMessages: React.Dispatch<React.SetStateAction<ChatMessages[]>>;
messages: ChatMessages[];
};
@@ -100,7 +100,7 @@ const MessageForm = ({ contactUsername, setMessages }: MessageFormProps) => {
const tempMessage: ChatMessages = {
sender: username,
message: data.message.trim(),
recipient: contactUsername,
recipient: contactUsername.username,
message_id: 0, // Set to 0 because of key={msg.message_id || msg.tempId} in messages list
pending: true,
tempId: tempId,
@@ -115,7 +115,7 @@ const MessageForm = ({ contactUsername, setMessages }: MessageFormProps) => {
'chat message',
{
message: data.message.trim(),
recipient: contactUsername,
recipient: contactUsername.username,
tempId: tempId,
attachment_url: attachmentUrl,
},

View File

@@ -41,7 +41,7 @@ function MessagesArea({
setIsLoading(true);
prevScrollHeight.current = container.scrollHeight;
setIsFetchingHistory(true);
fetchPreviousMessages(currentContact)
fetchPreviousMessages(currentContact.username)
.then(() => setIsLoading(false))
.catch(() => {
//console.error('Failed to fetch messages: ', e);
@@ -82,13 +82,14 @@ function MessagesArea({
read: false,
id: msg.message_id,
user_id: msg.sender_id,
conversation_id: msg.conversation_id,
type: 'direct',
group_id: null,
},
false,
);
console.log('changed status to false for: ', msg.sender);
}
if (msg.sender == currentContact && msg.sender !== username) {
if (msg.sender == currentContact?.username && msg.sender !== username) {
messageHandler(msg);
}
});

View File

@@ -26,8 +26,8 @@ export type ContactsProps = {
username: string;
user_id: number;
id: number;
conversation_id: number;
type: 'direct' | 'group';
group_id: number | null;
};
function Chat() {
@@ -180,7 +180,7 @@ function Chat() {
/>
</div>
<div className="flex-shrink-0 mb-2 mt-0">
{currentContact && currentContact.username.length >= 4 ? (
{currentContact && currentContact.username?.length >= 4 ? (
<MessageForm
contactUsername={currentContact}
setMessages={setMessages}

View File

@@ -158,16 +158,21 @@ async function insertMessage(
content,
attachmentUrl,
) {
console.log(
`senderUsername: ${senderUsername}, receiverUsername: ${receiverUsername}, content: ${content}, attachmentUrl: ${attachmentUrl} `,
);
const query = `
WITH sender AS (
SELECT user_id
FROM Accounts
WHERE username = $1
LIMIT 1
),
recipient AS (
SELECT user_id
FROM Accounts
WHERE username = $2
LIMIT 1
),
conversation AS (
SELECT conversation_id
@@ -453,51 +458,88 @@ async function changePassword(username, newPasswordHash) {
}
async function insertContact(userUsername, receiverUsername, read) {
// Step 1: Get user IDs for the sender and receiver
const senderUserId = await getUserId(userUsername);
const receiverUserId = await getUserId(receiverUsername);
if (!senderUserId || !receiverUserId) {
console.error("One or both users do not exist.");
return null;
}
// Step 2: Check if a conversation already exists between the two users
let conversationId = await getConversationId(userUsername, receiverUsername);
// Step 3: If no conversation exists, create a new one
if (!conversationId) {
const query = `
const query = `
WITH sender AS (
SELECT user_id
FROM Accounts
WHERE username = $1
LIMIT 1
),
receiver AS (
SELECT user_id
FROM Accounts
WHERE username = $2
LIMIT 1
),
existing_conversation AS (
SELECT conversation_id
FROM Conversations
WHERE conversation_type = 'direct'
AND EXISTS (
SELECT 1
FROM Memberships
WHERE conversation_id = Conversations.conversation_id
AND user_id = (SELECT user_id FROM sender)
)
AND EXISTS (
SELECT 1
FROM Memberships
WHERE conversation_id = Conversations.conversation_id
AND user_id = (SELECT user_id FROM receiver)
)
LIMIT 1
),
new_conversation AS (
INSERT INTO Conversations (conversation_type)
VALUES ('direct')
RETURNING conversation_id;
`;
try {
const result = await client.query(query);
conversationId = result.rows[0].conversation_id;
// Add both users to the new conversation
await addMemberToGroup(conversationId, senderUserId);
await addMemberToGroup(conversationId, receiverUserId);
} catch (e) {
console.error("Failed to create conversation ", e);
return null;
}
}
// Step 4: Insert the contact
const insertContactQuery = `
INSERT INTO Contacts (user_id, contact_user_id, read, last_active)
VALUES ($1, $2, $3, CURRENT_TIMESTAMP)
ON CONFLICT DO NOTHING
RETURNING contact_id AS id, contact_user_id AS user_id;
SELECT 'direct'
WHERE NOT EXISTS (SELECT 1 FROM existing_conversation)
RETURNING conversation_id
),
final_conversation AS (
SELECT conversation_id FROM existing_conversation
UNION ALL
SELECT conversation_id FROM new_conversation
),
insert_memberships AS (
INSERT INTO Memberships (conversation_id, user_id)
SELECT conversation_id, user_id
FROM final_conversation, sender
WHERE NOT EXISTS (
SELECT 1
FROM Memberships
WHERE conversation_id = final_conversation.conversation_id
AND user_id = sender.user_id
)
UNION ALL
SELECT conversation_id, user_id
FROM final_conversation, receiver
WHERE NOT EXISTS (
SELECT 1
FROM Memberships
WHERE conversation_id = final_conversation.conversation_id
AND user_id = receiver.user_id
)
),
insert_contact AS (
INSERT INTO Contacts (user_id, contact_user_id, read, last_active)
SELECT (SELECT user_id FROM sender), (SELECT user_id FROM receiver), $3, CURRENT_TIMESTAMP
ON CONFLICT DO NOTHING
RETURNING contact_id AS id, contact_user_id AS user_id, last_active
)
SELECT
ic.id,
ic.user_id,
a.username AS username,
ic.last_active,
'direct' AS type
FROM insert_contact ic
JOIN Accounts a ON a.user_id = ic.user_id;
`;
try {
const result = await client.query(insertContactQuery, [
senderUserId,
receiverUserId,
const result = await client.query(query, [
userUsername,
receiverUsername,
read,
]);
if (result.rows.length > 0) {
@@ -510,7 +552,6 @@ async function insertContact(userUsername, receiverUsername, read) {
}
}
// Helper function to get conversation ID between two users
async function getConversationId(senderUsername, receiverUsername) {
const query = `
SELECT conversation_id FROM Conversations