Skip to content

Commit

Permalink
Attendance count added to session model and implemented in session co…
Browse files Browse the repository at this point in the history
…ntroller/UpcomingEvents. Now displays in Members Attending.
  • Loading branch information
cloud-spotter committed Oct 25, 2023
1 parent bf9da6d commit 8f06b48
Show file tree
Hide file tree
Showing 4 changed files with 64 additions and 90 deletions.
68 changes: 23 additions & 45 deletions api/controllers/sessions.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,58 +25,36 @@ const SessionsController = {
res.status(201).json({ message: 'OK', token: token});
});
},
// Add attendence


// AddAttending: (req, res) => {
// Session.findOne({ _id: req.params.session_id })
// .populate("users_attending")
// // Check what populate is doing
// .exec((err, session) => {
// if (err) {
// throw err;
// }
// const user = req.user_id;
// const isSessionLikedByUser = session.likes.includes(user);
// if (isSessionLikedByUser) {
// session.likes.pop(user);
// } else {
// session.likes.push(user);
// }
// session.save((err) => {
// if (err) {
// throw err;
// }
// res.status(201).json({ session: session });
// });
// });
// },

AddAttending: (req, res) => {
/**
* Handles user attendance for a session.
* Increments the attendance count for the specified session and updates the database.
*
* @param {Object} req - The HTTP request object
* @param {Object} res - The HTTP response object
*/
AddAttending: async (req, res) => {
const sessionId = req.params.session_id;
const userId = req.user_id;

Session.findOne({ _id: sessionId }, (err, session) => {
if (err) {
return res.status(500).json({ error: "Internal Server Error" });
const userId = req.body.user_id;

try {
const session = await Session.findOne({ _id: sessionId });
if (!session) {
console.log("Session not found:", sessionId);
return res.status(404).json({ error: "Session not found" });
}

// Check if the user is already attending the session
const isUserAttending = session.users_attending.includes(userId);
session.attending += 1;

if (!isUserAttending) {
// If the user is not already attending, add them to the list of attendees
session.users_attending.push(userId);
}
console.log("Updated attending count:", session.attending);

session.save((err) => {
if (err) {
return res.status(500).json({ error: "Internal Server Error" });
}
await session.save();

res.status(200).json({ session: session });
});
});
res.status(200).json({ success: true, attending: session.attending }); // Include attending count in the response
} catch (err) {
console.error("Error:", err);
return res.status(500).json({ error: "Internal Server Error" });
}
},
};

Expand Down
2 changes: 1 addition & 1 deletion api/models/book.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const BookSchema = new mongoose.Schema({
authors: { type: Array, required: true },
title: { type: String, required: true },
year_published: { type: String, required: true },
// TODO: check type for year_published and session_id
// TODO: session_id may be unnecessary. Remove?
session: [
{
type: mongoose.Schema.Types.ObjectId,
Expand Down
5 changes: 1 addition & 4 deletions api/models/session.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,8 @@ const SessionSchema = new mongoose.Schema({
required: false
},
],
attending: { type: Number, default: 0 }, // Added to implement attendance count on 'Attend' button click
});
/* For the chosen_book, there's no need for an array as we only need one book.
So we can have just an ObjectId that references the Book model.
For suggested_books, we can represent it as an array of subdocuments, where each subdocument has a user_id
(reference to User) and a book_id (reference to Book).*/

const Session = mongoose.model("Session", SessionSchema);

Expand Down
79 changes: 39 additions & 40 deletions frontend/src/components/upcomingevents/UpcomingEvents.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import CoverLabel from "./CoverLabel";
import "../session/SessionForm";
import sortBy from "lodash/sortBy";

// TODO update other files (e.g. box.js/bookLabel.js/SessionLabel.js) - call hooks

const UpcomingEvents = () => {
const [user, setUser] = useState("");
const [upcomingSessions, setUpcomingSessions] = useState([]);
Expand Down Expand Up @@ -55,16 +53,16 @@ const UpcomingEvents = () => {
const handleAttendSession = (session) => {
// Check if the user is already attending the session
const isAttending = isUserAttending(session);

// Prepare the data to send to the server
// Prepare data to send to server
const data = {
session_id: session._id, // Replace with the actual ID field in your session object
user_id: user._id, // Replace with the actual ID field in your user object
action: isAttending ? "Unattend" : "attend",
session_id: session._id,
user_id: user._id,
action: isAttending ? "Unattend" : "Attend",
};

// Send a request to your server to handle session attendance
fetch("/api/session/attend", {
// Send request to server to handle session attendance
fetch(`/sessions/${session._id}/attend`, { // Update the endpoint
method: "POST",
headers: {
"Content-Type": "application/json",
Expand All @@ -79,19 +77,21 @@ const UpcomingEvents = () => {
const updatedSessions = upcomingSessions.map((s) => {
if (s._id === session._id) {
if (isAttending) {
// Remove user from users_attending
s.users_attending = s.users_attending.filter(
(userId) => userId !== user._id
);
setMembersAttending(membersAttending - 1); // Decrement
} else {
// Add user to users_attending
s.users_attending.push(user._id);
setMembersAttending(membersAttending + 1); // Increment
}
}
return s;
});

setUpcomingSessions(updatedSessions);
setMembersAttending(response.attending); // Update members attending count
console.log("membersAttending:", membersAttending);
} else {
// Handle errors if necessary
console.error("Failed to update attendance status");
Expand All @@ -100,36 +100,35 @@ const UpcomingEvents = () => {
};

return (
<div className="upcoming-events">
<div className="section-title">
<div className="content">
<div className="text-wrapper">Upcoming Events</div>
</div>
</div>
{upcomingSessions ? (
<div id="scrollable">
{upcomingSessions.map((session) => (
<div className="upcoming-event-block">
<div className="book-wrapper">
<CoverLabel session={session}></CoverLabel>
<div className="box">
<BookLabel session={session}></BookLabel>
</div>
<div className="box">
<SessionLabel session={session} membersAttending={membersAttending} />
</div>
<button onClick={() => handleAttendSession(session)}>
{isUserAttending(session) ? "Unattend" : "Attend"}
</button>
<div className="upcoming-events">
<div className="section-title">
<div className="content">
<div className="text-wrapper">Upcoming Events</div>
</div>
</div>
{upcomingSessions ? (
<div id="scrollable">
{upcomingSessions.map((session) => (
<div className="upcoming-event-block">
<div className="book-wrapper">
<CoverLabel session={session}></CoverLabel>
<div className="box">
<BookLabel session={session}></BookLabel>
</div>
<div className="box">
<SessionLabel session={session} membersAttending={membersAttending} />
</div>
<button onClick={() => handleAttendSession(session)}>
{isUserAttending(session) ? "Unattend" : "Attend"}
</button>
</div>
</div>
))}
</div>
))}
) : (
<div className="upcoming-event-block"></div>
)}
</div>
) : (
<div className="upcoming-event-block"></div>
)}
</div>

);
};

Expand Down

0 comments on commit 8f06b48

Please sign in to comment.