const {body, validationResult} = require('express-validator'); const {_sr} = require('../plugins/serverResponses'); const {res404, res500} = require('../plugins/controllersHelperFunctions'); const Comment = require('../models/Comment'); const News = require('../models/News'); const ContactUs = require('../models/ContactUs'); const Category = require('../models/Category'); const Captcha = require('../models/Captcha'); const limit = 20; /////////////////////////////////////////////////////////////////////// admin module.exports.updateComment = [ [ body('name') .notEmpty().withMessage(_sr['fa'].required.name), body('description') .notEmpty().withMessage(_sr['fa'].required.description), body('email') .isEmail().withMessage(_sr['fa'].format.email), body('allowShow') .optional().isBoolean().withMessage(_sr['fa'].format.boolean), ], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() }); try { /** * get data from input */ var { name, description, email, allowShow } = req.body; /** * get id */ var commentId = req.params.id; /** * check comment exist or not */ var targetComment = await Comment.findOne({_id : commentId}); if(!targetComment) return res404(res,`پیام مورد نظر پیدا نشد`); /** * make update object */ targetComment.name = name.trim(); targetComment.description = description.trim(); targetComment.email = email; targetComment.allowShow = allowShow; await targetComment.save(); /** * show result */ return res.json(targetComment); } catch (error) { return res500(res , error?.message); } } ] module.exports.changeStatus = [ async (req, res) => { try { /** * get id */ var commentId = req.params.id; /** * check comment exist or not */ var targetComment = await Comment.findOne({_id : commentId}); if(!targetComment) return res404(res,`پیام مورد نظر پیدا نشد`); /** * make update object */ targetComment.allowShow = !targetComment.allowShow; await targetComment.save(); /** * show result */ return res.json(targetComment); } catch (error) { return res500(res , error.message); } } ] module.exports.deletOneComment = [ async (req, res) => { try { var commentId = req.params.id; /** * check comment */ var targetComment = await Comment.findOne({_id : commentId}); if(!targetComment){ return res404(res , `پیام مورد نظر پیدا نشد`); } /** * delete comment */ targetComment.deleteOne(); /** * show result */ return res.json(targetComment); } catch (error) { /** * if we got unknown error show to client */ res500(res , error); } } ] module.exports.getOneComment = [ async (req, res) => { try { const commentId = req.params.id; /** * get comment */ const targetComment = await Comment.findOne({_id : commentId}).populate('modelRef'); /** * if not exist */ if(!targetComment){ return res404(res , `پیام مورد نظر پیدا نشد`); } if(!targetComment.read){ targetComment.read = true; await targetComment.save(); } /** * show result */ return res.json(targetComment); } catch (error) { /** * if we got unknown error show to client */ res500(res , error); } } ] module.exports.getAll = [ async (req, res) => { try { let findQuery = {}; findQuery.modelName = req.params.model; if (req.params.model !== 'ContactUs'){ if (req.user.specialPermissions.length) { findQuery.catsId = {$in : req.user.specialPermissions}; } } /** * get all comment */ const getAll = await Comment.paginate(findQuery , {page: req.query.page || 1 , limit , populate : 'modelRef' , sort:{created_at : -1}}); /** * show result */ return res.json(getAll); } catch (error) { return res500(res , error.message); } } ] module.exports.getAllforCount = [ async (req, res) => { try { let findQuery = {}; findQuery.modelName = req.params.model; if (req.params.model !== 'ContactUs'){ if (req.user.specialPermissions.length) { findQuery.catsId = {$in : req.user.specialPermissions}; } } /** * get all comment */ const getAll = await Comment.find(findQuery).populate('modelRef'); /** * show result */ return res.json(getAll); } catch (error) { return res500(res , error.message); } } ] module.exports.search = [ async (req, res) => { try { var findQuery = {}; findQuery['$and'] = []; findQuery['$or'] = []; var { name, email, read, allowShow, date } = req.body; findQuery.modelName = req.params.model; if (req.params.model !== 'ContactUs'){ if (req.user.specialPermissions.length) { findQuery.catsId = {$in : req.user.specialPermissions}; } } /** search by term */ if (name && !_.isEmpty(name)) { findQuery['$or'].push( { name: { $regex: '.*' + name + '.*' }, } ); } /** search by email */ if (email && !_.isEmpty(email)) { findQuery['$and'].push({ email }); } /** search by read */ if (!_.isUndefined(read) && _.isBoolean(read)) { findQuery['$and'].push({ read }); } /** search by allowShow */ if (!_.isUndefined(allowShow) && _.isBoolean(allowShow)) { findQuery['$and'].push({ allowShow }) } /** search by date */ if (date && !_.isEmpty(date)) { if(date.length === 1){ findQuery['$and'].push({ created_at: { $gte: moment(date[0]).startOf('days'), $lt: moment(date[0]).endOf('days') } }); }else{ findQuery['$and'].push({ created_at: { $gte: new Date(date[0]), $lt: new Date(date[1]) } }); } } _.isEmpty(findQuery['$and']) && delete findQuery['$and']; _.isEmpty(findQuery['$or']) && delete findQuery['$or']; /** get comments */ var comments = await Comment.paginate(findQuery , {page : req.query.page , limit, populate : 'modelRef' , sort:{created_at : -1}}); /** show result */ return res.json(comments); } catch (error) { return res500(res ,error?.message) } } ] /////////////////////////////////////////////////////////////////////// public module.exports.addComment = [ [ body('name') .notEmpty().withMessage(_sr['fa'].required.title), body('description') .notEmpty().withMessage(_sr['fa'].required.description), body('email') .isEmail().withMessage(_sr['fa'].format.email), body('modelId') .if((value , {req}) => { return req.body.modelName !== 'contactus'; }) .notEmpty().withMessage(`این فیلد ${_sr['fa'].optional.string}`), body('modelName') .isString().withMessage(`این فیلد ${_sr['fa'].optional.string}`) .bail() .isIn(['news' , 'contactus' , 'category']).withMessage(`${_sr['fa'].optional.onlyValid} 'news' , 'contactus' , 'category'`), body('captcha') .notEmpty().withMessage(_sr['fa'].required.field) .custom((value , {req}) => { return Captcha.findOne({code : value}).then(data => { if (!data) return Promise.reject(`عبارت وارد شده صحیح نمیباشد`) else return true }) }), ], async (req, res) => { const errors = validationResult(req) if (!errors.isEmpty()) return res.status(422).json({ validation: errors.mapped() }); try { let { name, description, email, modelId, modelName } = req.body; let Model; switch (modelName) { case 'news': Model = News; modelName = 'News'; break; case 'contactus': Model = ContactUs modelName = 'ContactUs'; break; case 'category': Model = Category modelName = 'Category'; break; } let checkParent = null; if(modelName !== 'ContactUs'){ checkParent = await Model.findOne({_id : modelId}); if(!checkParent){ return res404(res , `ای دی فرستاده شده وجود ندارد`); } if(!checkParent?.allowComment){ return res.status(403).json({message : `شما اجازه پیام گذاشتن برای این خبر یا صفحه را ندارید`}); } } const commentData = { name : name.trim(), description : description.trim(), email : email.trim(), modelRef : modelId || null, modelName, modelType : checkParent?.modelType || null, _updatedBy : req.user?._id || null }; if (modelName !== 'ContactUs'){ commentData.catsId = modelName === 'Category' ? checkParent?.treeCat || [] : checkParent?.allCat || [] } /** * add new comment */ const create = await Comment.create(commentData); /** * check added or not */ if (!create) { return res500(res, `مشکلی در اضافه کردن پیام پیش آمده است`); } /** * show result */ return res.json(create); } catch (error) { /** * if we got unknown error show to client */ return res500(res , error?.message); } } ] module.exports.getCommentById = [ async (req , res) => { try { const modelId = req.params.id; const getComments = await Comment.find({modelRef: modelId, allowShow: true}); return res.json(getComments); } catch (error) { return res500(res , error?.message); } } ]