From 98e0e5113a73bacab931d11c2aaee68ba090a125 Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Tue, 30 Jul 2024 23:00:43 +0530 Subject: [PATCH 1/2] 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 7e51b41129c3e0b6b9ebcbd24462879b28ef4435 Mon Sep 17 00:00:00 2001 From: balaharisankar Date: Sun, 4 Aug 2024 22:50:58 +0530 Subject: [PATCH 2/2] Answers Integrated in Q&A page --- .../src/pages/Q&A/AnswerModel/AnswerModel.jsx | 43 +++++++++- .../pages/Q&A/AnswerModel/AnswerModel.scss | 80 +++++++++++++++---- 2 files changed, 104 insertions(+), 19 deletions(-) diff --git a/frontend/src/pages/Q&A/AnswerModel/AnswerModel.jsx b/frontend/src/pages/Q&A/AnswerModel/AnswerModel.jsx index a0f7bfc4..aaf075af 100644 --- a/frontend/src/pages/Q&A/AnswerModel/AnswerModel.jsx +++ b/frontend/src/pages/Q&A/AnswerModel/AnswerModel.jsx @@ -1,16 +1,32 @@ -import React, { useState } from "react"; +import React, { useEffect, useState } from "react"; import { Modal, Backdrop, Fade } from '@material-ui/core'; import { SimpleToast } from '../../../components/util/Toast' -import {postAnswer} from '../../../service/Faq' +import {postAnswer,getAnswers} from '../../../service/Faq' import style from './AnswerModel.scss' export function AnswerModel(props) { const [answer, setAnswer] = useState("") + const[answers,setAnswers]=useState([]) const [toast, setToast] = useState({ toastStatus: false, toastType: "", toastMessage: "", }); + const filterAnswers=(fetchedAnswers)=>{ + return fetchedAnswers.filter((ans)=>{return ans.isApproved==true}) + } + async function fetchAnswers(){ + const data=await getAnswers(props.data._id,setToast) + setAnswers(filterAnswers(data)) + } + useEffect(()=>{ + fetchAnswers() + },[props]) + function timeStampFormatter(time){ + const months=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"] + const messageTime=new Date(time) + return `${String(messageTime.getDate())} ${String(months[messageTime.getMonth()])} ${String(messageTime.getFullYear())} ${String(messageTime.getHours()%12 || 12).padStart(2,'0')}:${String(messageTime.getMinutes()).padStart(2,'0')} ${messageTime.getHours()>=12?'pm':'am'}` + } const Tags = [ { value: "ml" }, { value: "open-source" }, @@ -75,7 +91,7 @@ export function AnswerModel(props) { props && props.data?.tags?.map((tag, index) => { if (tag) return ( -

#{Tags[index].value}

+

#{tag}

) }) } @@ -84,6 +100,27 @@ export function AnswerModel(props) { { setAnswer(e.target.value) }} value={answer} type="text" placeholder="Post your answer" /> +

Answers ({answers.length})

+ { + answers.length==0? +

No answers found...

+ : +
+ { + answers.map((ans,index)=>{ + return( +
+
+
{ans.created_by}
+

{timeStampFormatter(ans.created_on)}

+
+

{ans.answer}

+
+ ) + }) + } +
+ } diff --git a/frontend/src/pages/Q&A/AnswerModel/AnswerModel.scss b/frontend/src/pages/Q&A/AnswerModel/AnswerModel.scss index a087fd0f..3524d2a8 100644 --- a/frontend/src/pages/Q&A/AnswerModel/AnswerModel.scss +++ b/frontend/src/pages/Q&A/AnswerModel/AnswerModel.scss @@ -1,6 +1,7 @@ -:root{ +:root { font-family: "Futura LT Book"; } + .modal-container { width: 70%; height: auto; @@ -8,9 +9,13 @@ outline: none !important; padding: 20px 20px; border-radius: 12px; - h2{ + + h2 { margin: 0; } + + max-height: 100%; + overflow-y: scroll; } .modal { @@ -22,44 +27,52 @@ overflow-y: scroll; outline: none !important; } -.close-icon-container{ + +.close-icon-container { display: flex; justify-content: end; } -.close-icon{ + +.close-icon { font-size: 24px; padding-right: 20px; cursor: pointer; - color:#243e74; + color: #243e74; } -.ques-title{ - color:#243e74; + +.ques-title { + color: #243e74; } -.ques-description{ + +.ques-description { font-size: 16px; margin: 10px auto; } -.tag-container{ + +.tag-container { width: 100%; display: flex; gap: 8px; flex-wrap: wrap; } -.answer-form{ + +.answer-form { width: 100%; margin: 14px auto; display: flex; justify-content: space-between; gap: 8px; } -.answer-field{ + +.answer-field { width: 85%; padding: 10px 20px; outline: none; border: 1px solid #ccc; border-radius: 8px; } -.post-answer-btn{ + +.post-answer-btn { width: 15%; padding: 10px 20px; background-color: #243e74; @@ -68,17 +81,52 @@ border-radius: 8px; outline: none; } + +.answer-title { + color: #243e74; +} + +.answer-container { + width: 100%; + border-bottom: 1px solid #ccc; + padding-bottom: 20px; + margin-top: 20px; + + p { + margin-top: 8px; + font-size: 16px; + } +} + +.answer-header { + display: flex; + align-items: center; + gap: 10px; + + h5 { + margin: 0; + } + + p { + font-size: 12px; + margin: 0; + } +} + @media screen and (max-width:768px) { - .modal-container{ + .modal-container { width: 90%; } - .close-icon{ + + .close-icon { padding-right: 5px; } - .answer-field{ + + .answer-field { width: 70%; } - .post-answer-btn{ + + .post-answer-btn { width: 25%; } } \ No newline at end of file