Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 19 additions & 4 deletions api/controllers/infopostControllers.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
const asyncHandler = require("express-async-handler");
const dotenv = require("dotenv");
const axios=require('axios');
dotenv.config();
const infopostModel = require("../models/infopostModel");
const imageModel = require("../models/imageModel");
const userModel = require("../models/userModel");
const notificationController = require("../controllers/notificationController");
const path = require("path");

// multer middleware for handling uploading images
const multer = require("multer");
const ROLES_LIST = require("../../config/roles_list");
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, "../html/uploads");
Expand Down Expand Up @@ -44,18 +49,28 @@ const postinfopost = asyncHandler(async (req, res) => {
savedImages.push(image.filename);
}
}
//defining tag for the question
const query=req.body.body;
const tag_response=await axios.post('http://localhost:5001/tag',{query});
const classified_tag=tag_response.data;
const infopost = new infopostModel({
body: req.body.body,
url: req.body.urls,
images: savedImages,
tag:classified_tag
});
const savedInfopost = await infopost.save();
// Notify all students about the new infopost
const allStudents = await userModel.find({ role: ROLES_LIST.STUDENT });
const studentIds = allStudents.map(student => student._id);
await notificationController.createNotification(1, studentIds, savedInfopost._id, "New infopost");


const message = "Infopost posted successfully";
await infopost.save().then((data) => {
res.json({data,message});
});
res.json({ data: savedInfopost, message });
});
} catch (err) {
res.status(400).res.json({ message: " An error occured while posting the infopost" });
res.status(400).json({ message: "An error occurred while posting the infopost" });
}
});

Expand Down
46 changes: 46 additions & 0 deletions api/controllers/notificationController.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
const asyncHandler = require("express-async-handler");
const dotenv = require("dotenv");
dotenv.config();
const notificationModel = require("../models/notificationModel");
const User = require('../models/userModel');
const path = require("path");
const ROLES_LIST = require("../../config/roles_list");

//Function for creating notifications
const createNotification = asyncHandler(async (senderid, recipientlist, contentid, content) => {
try {
const newNotification = new notificationModel({
senderid: senderid,
recipientlist: recipientlist,
contentid: contentid,
content: content
});
await newNotification.save();
console.log("Notification created:", newNotification);


return newNotification;
} catch (err) {
throw new Error("An error occurred while creating notification"+err.message);
}
});


// Function to get all notifications of a particular student
const getNotificationsByStudent = async (req, res) => {
try {
const studentId = req.params.studentId;

const notifications = await notificationModel.find({ recipientlist: studentId });

res.json({ notifications });
} catch (error) {
console.error("Error retrieving notifications:", error);
res.status(500).json({ error: 'An error occurred while retrieving notifications' });
}
};

