Skip to content

Commit

Permalink
notifications events invitation + clearAll
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperMitic committed Oct 28, 2024
1 parent 76cc159 commit 7726782
Show file tree
Hide file tree
Showing 5 changed files with 106 additions and 109 deletions.
69 changes: 49 additions & 20 deletions client/components/navbar/notifications-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,29 +21,48 @@ export const NotificationsDropdown = () => {
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);

useEffect(() => {
const fetchNotifications = async () => {
try {
const response = await fetch("/api/users/inbox", {
method: "GET",
credentials: "include",
});
const fetchNotifications = async () => {
try {
const response = await fetch("/api/users/inbox", {
method: "GET",
credentials: "include",
});

if (!response.ok) {
throw new Error("Failed to fetch notifications");
}

if (!response.ok) {
throw new Error("Failed to fetch notifications");
}
const data = await response.json();
setNotifications(data);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error fetching notifications",
);
} finally {
setIsLoading(false);
}
};

const data = await response.json();
setNotifications(data);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error fetching notifications",
);
} finally {
setIsLoading(false);
const handleClearAll = async () => {
try {
const response = await fetch("/api/users/inbox", {
method: "DELETE",
credentials: "include",
});

if (!response.ok) {
throw new Error("Failed to clear notifications");
}
};

setNotifications([]); // Aggiorna lo stato locale dopo la cancellazione
} catch (err) {
setError(
err instanceof Error ? err.message : "Error clearing notifications",
);
}
};

useEffect(() => {
fetchNotifications();
}, []);

Expand All @@ -69,7 +88,17 @@ export const NotificationsDropdown = () => {
variant="flat"
color="success"
>
<DropdownSection title="Notifiche">
<DropdownSection title="Notifiche" showDivider>
<DropdownItem
className="text-danger"
color="danger"
onClick={handleClearAll}
>
Clear All
</DropdownItem>
</DropdownSection>

<DropdownSection>
{isLoading ? (
<DropdownItem>Loading...</DropdownItem>
) : error ? (
Expand Down
6 changes: 3 additions & 3 deletions server/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import path from "path";
import { fileURLToPath } from "url";
import { createDataBase } from "./src/database.js";
import { Server } from "socket.io";
import { createServer } from 'http';
import { createWebSocket } from './src/socket.js';
import { createServer } from "http";
import { createWebSocket } from "./src/socket.js";

config();

Expand Down Expand Up @@ -34,7 +34,7 @@ async function startServer() {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
credentials: true
credentials: true,
},
});

Expand Down
129 changes: 44 additions & 85 deletions server/src/database.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ import { messageSchema } from "./models/chat-model.js";

// services import
import createProjectService from "./services/projects.mjs";
import { sendEmailNotification, sendNotification } from "./pushNotificationWorker.js";
import {
sendEmailNotification,
sendNotification,
} from "./pushNotificationWorker.js";

export async function createDataBase() {
const uri =
Expand Down Expand Up @@ -410,72 +413,6 @@ export async function createDataBase() {
}
};

const getEvents = async (uid) => {
const user = await userModel.findById(uid);
if (!user) throw new Error("User not found");

// Combina gli ID degli eventi creati e quelli a cui l'utente partecipa
const allEventIds = [
...new Set([...user.events, ...user.participatingEvents]),
];

// Recupera tutti gli eventi in una sola query
const events = await eventModel.find({ _id: { $in: allEventIds } });

return events;
};

const getEvent = async (uid, eventid) => {
const user = await userModel.findById(uid);
if (!user) throw new Error("User not found");

const event = await eventModel.findById(eventid);
if (!event) throw new Error("Event not found");

return event;
};

const createEvent = async (uid, event) => {
const user = await userModel.findById(uid);
if (!user) throw new Error("User not foun");

// Validate event object
if (!event.title) {
throw new Error("Event must have a title");
}

if (!event.dtstart || !event.dtend) {
throw new Error("Event must have a date");
}
// add event to the user's events
var addedEvent = await eventModel.create({ ...event, uid: uid });
user.events.push(addedEvent._id);
await user.save();

// invite all users in the event
/*
var err = "Invited users not found: ";
if (event.invitedUsers) {
event.invitedUsers.forEach(async (invitedUser) => {
const invitedUserDoc = await userModel.findOne({
username: invitedUser,
});
if (!invitedUserDoc) err += invitedUser + ", ";
else {
invitedUserDoc.invitedEvents.push(addedEvent._id);
await invitedUserDoc.save();
}
});
}
if (err !== "Invited users not found: ") throw new Error(err);
*/

// generate notifications for all the invited users
//await generateNotificationsForEvent(addedEvent, [user]);

return addedEvent;
};

const addNotification = async (user, notification) => {
if (!user.inobxNotifications) user.inboxNotifications = [];
user.inboxNotifications.push(notification);
Expand Down Expand Up @@ -620,7 +557,6 @@ export async function createDataBase() {
return events;
};


const getEvent = async (uid, eventid) => {
const user = await userModel.findById(uid);
if (!user) throw new Error("User not found");
Expand All @@ -638,7 +574,8 @@ export async function createDataBase() {

// Validazione evento
if (!event.title) throw new Error("Event must have a title");
if (!event.dtstart || !event.dtend) throw new Error("Event must have a date");
if (!event.dtstart || !event.dtend)
throw new Error("Event must have a date");

try {
// Creazione evento
Expand All @@ -649,7 +586,7 @@ export async function createDataBase() {
await userModel.findByIdAndUpdate(
uid,
{ $push: { events: addedEvent._id } },
{ new: true }
{ new: true },
);

// Gestione partecipanti
Expand All @@ -660,25 +597,32 @@ export async function createDataBase() {
const updated = await userModel.findByIdAndUpdate(
participant,
{ $push: { invitedEvents: addedEvent._id } },
{ new: true }
{ new: true },
);

//costruzione della notifica per i partecipanti
/*

var payload = {
title: "Notifica da Selfie",
body: user.username + " ti ha invitato all'evento " + addedEvent.title + "\nClicca il link per accettare l'invito.",
URL: `localhost:3000/calendar/partecipat/${addedEvent._id}`,
title: "📆 Sei stato invitato a un evento di gruppo",
body:
"L'utente " +
user.username +
" ti ha invitato all'evento " +
addedEvent.title +
"\nClicca qui per accettare l'invito.",
link: `/calendar/${addedEvent._id}/${participant}`,
};
const result = sendNotification(participant, payload);
const result = sendNotification(updated, payload);
console.log(result.statusCode);
*/

if (!updated) {
console.log(`User not found: ${participant}`);
} else {
console.log(`Event added to user: ${participant}`);
console.log('Updated participating events:', updated.participatingEvents);
console.log(
"Updated participating events:",
updated.participatingEvents,
);
}
} catch (err) {
console.error(`Error updating participant ${participant}:`, err);
Expand Down Expand Up @@ -758,10 +702,12 @@ export async function createDataBase() {
if (!event) throw new Error("Event not found");

// togliere l'evento dalla lista degli eventi dello user
const res = await userModel.findByIdAndUpdate(uid, { $pull: { participatingEvents: eventId } });
const res = await userModel.findByIdAndUpdate(uid, {
$pull: { participatingEvents: eventId },
});

return res;
}
};

// accetto la proposta dell'evento [componente participateevent]
const participateEvent = async (uid, eventId) => {
Expand All @@ -781,7 +727,7 @@ export async function createDataBase() {
);
await user.save();

//devo fare altro per mandare le notifiche dell'evento?
//devo fare altro per mandare le notifiche dell'evento?
//non credo tanto l'evento c'è già nello user

return user.invitedEvents;
Expand Down Expand Up @@ -1215,6 +1161,18 @@ export async function createDataBase() {
}
};

const deleteInbox = async (uid) => {
try {
const user = await userModel.findById(uid);
if (!user) throw new Error("User not found");

user.inbox = [];
await user.save();
} catch (error) {
console.error("Error deleting inbox:", error);
}
};

const getNextNotifications = async () => {
const users = await userModel.find({});
let notifications = { email: [], pushNotification: [] };
Expand Down Expand Up @@ -1746,10 +1704,10 @@ export async function createDataBase() {
const sender = msg.sender.toString() === uid ? user : otherUser;
return otherUser
? {
uid: otherUser._id,
username: otherUser.username,
lastMessage: { ...msg, sender: sender.username },
}
uid: otherUser._id,
username: otherUser.username,
lastMessage: { ...msg, sender: sender.username },
}
: null;
})
.filter((chat) => chat !== null);
Expand Down Expand Up @@ -1891,6 +1849,7 @@ export async function createDataBase() {
addSong,
addNotificationToInbox,
getInbox,
deleteInbox,
getNextNotifications,
getDateTime,
verifyEmail,
Expand Down
1 change: 1 addition & 0 deletions server/src/pushNotificationWorker.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,7 @@ export async function sendEmailNotification(payload) {

export async function sendNotification(user, payload) {
try {
console.log(`Sending notification to ${user}`);
if (!payload.title || !payload.body) {
throw new Error("Title and body are required in the payload");
}
Expand Down
10 changes: 9 additions & 1 deletion server/src/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,21 @@ export default function createUserRouter(db) {

router.get("/inbox", cookieJwtAuth, async (req, res) => {
try {
console.log("req.user._id", req.user._id);
const notifications = await db.getInbox(req.user._id);
return res.status(200).json(notifications);
} catch (error) {
return res.status(404).json({ message: error.message });
}
});

router.delete("/inbox", cookieJwtAuth, async (req, res) => {
try {
const response = await db.deleteInbox(req.user._id);
return res.status(200).json(response);
} catch (error) {
return res.status(404).json({ message: error.message });
}
});

return router;
}

0 comments on commit 7726782

Please sign in to comment.