adding member to group is working

This commit is contained in:
slawk0
2024-11-30 12:07:57 +01:00
parent b024810af7
commit a805cf3e1a
6 changed files with 84 additions and 23 deletions

View File

@@ -2,12 +2,18 @@ import LoadingWheel from './LoadingWheel.tsx';
import { useRef, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { axiosClient } from '../../App.tsx';
import { ContactsProps } from '../../pages/Chat.tsx';
type Inputs = {
username: string;
user_id: number;
};
function AddGroupMember() {
interface AddGroupMemberProps {
contact?: ContactsProps;
}
function AddGroupMember({ contact }: AddGroupMemberProps) {
const [isLoading, setIsLoading] = useState<boolean>(false);
const modalRef = useRef<HTMLDialogElement | null>(null);
@@ -20,13 +26,14 @@ function AddGroupMember() {
const onSubmit: SubmitHandler<Inputs> = async (data) => {
try {
setIsLoading(true);
const response = await axiosClient.post(`/api/chat/groups/add/`, data);
const response = await axiosClient.post(`/api/chat/groups/add/`, {
group_id: contact?.group_id,
username: data.username,
});
console.log(response.data);
if (response.data.ok) {
setIsLoading(false);
if (modalRef.current) {
modalRef.current.close();
}
setIsLoading(false);
if (modalRef.current) {
modalRef.current.close();
}
} catch (e) {
console.error('Failed to create group: ', e);
@@ -41,13 +48,13 @@ function AddGroupMember() {
className="m-2 border p-1 rounded-md"
onClick={() =>
(
document.getElementById('my_modal_1') as HTMLDialogElement
document.getElementById('addMemberModal') as HTMLDialogElement
).showModal()
}
>
Add member
</button>
<dialog id="my_modal_1" className="modal" ref={modalRef}>
<dialog id="addMemberModal" className="modal" ref={modalRef}>
<div className="modal-box bg-gray-800 text-center relative p-1">
<div className="absolute right-2 top-2">
<form method="dialog">

View File

@@ -4,15 +4,15 @@ import AddGroupMember from './AddGroupMember.tsx';
import { ContactsProps } from '../../pages/Chat.tsx';
type ContactProfileProps = {
username: ContactsProps | null;
contact: ContactsProps | null;
};
function ContactProfile({ username }: ContactProfileProps) {
function ContactProfile({ contact }: ContactProfileProps) {
return (
<div className="flex items-center">
<div className="flex items-center p-2">
<img className="w-4 mr-2 invert" src={profile} alt="profile img" />
<p>{username ? username.username : null}</p>
<p>{contact ? contact.username : null}</p>
</div>
<div className="flex-grow"></div>
@@ -20,7 +20,9 @@ function ContactProfile({ username }: ContactProfileProps) {
<CreateGroupButton />
</div>
<div>
<AddGroupMember />
{contact?.type === 'group' ? (
<AddGroupMember contact={contact} />
) : null}
</div>
</div>
);

View File

@@ -2,6 +2,7 @@ import LoadingWheel from './LoadingWheel.tsx';
import { useRef, useState } from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { axiosClient } from '../../App.tsx';
import { ContactsProps } from '../../pages/Chat.tsx';
type Inputs = {
groupName: string;
@@ -20,9 +21,7 @@ function createGroupButton() {
const onSubmit: SubmitHandler<Inputs> = async (data) => {
try {
setIsLoading(true);
const response = await axiosClient.post(
`/api/chat/creategroup/${data.groupName}`,
);
const response = await axiosClient.post(`/api/chat/groups/create`, data);
console.log(response.data);
if (response.data.group_id) {
setIsLoading(false);
@@ -43,13 +42,13 @@ function createGroupButton() {
className="m-2 border p-1 rounded-md"
onClick={() =>
(
document.getElementById('my_modal_1') as HTMLDialogElement
document.getElementById('createGroupModal') as HTMLDialogElement
).showModal()
}
>
Create group
</button>
<dialog id="my_modal_1" className="modal" ref={modalRef}>
<dialog id="createGroupModal" className="modal" ref={modalRef}>
<div className="modal-box bg-gray-800 text-center relative p-1">
<div className="absolute right-2 top-2">
<form method="dialog">

View File

@@ -163,7 +163,7 @@ function Chat() {
{/*Chat area */}
<div className="text-white bg-[#121212] flex flex-col h-screen w-full">
<div className="flex-shrink-0">
<ContactProfile username={currentContact} />
<ContactProfile contact={currentContact} />
</div>
<hr className="flex-shrink-0" />
<div className="flex-grow overflow-x-hidden overflow-y-auto m-2">

View File

@@ -105,7 +105,7 @@ async function createTables() {
CREATE TABLE IF NOT EXISTS Contacts (
contact_id SERIAL PRIMARY KEY,
user_id INT REFERENCES Accounts(user_id) ON DELETE CASCADE,
contact_user_id INT REFERENCES Accounts(user_id) ON DELETE CASCADE,
contact_user_id INT NOT NULL REFERENCES Accounts(user_id) ON DELETE CASCADE,
read BOOLEAN NOT NULL DEFAULT FALSE,
last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT unique_contact UNIQUE (user_id, contact_user_id)
@@ -275,6 +275,45 @@ async function addMemberToGroup(conversation_id, user_id) {
}
}
async function addMemberToGroupByUsername(conversation_id, username) {
const query = `
WITH user_id_query AS (
SELECT user_id
FROM Accounts
WHERE username = $1
LIMIT 1
),
insert_membership AS (
INSERT INTO Memberships (conversation_id, user_id)
SELECT $2, user_id
FROM user_id_query
WHERE NOT EXISTS (
SELECT 1
FROM Memberships
WHERE conversation_id = $2 AND user_id = (SELECT user_id FROM user_id_query)
)
)
SELECT (SELECT user_id FROM user_id_query) AS added_user_id;
`;
try {
const result = await client.query(query, [username, conversation_id]);
if (result.rows.length > 0) {
console.log(
`Added user with username ${username} to conversation_id ${conversation_id}`,
);
return result.rows[0].added_user_id;
} else {
console.log(
`User with username ${username} not found or already in group.`,
);
return null;
}
} catch (e) {
console.error("Failed to add member to group by username", e);
}
}
async function getMessages(user_id, receiverUsername, limit = 50, cursor = 0) {
let query = `
WITH recipient AS (
@@ -706,4 +745,6 @@ module.exports = {
updateContactStatus,
updateContactLastActive,
createGroup,
addMemberToGroup,
addMemberToGroupByUsername,
};

View File

@@ -36,7 +36,13 @@ const {
} = require("./utils/filter");
const { generateJwtToken, verifyJwtToken } = require("./auth/jwt");
const { initializeSocket } = require("./socket/socket");
const { getContacts, insertContact, createGroup } = require("./db/db");
const {
getContacts,
insertContact,
createGroup,
addMemberToGroup,
addMemberToGroupByUsername,
} = require("./db/db");
const { extname } = require("node:path");
const corsOptions = {
@@ -305,9 +311,9 @@ app.post(
app.post("/api/chat/groups/create", authorizeUser, async (req, res) => {
const user_id = req.user.user_id;
const groupname = req.body.groupname;
const groupname = req.body.groupName;
if (!groupname) {
res.status(400).json({ message: "Groupname not provided" });
return res.status(400).json({ message: "Groupname not provided" });
}
const group_id = await createGroup(user_id, groupname);
if (!group_id) {
@@ -321,9 +327,15 @@ app.post("/api/chat/groups/create", authorizeUser, async (req, res) => {
app.post("/api/chat/groups/add", async (req, res) => {
const username = req.body.username;
const group_id = req.body.group_id;
if (!username) {
return res.status(400).json({ message: "Username not provided" });
}
const result = await addMemberToGroupByUsername(group_id, username);
if (result !== null) {
return res.status(200).json({ message: "Successfully added member" });
}
res.status(500).json({ message: "Failed to add member" });
});
initializeSocket(io);