Skip to content

Commit

Permalink
merge develop into main
Browse files Browse the repository at this point in the history
  • Loading branch information
gerbie-goober committed Aug 5, 2024
2 parents aabba1f + 2ac64d7 commit 2b414db
Show file tree
Hide file tree
Showing 12 changed files with 757 additions and 141 deletions.
45 changes: 45 additions & 0 deletions backend/API/getReplies.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const mongoose = require("mongoose");
const TrendingComment = require('../schema/trendingComment');
const Vote = require('../schema/votes');

const getRepliesForComment = async (req, res) => {
const commentId = req.params.commentId; // This is the ID of the parent comment
const userId = req.params.userId; // Assuming you are using some form of user auth to get user info

try {
const replies = await TrendingComment.find({ parentId: commentId })
.lean()
.sort({ createdAt: -1 });

// Aggregate votes for replies similarly as you did for comments
const replyIds = replies.map(reply => reply._id);
const votes = await Vote.aggregate([
{ $match: { commentId: { $in: replyIds } } },
{ $group: { _id: "$commentId", totalVotes: { $sum: "$voteType" },
userVote: {
$max: {
$cond: { if: { $eq: ["$userId", userId] }, then: "$voteType", else: 0 }
}
}}}
]);

const votesMap = votes.reduce((acc, vote) => {
acc[vote._id.toString()] = { totalVotes: vote.totalVotes, userVote: vote.userVote };
return acc;
}, {});

// Attach vote data to replies
const repliesWithVotes = replies.map(reply => ({
...reply,
votes: votesMap[reply._id.toString()] ? votesMap[reply._id.toString()].totalVotes : 0,
userVote: votesMap[reply._id.toString()] ? votesMap[reply._id.toString()].userVote : 0,
}));

res.json(repliesWithVotes);
} catch (error) {
console.error('Error fetching replies:', error);
res.status(500).json({ message: error.message });
}
};

module.exports = getRepliesForComment;
58 changes: 51 additions & 7 deletions backend/API/getTrendingComments.js
Original file line number Diff line number Diff line change
@@ -1,18 +1,62 @@
const mongoose = require("mongoose");
const TrendingComment = require('../schema/trendingComment');
const Vote = require('../schema/votes');

