From 98e0e5113a73bacab931d11c2aaee68ba090a125 Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Tue, 30 Jul 2024 23:00:43 +0530 Subject: [PATCH 1/3] Upvote and Downvotes fixed --- backend/app.js | 16 +- backend/app/models/question.js | 4 + .../routes/Q&A/question/downvoteQuestion.js | 26 +-- .../app/routes/Q&A/question/upvoteQuestion.js | 2 +- frontend/src/pages/Q&A/Q&A.jsx | 2 +- frontend/src/service/Faq.jsx | 210 +++++++++--------- 6 files changed, 131 insertions(+), 129 deletions(-) diff --git a/backend/app.js b/backend/app.js index 2c6a34c5..ea39cea0 100644 --- a/backend/app.js +++ b/backend/app.js @@ -15,8 +15,20 @@ app.use(express.static('uploads')); // Set security headers app.use(helmet()); +// cookie +app.use(cookieParser()); + // CORS -app.use(cors()); +// app.use(cors()); +app.use(cors({credentials:true,origin:process.env.FRONTEND_URL})); + +app.use(function(req, res, next) { + res.header('Access-Control-Allow-Credentials', true); + res.header('Access-Control-Allow-Origin', process.env.FRONTEND_URL); + res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,UPDATE,OPTIONS'); + res.header('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept'); + next(); +}); // Body Parser app.use(express.json({ limit: '50mb' })); @@ -25,8 +37,6 @@ app.use(express.urlencoded({ limit: '50mb', extended: true })); // Response time app.use(responseTime({ suffix: false })); -// cookie -app.use(cookieParser()); // Use routes app.use('/', routes); diff --git a/backend/app/models/question.js b/backend/app/models/question.js index 43051a07..4fe46114 100644 --- a/backend/app/models/question.js +++ b/backend/app/models/question.js @@ -25,6 +25,10 @@ const questionSchema = new Schema( type: Number, default: 0, }, + downvotes:{ + type:Number, + default:0 + } }, { timestamps: { createdAt: 'createdAt', updatedAt: 'updatedAt' } } ); diff --git a/backend/app/routes/Q&A/question/downvoteQuestion.js b/backend/app/routes/Q&A/question/downvoteQuestion.js index d29b7869..3dcc23b9 100644 --- a/backend/app/routes/Q&A/question/downvoteQuestion.js +++ b/backend/app/routes/Q&A/question/downvoteQuestion.js @@ -6,25 +6,11 @@ const { getVoteCookieName } = require('../../../../helpers/middlewares/cookie'); module.exports = async (req, res, next) => { const { questionId } = req.body; - const [err] = await to( - question.updateOne({ _id: questionId }, [ - { - $set: { - upvotes: { - $cond: [ - { - $gt: ['$upvotes', 0], - }, - { - $subtract: ['$upvotes', 1], - }, - 0, - ], - }, - }, - }, - ]) - ); + const existingQues=await question.findById(questionId) + if(!existingQues.downvotes){ + const [err] = await to(question.updateOne({ _id: questionId },{$set:{downvotes:0}})); + } + const [err] = await to(question.updateOne({ _id: questionId }, { $inc: { downvotes: 1 } })); if (err) { console.log(err); const error = new ErrorHandler(constants.ERRORS.DATABASE, { @@ -36,7 +22,7 @@ module.exports = async (req, res, next) => { return next(error); } - res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000 }); + res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000, sameSite: "none", secure: true }); res.status(200).send({ message: 'Question has been down voted', }); diff --git a/backend/app/routes/Q&A/question/upvoteQuestion.js b/backend/app/routes/Q&A/question/upvoteQuestion.js index 77a1b2a2..671dca9d 100644 --- a/backend/app/routes/Q&A/question/upvoteQuestion.js +++ b/backend/app/routes/Q&A/question/upvoteQuestion.js @@ -16,7 +16,7 @@ module.exports = async (req, res, next) => { return next(error); } - res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000 }); + res.cookie(getVoteCookieName('question', questionId), true, { maxAge: 20 * 365 * 24 * 60 * 60 * 1000,sameSite:"none",secure:true }); res.status(200).send({ message: 'Question has been upvoted', diff --git a/frontend/src/pages/Q&A/Q&A.jsx b/frontend/src/pages/Q&A/Q&A.jsx index d9d2e1bb..0423c21d 100644 --- a/frontend/src/pages/Q&A/Q&A.jsx +++ b/frontend/src/pages/Q&A/Q&A.jsx @@ -191,7 +191,7 @@ function Ques(props) { className="vote-btn" onClick={() => handleDownvote(item._id)} > - 👎 {item?.downvote} + 👎 {item?.downvotes} diff --git a/frontend/src/service/Faq.jsx b/frontend/src/service/Faq.jsx index f23e7c8b..d3ee876c 100644 --- a/frontend/src/service/Faq.jsx +++ b/frontend/src/service/Faq.jsx @@ -2,127 +2,127 @@ import { END_POINT } from "../config/api"; import { showToast } from "./toastService"; export async function postFaq(formData, setToast, toast) { - try { - const response = await fetch(`${END_POINT}/faq/postFaq`, { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${localStorage.getItem("token")}`, - }, - body: JSON.stringify(formData), + try { + const response = await fetch(`${END_POINT}/faq/postFaq`, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${localStorage.getItem("token")}`, + }, + body: JSON.stringify(formData), + }); + + if (response.ok) { + setToast({ + ...toast, + toastMessage: "FAQ has been added", + toastStatus: true, + toastType: "success", }); - - if (response.ok) { - setToast({ - ...toast, - toastMessage: "FAQ has been added", - toastStatus: true, - toastType: "success", - }); - return { success: true }; - } else { - setToast({ - ...toast, - toastMessage: "Database Error", - toastStatus: true, - toastType: "error", - }); - return { success: false, error: "Database Error" }; - } - } catch (error) { + return { success: true }; + } else { setToast({ ...toast, - toastMessage: "Network Error", + toastMessage: "Database Error", toastStatus: true, toastType: "error", }); - return { success: false, error: "Network Error" }; + return { success: false, error: "Database Error" }; } + } catch (error) { + setToast({ + ...toast, + toastMessage: "Network Error", + toastStatus: true, + toastType: "error", + }); + return { success: false, error: "Network Error" }; } +} export async function getFaq() { - try { - const response = await fetch(`${END_POINT}/faq/getFaq`); - if (!response.ok) { - throw new Error("Failed to fetch FAQs"); - } - const data = await response.json(); - return data.Faq; - } catch (error) { - console.error("Failed to fetch FAQs:", error.message); + try { + const response = await fetch(`${END_POINT}/faq/getFaq`); + if (!response.ok) { throw new Error("Failed to fetch FAQs"); } + const data = await response.json(); + return data.Faq; + } catch (error) { + console.error("Failed to fetch FAQs:", error.message); + throw new Error("Failed to fetch FAQs"); + } } -export const deleteFaq = async (faqId, setToast, toast) => { - const url = `${END_POINT}/faq/deleteFaq`; - const body = { faqId: faqId }; - const headers = { - "Content-Type": "application/json", - authorization: `Bearer ${localStorage.getItem("token")}`, - }; - try { - const response = await fetch(url, { - method: "PUT", - headers: headers, - body: JSON.stringify(body), - }); - if (!response.ok) { - throw new Error(`HTTP error! status: ${response.status}`); - } - const data = await response.json(); - setToast({ - ...toast, - toastMessage: data.message, - toastStatus: true, - toastType: "success", - }); - return data.message; - } catch (error) { - console.error("Failed to delete FAQ:", error.message); - setToast({ - ...toast, - toastMessage: "Failed to delete FAQ", - toastStatus: true, - toastType: "error", - }); - throw new Error("Failed to delete FAQ"); +export const deleteFaq = async (faqId, setToast, toast) => { + const url = `${END_POINT}/faq/deleteFaq`; + const body = { faqId: faqId }; + const headers = { + "Content-Type": "application/json", + authorization: `Bearer ${localStorage.getItem("token")}`, + }; + try { + const response = await fetch(url, { + method: "PUT", + headers: headers, + body: JSON.stringify(body), + }); + if (!response.ok) { + throw new Error(`HTTP error! status: ${response.status}`); } + const data = await response.json(); + setToast({ + ...toast, + toastMessage: data.message, + toastStatus: true, + toastType: "success", + }); + return data.message; + } catch (error) { + console.error("Failed to delete FAQ:", error.message); + setToast({ + ...toast, + toastMessage: "Failed to delete FAQ", + toastStatus: true, + toastType: "error", + }); + throw new Error("Failed to delete FAQ"); + } }; export const updateFaq = async (faqId, updatedFaqDetails, setToast, toast) => { - try { - const response = await fetch(`${END_POINT}/faq/updateFaq`, { - method: "PATCH", - headers: { - "Content-Type": "application/json", - authorization: `Bearer ${localStorage.getItem("token")}`, - }, - body: JSON.stringify({ faqId, ...updatedFaqDetails }), - }); - - if (!response.ok) { - throw new Error("Failed to update FAQ"); - } + try { + const response = await fetch(`${END_POINT}/faq/updateFaq`, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + authorization: `Bearer ${localStorage.getItem("token")}`, + }, + body: JSON.stringify({ faqId, ...updatedFaqDetails }), + }); - const data = await response.json(); - setToast({ - ...toast, - toastMessage: data.message, - toastStatus: true, - toastType: "success", - }); - return data.message; - } catch (error) { - console.error("Failed to update FAQ:", error.message); - setToast({ - ...toast, - toastMessage: "Failed to update FAQ", - toastStatus: true, - toastType: "error", - }); - throw new Error("Failed to update FAQ"); + if (!response.ok) { + throw new Error("Failed to update FAQ"); } + + const data = await response.json(); + setToast({ + ...toast, + toastMessage: data.message, + toastStatus: true, + toastType: "success", + }); + return data.message; + } catch (error) { + console.error("Failed to update FAQ:", error.message); + setToast({ + ...toast, + toastMessage: "Failed to update FAQ", + toastStatus: true, + toastType: "error", + }); + throw new Error("Failed to update FAQ"); + } }; export const getAllQuestions = async (setToast, toast) => { @@ -292,6 +292,7 @@ export const upvote = async (questionId, handleToast) => { headers: { "Content-Type": "application/json", }, + credentials: "include", body: JSON.stringify({ questionId }), }); if (!response.ok) { @@ -300,7 +301,7 @@ export const upvote = async (questionId, handleToast) => { showToast(handleToast, "Upvote Successfully"); return response.json(); } catch (error) { - showToast(handleToast, "Failed to upvote question", "error"); + showToast(handleToast, "You have already voted", "error"); throw new Error("Failed to upvote question"); } }; @@ -312,6 +313,7 @@ export const downvote = async (questionId, handleToast) => { headers: { "Content-Type": "application/json", }, + credentials: "include", body: JSON.stringify({ questionId }), }); if (!response.ok) { @@ -320,7 +322,7 @@ export const downvote = async (questionId, handleToast) => { showToast(handleToast, "Downvote Successfully"); return response.json(); } catch (error) { - showToast(handleToast, "Failed to downvote question", "error"); + showToast(handleToast, "You have already voted", "error"); throw new Error("Failed to downvote question"); } -}; \ No newline at end of file +}; From 2973a13fe6d1888ca5224eb35bcc75c3b16bdc42 Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Sat, 10 Aug 2024 00:38:04 +0530 Subject: [PATCH 2/3] Footer social icons adjusted --- frontend/src/components/Footer/footer.module.scss | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/frontend/src/components/Footer/footer.module.scss b/frontend/src/components/Footer/footer.module.scss index 466cbf42..63cbc0b8 100644 --- a/frontend/src/components/Footer/footer.module.scss +++ b/frontend/src/components/Footer/footer.module.scss @@ -207,7 +207,6 @@ color: #dd2a7b; } - .fa-envelope:hover, .fa-envelope-own:hover { color: #c71610; @@ -703,7 +702,7 @@ a > span { } } -@media screen and (max-width: 510px) { +@media screen and (max-width: 1124px) { .col .social { display: grid; grid-template-columns: 50% 50%; From 1ad17fc302edd319cee99fc6a84d62cf91569567 Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Sat, 10 Aug 2024 12:27:51 +0530 Subject: [PATCH 3/3] Sent mail on approving every broadcast to the subscribers --- .../broadcast/@validationSchema/index.js | 3 +- .../app/routes/broadcast/updateBroadcast.js | 76 +++++++++++++++---- backend/utility/emailTemplates.js | 18 +++++ .../Broadcast/ManageBroadcasts/Card/Card.jsx | 5 +- 4 files changed, 86 insertions(+), 16 deletions(-) diff --git a/backend/app/routes/broadcast/@validationSchema/index.js b/backend/app/routes/broadcast/@validationSchema/index.js index 934ef07f..45962dad 100644 --- a/backend/app/routes/broadcast/@validationSchema/index.js +++ b/backend/app/routes/broadcast/@validationSchema/index.js @@ -20,7 +20,8 @@ const updateBroadcastValidationSchema = Joi.object().keys({ imageUrl: Joi.array().min(1).items(Joi.string().uri()), tags: Joi.array().min(1).items(Joi.string()), isApproved: Joi.boolean().required(), - id : Joi.string().min(24).max(24).required() + id : Joi.string().min(24).max(24).required(), + approving:Joi.boolean() }); const getBroadcastsValidationSchema = Joi.object().keys({ diff --git a/backend/app/routes/broadcast/updateBroadcast.js b/backend/app/routes/broadcast/updateBroadcast.js index be508474..ba3e6b83 100644 --- a/backend/app/routes/broadcast/updateBroadcast.js +++ b/backend/app/routes/broadcast/updateBroadcast.js @@ -1,12 +1,16 @@ const to = require('await-to-js').default; const Broadcast = require('../../models/Broadcast'); +const Subscribers = require('../../models/Subscriber'); const { ErrorHandler } = require('../../../helpers/error'); const constants = require('../../../constants'); +const nodemailer = require('nodemailer') +const config = require('../../../config') +const { broadcastPublishMailTemplate } = require('../../../utility/emailTemplates') -module.exports = async (req, res, next) => { - if(Object.keys(req.body).length <= 1) { +module.exports = async (req, res, next) => { + if (Object.keys(req.body).length <= 1) { return res.status(200).send({ - message : "Not Sufficient Data" + message: "Not Sufficient Data" }) } @@ -15,11 +19,13 @@ module.exports = async (req, res, next) => { }; delete data.id; + let approving = data?.approving + delete data?.approving - const [err, result] = await to(Broadcast.findOneAndUpdate({ _id : req.body.id }, { $set : data })); + const [err, result] = await to(Broadcast.findOneAndUpdate({ _id: req.body.id }, { $set: data })); // error occured due to the some problem - if(err) { + if (err) { const error = new ErrorHandler(constants.ERRORS.DATABASE, { statusCode: 500, message: 'Database Error', @@ -28,9 +34,9 @@ module.exports = async (req, res, next) => { return next(error); } - + // if result is null that means broadcast with given id is not exist in collection - if(result === null) { + if (result === null) { const broadcastNotExistsError = new ErrorHandler(constants.ERRORS.INPUT, { statusCode: 400, message: 'Broadcast Not Exist...', @@ -38,11 +44,55 @@ module.exports = async (req, res, next) => { return next(broadcastNotExistsError); } - - // success response - res.status(200).send({ - message : "Broadcast Updated..." + var subscribers; + if (approving && data?.isApproved == true) { + const transporter = nodemailer.createTransport({ + type: 'SMTP', + host: config.EMAIL_HOST, + secure: true, + debug: true, + port: 465, + auth: { + user: config.EMAIL_USER, + pass: config.EMAIL_PASS, + }, + }); + subscribers = await Subscribers.find(); + subscribers = subscribers.map((subscriber) => { return subscriber?.email }) + + const mailOptions = { + from: `HITK TECH Community <${config.EMAIL_USER}>`, + to: "hitktechcommunity@gmail.com", + subject: `New Broadcast: ${data?.title} 😍`, + html: broadcastPublishMailTemplate(data), + bcc: subscribers, + attachments: data?.imageUrl.map((image, index) => { + return { + filename: `${data?.title}${index+1}`, + path: image + } + }) + }; + await transporter.sendMail(mailOptions).catch((err) => { + if (err) { + const error = new ErrorHandler(constants.ERRORS.UNEXPECTED, { + statusCode: 500, + message: 'The server encountered an unexpected condition which prevented it from fulfilling the request.', + errStack: err, + user: req.body.email, + }); + throw error; + } }); - - return next(); + } + + + + + // success response + res.status(200).send({ + message: "Broadcast Updated...", + }); + + return next(); } \ No newline at end of file diff --git a/backend/utility/emailTemplates.js b/backend/utility/emailTemplates.js index 118e8382..6c7c4118 100644 --- a/backend/utility/emailTemplates.js +++ b/backend/utility/emailTemplates.js @@ -119,4 +119,22 @@ module.exports.welcomeSubscriberMailTemplate=()=>{ The HITK Tech Community Team ` return emailContent +} + +module.exports.broadcastPublishMailTemplate=(data)=>{ + const emailContent=` +

Hello there

+

${data?.title}

+ ${data?.content} + Click here +
+ For more resource See all broadcasts +
+
+ Best regards
+ The HITK Tech Community + + `; + + return emailContent; } \ No newline at end of file diff --git a/frontend/src/pages/Admin/Components/Broadcast/ManageBroadcasts/Card/Card.jsx b/frontend/src/pages/Admin/Components/Broadcast/ManageBroadcasts/Card/Card.jsx index 6c1ebfc8..98d09f1d 100644 --- a/frontend/src/pages/Admin/Components/Broadcast/ManageBroadcasts/Card/Card.jsx +++ b/frontend/src/pages/Admin/Components/Broadcast/ManageBroadcasts/Card/Card.jsx @@ -60,6 +60,7 @@ export function Card(props) { tags: project.tags, isApproved: true, title: project.title, + approving: true, }; const res = await UpdateBoardCast(data, setToast, toast); if (res) { @@ -167,9 +168,9 @@ export function Card(props) { > View Details - +
- {!props?.project?.isApproved && ( + {!props?.project?.isApproved && (