module.exports = {
createNotification,
getNotificationsByStudent
};
137 changes: 88 additions & 49 deletions api/controllers/questionController.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
const axios= require('axios');
const dotenv = require("dotenv");
dotenv.config();
const asyncHandler = require("express-async-handler"); // the function of async handler here is to handle errors in async functions. https://www.npmjs.com/package/express-async-handler
Expand Down Expand Up @@ -42,6 +43,8 @@ const upload = multer({
const questionModel = require("../models/questionModel");
const userModel = require("../models/userModel");
const imageModel = require("../models/imageModel");
//import the controllers
const notificationController = require("../controllers/notificationController");

//-------------------------------------------------------------------------------------------------------------------------------------

Expand Down Expand Up @@ -88,6 +91,10 @@ const postQuestion = asyncHandler(async (req, res) => {
}
console.log("user found", um);
const message = "Question posted successfully";
//defining tag for the question
const query=body.body;
const tag_response=await axios.post('http://localhost:5001/tag',{query});
const classified_tag=tag_response.data;
//creating question
await questionModel
.create({
Expand All @@ -96,6 +103,7 @@ const postQuestion = asyncHandler(async (req, res) => {
body: body.body,
images: savedImages,
_id: qID,
tag:classified_tag
//reason I didn't initialise comment or answer is because it used to create a default answer and comment
})
.then(async (data) => {
Expand All @@ -109,8 +117,14 @@ const postQuestion = asyncHandler(async (req, res) => {
um.asked_questions = temp;
await um.save();

//creating tfidf embeddings
axios.get('http://localhost:5001/embed').then(
console.log('created embeddings')
)

res.json({data,message});
});

});
} catch (err) {
res.status(400).json({ message: "Error occured while posting the question" });
Expand Down Expand Up @@ -302,43 +316,60 @@ const answerQ = asyncHandler(async (req, res) => {

const body = req.body["answers"];
console.log("body", body);
const um = await userModel.findOne({ user_ID: body.user_ID });
if(!um){
res.status(401).json({error:"User not found"})

// const um = await userModel.findOne({ user_ID: body.user_ID });

const um = await userModel.findOne({ user_ID: req.body.user_ID });
if (!um) {
return res.status(401).json({ error: "User not found" });

}
console.log("user model", um);
let verified = false;
if (um.role === 5980) {
verified = true;
}
const message = "Successfully answered the question";
// Update the question with the provided answer
await questionModel
.updateOne(
{ _id: req.params.qid }, // this line is to find the question with the id
.findByIdAndUpdate(
req.params.qid,
{
$push: {
answers: [
{
body: body.body,
user_ID: body.user_ID,
user_Name: um.name,
images: savedImages,
verified: verified,
},
],
answers: {
body: req.body.body,
user_ID: req.body.user_ID,
user_Name: um.name,
images: savedImages,
verified: verified,
},
},
$set: { status: true },
}
},
{ new: true } // To return the updated document
)
.then((data) => {
res.json({data,message});
.then(async (updatedQuestion) => {
// To check if the question was found and updated
if (!updatedQuestion) {
return res.status(404).json({ error: "Question not found" });
}
// Notify the student that their question has been answered
const studentId = updatedQuestion.user_ID;
const answererId = req.body.user_ID;
const notifMessage = "Your question has been answered";
notificationController.createNotification(
answererId,
[studentId],
req.params.qid,
notifMessage
);
res.json({ data: updatedQuestion, message });
});
});
} catch (err) {
res.status(400).json({ message: "Error occured while answering the question" });
res.status(400).json({ message: "Error occurred while answering the question" });
}
});

//Commenting
//Commenting on a question
//no point of keeping track of comments
Expand All @@ -347,42 +378,50 @@ const commentQ = asyncHandler(async (req, res) => {
try {
const cID = new mongoose.Types.ObjectId();
const body = req.body["comments"];
const um = await userModel.findOne({ user_ID: body.user_ID });
if(!um){
res.status(401).json({error:"User not found"})

// const um = await userModel.findOne({ user_ID: body.user_ID });

const um = await userModel.findOne({ user_ID: req.body.user_ID });
if (!um) {
return res.status(401).json({ error: "User not found" });

}
console.log("user model", um);
const message = "Successfully commented on the question";
await questionModel
.updateOne(
{ _id: req.params.qid },
{
$push: {
comments: [
{
_id: cID,
body: body.body,
user_ID: body.user_ID,
user_Name: um.name,
},
],
// Update the question document by pushing the new comment
await questionModel.findByIdAndUpdate(
req.params.qid,
{
$push: {
comments: {
_id: cID,
body: req.body.body,
user_ID: req.body.user_ID,
user_Name: um ? um.name : 'Unknown', // Handle case where user is not found
},
}
)
.then(async (data) => {
console.log(cID.valueOf());
//inserting posted comment id to user model

const temp = um.question_comments.concat([
{ questionID: req.params.qid, commentID: cID.valueOf() },
]);
um.question_comments = temp;
await um.save();
res.json({data,message});
});
},
},
);
//Notify the student that someone commented on their question
const studentid = (await questionModel.findById(req.params.qid)).user_ID;
const senderid = req.body.user_ID;
const notifMessage = "Your question has been commented on";
notificationController.createNotification(
senderid,
[studentid],
req.params.qid,
notifMessage
);
// Insert the posted comment ID to user model
const temp = um.question_comments.concat([
{ questionID: req.params.qid, commentID: cID.valueOf() },
]);
um.question_comments = temp;
await um.save();
res.json({ message });
} catch (err) {
console.log(err);
res.status(400).res.json({ message: "Error occured while commenting on the question" });
res.status(400).json({ message: "Error occurred while commenting on the question" });
}
});

Expand Down
1 change: 1 addition & 0 deletions api/models/infopostModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const infopostSchema = mongoose.Schema({
hidden: { type: Boolean, default: false },
images: [{ type: String }],
asked_At: { type: Date, default: Date.now },
tag: { type: String, required: true }
});

const infopostModel = mongoose.model("infopostModel", infopostSchema);
Expand Down
16 changes: 16 additions & 0 deletions api/models/notificationModel.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
const mongoose=require('mongoose')

const notificationSchema = mongoose.Schema({
id: mongoose.Schema.Types.ObjectId,
recipientlist: [{type: String, required: true}],
senderid: {type: String, required: true},
contentid: {type: String, required: true},
content: {type: String },
sent_At: {type: Date, default: Date.now},
isseen: {type: Boolean, default: false, required: true}

});

const notificationModel = mongoose.model("notificationModel", notificationSchema);

module.exports = notificationModel;
1 change: 1 addition & 0 deletions api/models/questionModel.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ const QuestionSchema = mongoose.Schema({
answers: [AnswerSchema],
comments: [commentSchema],
verified: { type: Boolean, default: false },
tag: { type: String, required: true }
});

//create model of the schema
Expand Down
9 changes: 9 additions & 0 deletions api/routes/notificationRouters.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const express = require('express');
const router = express.Router();
const notificationController = require('../controllers/notificationController');

// Route to get all notifications of a particular student
router.get('/:studentId', notificationController.getNotificationsByStudent);


module.exports = router;
Loading