const getTrendingComments = async (req, res) => {
const userId = req.params.userId; // Assuming you have user information from session or token
const resumeId = req.params.resumeId;

try {
let comments = await TrendingComment.find({ resumeId: req.params.resumeId, parentId: null })
.sort({ createdAt: -1 });
comments = await Promise.all(comments.map(async (comment) => {
const replies = await TrendingComment.find({ parentId: comment._id }).sort({ createdAt: 1 });
return { ...comment.toObject(), replies };
// const comments = await TrendingComment.find({ resumeId, parentId: null})
// .lean()
// .sort({ createdAt: -1 });

const comments = await TrendingComment.aggregate([
// Match top-level comments
{ $match: { resumeId: mongoose.Types.ObjectId(resumeId), parentId: null } },
// Lookup to find replies and count them
{ $lookup: {
from: "trendingcomments", // assuming collection name is trendingcomments
localField: "_id",
foreignField: "parentId",
as: "replies"
}},
{ $addFields: {
repliesCount: { $size: "$replies" }
}},
{ $project: { replies: 0 } }, // Exclude the replies field from output
// Sort comments by creation date
{ $sort: { createdAt: -1 } }
]);
// Get vote counts and user-specific votes in one go, if possible
const commentIds = comments.map(comment => comment._id);
const votes = await Vote.aggregate([
{ $match: { commentId: { $in: commentIds } } },
{ $group: { _id: "$commentId", totalVotes: { $sum: "$voteType" },
userVote: {
$max: {
$cond: { if: { $eq: ["$userId", userId] }, then: "$voteType", else: 0 }
}
}}}
]);

const votesMap = votes.reduce((acc, vote) => {
acc[vote._id.toString()] = { totalVotes: vote.totalVotes, userVote: vote.userVote };
return acc;
}, {});

// Attach vote data to comments
const commentsWithVotes = comments.map(comment => ({
...comment,
votes: votesMap[comment._id.toString()] ? votesMap[comment._id.toString()].totalVotes : 0,
userVote: votesMap[comment._id.toString()] ? votesMap[comment._id.toString()].userVote : 0,
}));
res.json(comments);

res.json(commentsWithVotes);
} catch (error) {
console.error('Error fetching trending comments:', error);
res.status(500).json({ message: error.message });
}
};

module.exports = getTrendingComments;
module.exports = getTrendingComments;
64 changes: 51 additions & 13 deletions backend/API/votes.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,61 @@
const mongoose = require("mongoose");
const Vote = require('../schema/votes');
const TrendingComment = require('../schema/trendingComment');

const voteOnComment = async (req, res) => {
const { commentId, delta } = req.body;
const { userId, commentId, voteType } = req.body;

try {
const comment = await TrendingComment.findByIdAndUpdate(
commentId,
{ $inc: { votes: delta } }, // Increment or decrement the votes field
{ new: true } // Return the updated document
);

if (!comment) {
return res.status(404).send({ message: "Comment not found" });
const existingVote = await Vote.findOne({ commentId, userId });

if (existingVote) {
if (voteType === 0) {
await existingVote.remove();
} else if (existingVote.voteType !== voteType) {
existingVote.voteType = voteType;
await existingVote.save();
}
} else {
if (voteType !== 0) { // Only save if voteType is not 0
const newVote = new Vote({ commentId, userId, voteType });
await newVote.save();
}
}

res.json(comment);
await updateCommentVotes(commentId);
res.status(200).json({ message: 'Vote registered successfully.' });
} catch (error) {
res.status(500).json({ message: 'Error processing vote', error: error.message });
}
};

// Helper function to update the vote count on a comment
async function updateCommentVotes(commentId) {
const votes = await Vote.aggregate([
{ $match: { commentId: mongoose.Types.ObjectId(commentId) } },
{ $group: { _id: null, totalVotes: { $sum: '$voteType' } } }
]);

const totalVotes = votes.length > 0 ? votes[0].totalVotes : 0;
await TrendingComment.findByIdAndUpdate(commentId, { votes: totalVotes });
}


const getVoteStatus = async (req, res) => {
const { userId, commentId } = req.query; // Assuming userId and commentId are passed as query parameters

try {
const existingVote = await Vote.findOne({ commentId, userId });

if (existingVote) {
res.status(200).json({ voteType: existingVote.voteType });
} else {
res.status(200).json({ voteType: 0 }); // No vote
}
} catch (error) {
console.error('Failed to update comment votes:', error);
res.status(500).send({ message: "Failed to update comment votes due to an internal error." });
res.status(500).json({ message: 'Error fetching vote status', error: error.message });
}
};

module.exports = voteOnComment;
module.exports = { voteOnComment, getVoteStatus };
// module.exports = voteOnComment;
2 changes: 1 addition & 1 deletion backend/Utils/CommentFilter.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const Filter = require('bad-words');
const filter = new Filter();
const customWords = ['stupid', 'idiot', 'dumb', 'crazy','hate','bad','horrible','terrible']; // Add more as needed
const customWords = ['stupid', 'idiot', 'dumb', 'crazy','hate','bad','horrible','terrible', 'awful', 'disgusting']; // Add more as needed
filter.addWords(...customWords)
const isBad = (text) => filter.isProfane(text);

Expand Down
15 changes: 15 additions & 0 deletions backend/schema/votes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const voteSchema = new Schema({
commentId: { type: Schema.Types.ObjectId, ref: 'TrendingComment', required: true },
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
voteType: { type: Number, required: true, validate: {
validator: function(v) {
return v === 1 || v === -1 || v === 0; // Ensures vote is either an upvote (+1) or a downvote (-1)
},
message: props => `${props.value} is not a valid vote type!`
}}
});

module.exports = mongoose.model('Vote', voteSchema);
5 changes: 4 additions & 1 deletion backend/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,10 @@ const getResumebyId = require('./API/getResumebyId');
const getUserbyId = require('./API/getUserbyId');
const getTrendingComments = require('./API/getTrendingComments');
const postTrendingComment = require('./API/postTrendingComment');
const voteOnComment = require('./API/votes');
const { voteOnComment, getVoteStatus } = require('./API/votes');
const { blockUser, checkIfBlocked, getBlockedUsers } = require('./API/BlockingUser');
const BlockedUser = require('./schema/blockedUsers');
const getRepliesForComment = require('./API/getReplies');

// Direct messaging API's
const sendMessage = require('./API/sendMessage');
Expand Down Expand Up @@ -184,6 +185,8 @@ app.post('/block-user', blockUser);
app.get('/api/trending/get-comments/:resumeId', getTrendingComments);
app.post('/trending/post-comments', postTrendingComment);
app.post('/api/comments/vote', voteOnComment);
app.get('/comments/vote-status', getVoteStatus);
app.get('/api/comments/replies/:commentId', getRepliesForComment);
//app.post('/get-number-of-unread-dms', getNumberOfUnreadDms);
app.post('/api/dm-status/update', updateDmStatus);
app.get('/api/dm-status', getDmStatus);
Expand Down
Binary file added frontend/dump.rdb
Binary file not shown.
8 changes: 4 additions & 4 deletions frontend/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions frontend/src/pages/ProfilePage.css
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
align-items: center;
width: 125px;
position: absolute;
left: 90px;
left: 65px;
top: 50px;
}

Expand Down Expand Up @@ -139,7 +139,7 @@
background-color: #26ACD6;
position: relative;
margin-right: 10px;
top: 60px;
top: 70px;
}

/* Container for field labels and values */
Expand All @@ -149,6 +149,7 @@
flex-direction: column;
align-items: flex-start;
position: relative;
text-align: left;
margin-left: 10px;
margin-top: 40px;
}
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/pages/ResumeComment.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import axios from 'axios';
import { Worker, Viewer, SpecialZoomLevel } from '@react-pdf-viewer/core';
import { useParams, useNavigate } from 'react-router-dom';
import useIsAuthenticated from 'react-auth-kit/hooks/useIsAuthenticated';

import useAuthUser from 'react-auth-kit/hooks/useAuthUser';
import '@react-pdf-viewer/core/lib/styles/index.css';
import './ResumeComment.css';
Expand All @@ -27,7 +26,6 @@ const ResumeComment = () => {
const [highlights, setHighlights] = useState([]);
const [selectedCommentId, setSelectedCommentId] = useState(null);
const [isModalOpen, setModalOpen] = useState(false);

const viewerRef = useRef(null);
const commentBoxRef = useRef(null);

Expand Down
Loading

0 comments on commit 2b414db

Please sign in to comment.