modified: controllers/application/academy/academyCategoryController.js

modified:   controllers/application/academy/academyControllers.js
	modified:   controllers/application/academy/helpers/chatHelpers.js
	modified:   controllers/application/academy/middlewares/404.js
	modified:   controllers/application/academy/middlewares/adminAuth.js
	modified:   controllers/application/academy/middlewares/auth.js
	modified:   controllers/application/academy/middlewares/blockCheck.js
	modified:   controllers/application/academy/middlewares/exception.js
	modified:   controllers/application/academy/middlewares/index.js
	modified:   controllers/application/academy/middlewares/isHalfRegister.js
	modified:   controllers/application/academy/middlewares/isRegister.js
	modified:   controllers/application/academy/middlewares/lastOnline.js
	modified:   controllers/application/academy/middlewares/upload.js
	modified:   controllers/application/academy/models/AcademyCategoryModel.js
	modified:   controllers/application/academy/models/AcademyContentModel.js
	modified:   controllers/application/academy/models/AcademyLikeModel.js
	modified:   controllers/application/academy/models/AcademyModel.js
	modified:   controllers/application/academy/models/AcademyPaymentModel.js
	modified:   controllers/application/academy/models/AdminModel.js
	modified:   controllers/application/academy/models/AdvertisingCategoryModel.js
	modified:   controllers/application/academy/models/AdvertisingCommentModel.js
	modified:   controllers/application/academy/models/AdvertisingFeaturesModel.js
	modified:   controllers/application/academy/models/AdvertisingLikeModel.js
	modified:   controllers/application/academy/models/AdvertisingModel.js
	modified:   controllers/application/academy/models/AdvertisingProfile.js
	modified:   controllers/application/academy/models/AdvertisingRatingModel.js
	modified:   controllers/application/academy/models/AdvertisingTypeModel.js
	modified:   controllers/application/academy/models/CommentModel.js
	modified:   controllers/application/academy/models/CourseComentModel.js
	modified:   controllers/application/academy/models/CourseModel.js
	modified:   controllers/application/academy/models/CoursePaymentModel.js
	modified:   controllers/application/academy/models/ExpertiseModel.js
	modified:   controllers/application/academy/models/IsPaymentCourseModel.js
	modified:   controllers/application/academy/models/LikeModel.js
	modified:   controllers/application/academy/models/MessageModel.js
	modified:   controllers/application/academy/models/NotificationModel.js
	modified:   controllers/application/academy/models/OfferModel.js
	modified:   controllers/application/academy/models/OfferTypeModel.js
	modified:   controllers/application/academy/models/PaymentModel.js
	modified:   controllers/application/academy/models/PostModel.js
	modified:   controllers/application/academy/models/ProjectModel.js
	modified:   controllers/application/academy/models/RequestModel.js
	modified:   controllers/application/academy/models/SettingsModel.js
	modified:   controllers/application/academy/models/StateCity.js
	modified:   controllers/application/academy/models/TaxModel.js
	modified:   controllers/application/academy/models/TicketMessageModel.js
	modified:   controllers/application/academy/models/TicketModel.js
	modified:   controllers/application/academy/models/TypeAndPriceModel.js
	modified:   controllers/application/academy/models/UserModel.js
	modified:   controllers/application/academy/models/VersionModel.js
	modified:   controllers/application/academy/models/license.js
	modified:   controllers/application/advertising/advertisingController.js
	modified:   controllers/application/citysController.js
	modified:   controllers/application/expertise/expertiseController.js
	modified:   controllers/application/financial/financialController.js
	modified:   controllers/application/login/changePasswordController.js
	modified:   controllers/application/login/loginController.js
	modified:   controllers/application/login/loginWithUserName.js
	modified:   controllers/application/login/verifyController.js
	modified:   controllers/application/messages/messageController.js
	modified:   controllers/application/notification/notificationController.js
	modified:   controllers/application/offer/offerController.js
	modified:   controllers/application/payment/paymentController.js
	modified:   controllers/application/payment/paymentControllerWeb.js
	modified:   controllers/application/posts/likeController.js
	modified:   controllers/application/posts/postController.js
	modified:   controllers/application/profile/profileController.js
	modified:   controllers/application/projects/createProjectController.js
	modified:   controllers/application/projects/getProjectController.js
	modified:   controllers/application/projects/projectTypesController.js
	modified:   controllers/application/projects/requestProjectController.js
	modified:   controllers/application/projects/updateProjectController.js
	modified:   controllers/application/provincesController.js
	modified:   controllers/application/register/registerController.js
	modified:   controllers/application/register/userFullNameController.js
	modified:   controllers/application/register/userTypeController.js
	modified:   controllers/application/register/usernameController.js
	modified:   controllers/application/register/verifyController.js
	modified:   controllers/application/search-web/searchController.js
	modified:   controllers/application/search/searchController.js
	modified:   controllers/application/settings/settingsController.js
	modified:   controllers/application/tickets/ticketsController.js
	modified:   controllers/application/users/getUserController.js
	modified:   controllers/application/verify/addressController.js
	modified:   controllers/application/verify/authController.js
	modified:   controllers/application/verify/colorsController.js
	modified:   controllers/application/verify/conversationController.js
	modified:   controllers/application/verify/cooperationTypeController.js
	modified:   controllers/application/verify/expertiseController.js
	modified:   controllers/application/verify/genderController.js
	modified:   controllers/application/verify/servicesController.js
	modified:   controllers/application/verify/setNationalCardImageController.js
	modified:   controllers/application/verify/setProfileImageController.js
	modified:   controllers/application/verify/sizesController.js
	modified:   controllers/application/version/versionController.js
	modified:   controllers/application/workroom/workroomController.js
	modified:   controllers/panel/advertising/academyCategoryController.js
	modified:   controllers/panel/advertising/advertisingController.js
	modified:   controllers/panel/comments/advertisingCommentController.js
	modified:   controllers/panel/comments/commentController.js
	modified:   controllers/panel/expertise/expertiseController.js
	modified:   controllers/panel/financial/financialController.js
	modified:   controllers/panel/login/loginController.js
	modified:   controllers/panel/posts/postController.js
	modified:   controllers/panel/projects/projectController.js
	modified:   controllers/panel/projects/projectTypesController.js
	modified:   controllers/panel/settings/settingsController.js
	modified:   controllers/panel/shops/shopsController.js
	modified:   controllers/panel/tickets/ticketsController.js
	modified:   controllers/panel/users/usersController.js
	modified:   controllers/panel/version/versionController.js
	modified:   helpers/chatHelpers.js
	modified:   index.js
	deleted:    logs/sms-irs/13-03-2024.log
	modified:   middlewares/404.js
	modified:   middlewares/adminAuth.js
	modified:   middlewares/auth.js
	modified:   middlewares/blockCheck.js
	modified:   middlewares/exception.js
	modified:   middlewares/index.js
	modified:   middlewares/isHalfRegister.js
	modified:   middlewares/isRegister.js
	modified:   middlewares/lastOnline.js
	modified:   middlewares/upload.js
	modified:   models/AcademyCategoryModel.js
	modified:   models/AcademyContentModel.js
	modified:   models/AcademyLikeModel.js
	modified:   models/AcademyModel.js
	modified:   models/AcademyPaymentModel.js
	modified:   models/AdminModel.js
	modified:   models/AdvertisingCategoryModel.js
	modified:   models/AdvertisingCommentModel.js
	modified:   models/AdvertisingFeaturesModel.js
	modified:   models/AdvertisingLikeModel.js
	modified:   models/AdvertisingModel.js
	modified:   models/AdvertisingProfile.js
	modified:   models/AdvertisingRatingModel.js
	modified:   models/AdvertisingTypeModel.js
	modified:   models/CommentModel.js
	modified:   models/CourseComentModel.js
	modified:   models/CourseModel.js
	modified:   models/CoursePaymentModel.js
	modified:   models/ExpertiseModel.js
	modified:   models/IsPaymentCourseModel.js
	modified:   models/LikeModel.js
	modified:   models/MessageModel.js
	modified:   models/NotificationModel.js
	modified:   models/OfferModel.js
	modified:   models/OfferTypeModel.js
	modified:   models/PaymentModel.js
	modified:   models/PostModel.js
	modified:   models/ProjectModel.js
	modified:   models/RequestModel.js
	modified:   models/SettingsModel.js
	modified:   models/StateCity.js
	modified:   models/TaxModel.js
	modified:   models/TicketMessageModel.js
	modified:   models/TicketModel.js
	modified:   models/TypeAndPriceModel.js
	modified:   models/UserModel.js
	modified:   models/VersionModel.js
	modified:   models/license.js
	modified:   routes/application/academy/index.js
	modified:   routes/application/advertising/index.js
	modified:   routes/application/city/index.js
	modified:   routes/application/expertise/index.js
	modified:   routes/application/financial/index.js
	modified:   routes/application/login/index.js
	modified:   routes/application/messages/index.js
	modified:   routes/application/notification/index.js
	modified:   routes/application/offers/index.js
	modified:   routes/application/posts/index.js
	modified:   routes/application/profile/index.js
	modified:   routes/application/projects/index.js
	modified:   routes/application/provinces/index.js
	modified:   routes/application/register/index.js
	modified:   routes/application/search-web/index.js
	modified:   routes/application/search/index.js
	modified:   routes/application/settings/index.js
	modified:   routes/application/tickets/index.js
	modified:   routes/application/users/index.js
	modified:   routes/application/verify/index.js
	modified:   routes/application/version/index.js
	modified:   routes/application/workroom/index.js
	modified:   routes/index.js
	modified:   routes/panel/advertising/index.js
	modified:   routes/panel/comments/index.js
	modified:   routes/panel/expertise/index.js
	modified:   routes/panel/financial/index.js
	modified:   routes/panel/login/index.js
	modified:   routes/panel/posts/index.js
	modified:   routes/panel/projects/index.js
	modified:   routes/panel/settings/index.js
	modified:   routes/panel/shops/index.js
	modified:   routes/panel/tickets/index.js
	modified:   routes/panel/users/index.js
	modified:   routes/panel/version/index.js
	modified:   scripts/dns/db.modstagram.com
	modified:   scripts/dns/db.modstagram.ir
	modified:   scripts/dns/named.conf.local.snippet
	modified:   scripts/nginx/api.modstagram.com.conf
	modified:   scripts/nginx/app.modstagram.com.conf
	modified:   scripts/nginx/blog.modstagram.com.conf
	modified:   scripts/nginx/cdn.modstagram.com.conf
	modified:   scripts/nginx/cdn.modstagram.com.http.conf
	modified:   scripts/nginx/modstagram-redirects.conf
	modified:   scripts/nginx/modstagram.com.conf
	modified:   scripts/nginx/panel.modstagram.com.conf
	modified:   scripts/nginx/pay.modstagram.com.conf
	modified:   scripts/server-setup.sh
	modified:   services/AdvertisingCron.js
	modified:   services/ProjectCron.js
	modified:   services/TokenService.js
	deleted:    storage/courses/videos/course-69f8b2da55f31efffa601c57-1778257437373.mp4
	deleted:    storage/courses/videos/course-69f8b2da55f31efffa601c57-1778257586892.mp4
	deleted:    storage/courses/videos/course-69f8b2da55f31efffa601c57-1778257829783.mp4
	deleted:    storage/courses/videos/course-69f8b2da55f31efffa601c57-1778257903018.mp4
	deleted:    storage/posts/videos/1766758940571-0-video_2025-05-21_16-30-58.mp4
	deleted:    storage/posts/videos/1766781626514-0-video_2025-05-21_16-30-58.mp4
	deleted:    storage/posts/videos/1766824222908-0-Find 'modeling videos' on TikTok - TikTok Search_7.mp4
	deleted:    storage/posts/videos/1766824281937-0-Find 'modeling videos' on TikTok - TikTok Search_6.mp4
	deleted:    storage/posts/videos/1766824360366-0-Find 'bridal makeup' on TikTok - TikTok Search_4.mp4
	deleted:    storage/posts/videos/1766824425868-0-Find 'Makeup' on TikTok - TikTok Search_25.mp4
	deleted:    storage/posts/videos/1766824503238-0-Find 'Makeup' on TikTok - TikTok Search.mp4
	deleted:    storage/posts/videos/1766824554864-0-Jalal.hafed (@jalal.hafed) Official.mp4
	deleted:    storage/posts/videos/1766824618322-0-Find 'Hairdressing' on TikTok - TikTok Search_3.mp4
	deleted:    storage/posts/videos/1766824689078-0-Find 'Beauty clinic' on TikTok - TikTok Search_22.mp4
	deleted:    storage/posts/videos/1766824721659-0-Find 'Beauty clinic' on TikTok - TikTok Search_13.mp4
	deleted:    storage/posts/videos/1766824796958-0-Find 'photography' on TikTok - TikTok Search_6.mp4
	deleted:    storage/posts/videos/1766825351987-0-aaaa.mp4
	deleted:    storage/posts/videos/1766825448136-0-sasasa.mp4
	deleted:    storage/posts/videos/1766825535111-0-qqq.mp4
	deleted:    "storage/posts/videos/1766825855902-0-Nail desin by Labella beauty salon\360\237\214\270\360\237\222\205\360\237\217\273  #nail #nailart #manicure #manicure\360\237\222\205 #salon #pedicure #labella.mp4"
	deleted:    storage/posts/videos/1766825905907-0-dsdsdsdsdsds.mp4
	deleted:    "storage/posts/videos/1766826114243-0-Every piece of jewelry tells a story\360\237\217\271  @mirjaliligold @mohseneh_b.mp4"
	deleted:    "storage/posts/videos/1766826180365-0-Romeo, save me\360\237\246\242.mp4"
	deleted:    storage/posts/videos/1766826458195-0-aaaaa.mp4
	deleted:    storage/posts/videos/1766826609640-0-asasa.mp4
	deleted:    storage/posts/videos/1766826685281-0-s.mp4
	deleted:    storage/posts/videos/1766826815345-0-asasa.mp4
	deleted:    storage/posts/videos/1766826842822-0-aaa.mp4
	deleted:    "storage/posts/videos/1766827337926-0-Snow, mountains, and me\342\200\246 a story that never gets old!  #backstage #stylish #snow #style#streetstyle.mp4"
	deleted:    "storage/posts/videos/1766828100639-0-\330\263\330\263\330\263\330\263.mp4"
	deleted:    storage/posts/videos/1766828130001-0-aaa.mp4
	deleted:    storage/posts/videos/1766828157845-0-ssss.mp4
	deleted:    storage/posts/videos/1766828203643-0-aaaa.mp4
	deleted:    "storage/posts/videos/1766828345460-0-You deserve to be happy, and you can\342\200\231t stay where your heart doesn\342\200\231t belong  #\330\252\331\210\331\204\330\257\331\205_\331\205\330\250\330\247\330\261\332\251 #\330\242\330\250\333\214 #\330\247\331\207\331\210\330\247\330\262 #\330\252\331\210\331\204\330\257 #\330\250\331\204\330\247\332\257\330\261 @gallery.nilai.mp4"
	deleted:    storage/posts/videos/1766828424672-0-1111.mp4
	deleted:    storage/posts/videos/1766828464781-0-sss.mp4
	deleted:    storage/posts/videos/1766828486889-0-aaaa.mp4
	deleted:    storage/posts/videos/1766828514279-0-sss.mp4
	deleted:    storage/posts/videos/1766828727356-0-ddd.mp4
	deleted:    "storage/posts/videos/1766828816020-0-Jewlery project  Brand- @houseofme_official  Dop- @_alishariatt  Videographer- @peyman_bozorgomid  Assistant- @amir.kh.k  Model- @ana.elitee  #jewleryphotography #fashionreels #\330\261\333\214\331\204.mp4"
	deleted:    "storage/posts/videos/1766828848513-0-Some of my favorite shots Models- @saharjalilii @setayesh.ghalenoeii @parmisaadat @paaarand @asalllbayat @bitakhaajoii  #photographer #\330\271\332\251\330\247\330\263\333\214_\331\201\330\264\331\206 #photosoftheday.mp4"
	deleted:    "storage/posts/videos/1766831745457-0-\330\263\330\263\330\263.mp4"
	deleted:    "storage/posts/videos/1766831795030-0-\330\264\330\264\330\264\330\264.mp4"
	deleted:    "storage/posts/videos/1766833279276-0-\330\247\330\262 \332\206\330\264\330\247\331\205 \331\207\331\204\330\252 \330\257\330\247\330\257\331\205\342\200\214 \331\210\331\204\333\214 .....mp4"
	deleted:    "storage/posts/videos/1766835292259-0-\330\263\333\214\330\263.mp4"
	deleted:    storage/posts/videos/1766835327424-0-a.mp4
	deleted:    storage/posts/videos/1766835787091-0-s.mp4
	deleted:    storage/posts/videos/1767012113143-0-aaa.mp4
	deleted:    "storage/posts/videos/1767012137018-0-Makeup by-\360\237\221\207\360\237\217\275\360\237\215\267 @pegah.mua  @kiavash_royalvideo.mp4"
	deleted:    storage/posts/videos/1767012672738-0-dddd.mp4
	deleted:    storage/posts/videos/1767012722043-0-Instagram.mp4
	deleted:    "storage/posts/videos/1768740975998-0-Faouzia\343\200\212Desert Rose\343\200\213.mp4"
	deleted:    storage/posts/videos/1768741493380-0-a.mp4
	deleted:    "storage/posts/videos/1771318409261-0-\330\266\330\265\330\266\330\265\330\266\330\265\330\266.mp4"
	deleted:    "storage/posts/videos/1771319189820-0-\330\263\330\263\330\263\330\263.mp4"
	deleted:    storage/posts/videos/1771937200099-0-WhatsApp Video 2025-05-17 at 11.50.09.mp4
	deleted:    storage/posts/videos/1772005435124-0-qqqq.mp4
	deleted:    storage/posts/videos/1772005611958-0-aaaaa.mp4
	deleted:    storage/posts/videos/1772006456443-0-qqqqww.mp4
	deleted:    storage/posts/videos/1772006543741-0-1111.mp4
	deleted:    storage/posts/videos/1772006606627-0-wewewe.mp4
	deleted:    storage/posts/videos/1772006663579-0-wwww.mp4
	deleted:    storage/posts/videos/1772006685382-0-333.mp4
	deleted:    storage/posts/videos/1772006740696-0-www.mp4
	deleted:    storage/posts/videos/1772006786181-0-4444.mp4
	deleted:    storage/posts/videos/1772009213487-0-aaaa.mp4
	deleted:    storage/posts/videos/1772009260843-0-sss.mp4
	deleted:    "storage/posts/videos/1772013946491-0-\330\250\330\250\330\250\330\250\330\250.mp4"
	deleted:    "storage/posts/videos/1772089789739-0-\330\266\330\266\330\266\330\266.mp4"
	deleted:    storage/posts/videos/1772090631353-0-qqqq.mp4
	deleted:    "storage/posts/videos/1772092053138-0-\330\265\330\265\330\265.mp4"
	deleted:    storage/posts/videos/1772101142214-0-2222.mp4
	deleted:    "storage/posts/videos/1772101261385-0-\330\266\330\266\330\266\330\266.mp4"
	deleted:    storage/posts/videos/1772101312006-0-Instagram.mp4
	deleted:    "storage/posts/videos/1772101434744-0-\330\263\333\214\330\263\333\214\330\263\333\214.mp4"
	deleted:    "storage/posts/videos/1772203614700-0-\330\263\330\247\331\205\330\250\330\261\331\207 \330\250\331\204\331\210\331\206\330\257 \330\250\330\261\330\247\333\214 \331\201\330\247\330\267\331\205\331\207 \330\271\330\262\333\214\330\262\331\205\360\237\222\225.mp4"
	deleted:    "storage/posts/videos/1772203641829-0-\330\257\332\251\331\204\330\261\331\207 \331\210 \330\261\331\206\332\257 \331\210 \332\251\331\210\330\252\330\247\331\207\333\214 \330\250\330\261\330\247\333\214 \330\263\331\210\330\257\330\247 \331\202\330\264\331\206\332\257\331\205\360\237\222\225.mp4"
	deleted:    "storage/posts/videos/1772203698315-0-\330\247\333\214\331\206 \332\251\330\247\330\261 \330\262\333\214\330\250\330\247\331\205\331\210\331\206 \330\250\330\261\330\247\333\214 \330\255\330\250\333\214\330\250\331\207 \330\256\330\247\331\206\331\205 \330\271\330\262\333\214\330\262\360\237\222\225.mp4"
	deleted:    "storage/posts/videos/1772205300232-0-\330\264\330\264\330\264\330\264.mp4"
	deleted:    "storage/posts/videos/1772205333900-0-\330\265\330\265\330\265\330\265\330\265.mp4"
	deleted:    "storage/posts/videos/1772207461030-0-\330\265\330\265\330\265.mp4"
	deleted:    "storage/posts/videos/1772207616124-0-\330\264\330\264\330\264.mp4"
	deleted:    "storage/posts/videos/1772207684446-0-\330\253\330\253\330\253\330\253.mp4"
	deleted:    "storage/posts/videos/1772208440984-0-\331\201\331\201\331\201.mp4"
	deleted:    "storage/posts/videos/1772208506469-0-\330\253\330\253\330\253\330\253.mp4"
	deleted:    "storage/posts/videos/1772208627195-0-\330\264\330\264\330\264\330\264.mp4"
	deleted:    "storage/posts/videos/1772208646258-0-\330\250\330\263\333\214\330\263.mp4"
	deleted:    storage/posts/videos/1772208704438-0-111.mp4
	deleted:    "storage/posts/videos/1772211057722-0-\330\266\330\266\330\266.mp4"
	deleted:    "storage/posts/videos/1772211118907-0-\330\265\330\265\330\265\330\265.mp4"
	deleted:    "storage/posts/videos/1772211184550-0-\330\253\330\253\330\253.mp4"
	deleted:    "storage/posts/videos/1772211618341-0-\330\265\330\265\330\265\330\265.mp4"
	deleted:    storage/posts/videos/1772211740270-0-4444.mp4
This commit is contained in:
Amirreza
2026-07-05 15:59:26 +03:30
parent 06f6260df3
commit b3bb0d0ff3
306 changed files with 23083 additions and 23100 deletions

View File

@@ -1,50 +1,50 @@
const AcademyCategoryModel = require('../../models/AcademyCategoryModel');
// دریافت همه دسته‌بندی‌های اکادمی
exports.getAll = async (req, res) => {
try {
const categories = await AcademyCategoryModel.find({}).sort({ createdAt: -1 });
res.json({ success: true, data: categories });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// ایجاد دسته‌بندی جدید
exports.create = async (req, res) => {
try {
const { title } = req.body;
if (!title) return res.status(400).json({ success: false, message: "عنوان الزامی است" });
const category = await AcademyCategoryModel.create({ title });
res.status(201).json({ success: true, message: "دسته‌بندی ایجاد شد", data: category });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// ویرایش دسته‌بندی
exports.update = async (req, res) => {
try {
const { id } = req.params;
const { title, status } = req.body;
const category = await AcademyCategoryModel.findByIdAndUpdate(id, { title, status }, { new: true });
if (!category) return res.status(404).json({ success: false, message: "دسته‌بندی یافت نشد" });
res.json({ success: true, message: "دسته‌بندی ویرایش شد", data: category });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// حذف دسته‌بندی
exports.remove = async (req, res) => {
try {
const { id } = req.params;
await AcademyCategoryModel.findByIdAndDelete(id);
res.json({ success: true, message: "دسته‌بندی حذف شد" });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
const AcademyCategoryModel = require('../../models/AcademyCategoryModel');
// دریافت همه دسته‌بندی‌های اکادمی
exports.getAll = async (req, res) => {
try {
const categories = await AcademyCategoryModel.find({}).sort({ createdAt: -1 });
res.json({ success: true, data: categories });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// ایجاد دسته‌بندی جدید
exports.create = async (req, res) => {
try {
const { title } = req.body;
if (!title) return res.status(400).json({ success: false, message: "عنوان الزامی است" });
const category = await AcademyCategoryModel.create({ title });
res.status(201).json({ success: true, message: "دسته‌بندی ایجاد شد", data: category });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// ویرایش دسته‌بندی
exports.update = async (req, res) => {
try {
const { id } = req.params;
const { title, status } = req.body;
const category = await AcademyCategoryModel.findByIdAndUpdate(id, { title, status }, { new: true });
if (!category) return res.status(404).json({ success: false, message: "دسته‌بندی یافت نشد" });
res.json({ success: true, message: "دسته‌بندی ویرایش شد", data: category });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};
// حذف دسته‌بندی
exports.remove = async (req, res) => {
try {
const { id } = req.params;
await AcademyCategoryModel.findByIdAndDelete(id);
res.json({ success: true, message: "دسته‌بندی حذف شد" });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
};

View File

@@ -1,350 +1,350 @@
/* eslint-disable eqeqeq */
/* eslint-disable camelcase */
const { ProvinceModel, CityModel } = require('../../../models/StateCity')
const AdvertisingModel = require('../../../models/AdvertisingModel')
// const AdvertisingLikeModel = require('../../../models/AdvertisingLikeModel')
// const AdvertisingComment = require('../../../models/AdvertisingCommentModel')
const AdvertisingProfileModel = require('../../../models/AdvertisingProfile')
const NotificationModel = require('../../../models/NotificationModel')
const AdvertisingCategoryModel = require('../../../models/AdvertisingCategoryModel')
const getAdvertisings = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10, province, city, category, search,
startDate,
endDate,
status
} = req.query
const filter = {
}
if (province) {
const provinceFind = await ProvinceModel.findOne({ id: province }, { _id: 0 })
filter.province = provinceFind
}
if (city) {
const cityFind = await CityModel.findOne({ id: city })
filter.city = cityFind
}
if (category) {
filter.category = category
}
if (search) {
filter.$or = [
{ title: { $regex: search, $options: 'i' } },
{ category: { $regex: search, $options: 'i' } }
]
}
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: [
{ path: 'creator_id', select: 'user_name first_name last_name' }
]
}
const advertisings = await AdvertisingModel.paginate(filter, options)
const newAds = advertisings.docs.map(ad => {
return {
// فیلدهای مشخص‌شده از ad._doc
_id: ad._doc._id,
creator_id: ad._doc.creator_id,
category: ad._doc.category,
title: ad._doc.title,
province: ad._doc.province,
city: ad._doc.city,
status: ad._doc.status,
neighbourhood: ad._doc.neighbourhood
}
})
res.status(200).json({
advertisings: newAds,
totalPages: advertisings.totalPages,
totalItems: advertisings.totalDocs
})
} catch (error) {
next(error)
}
}
const getSingleAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const advertisingId = req.query.advertisingId
const advertising = await AdvertisingModel.findById(advertisingId)
.populate('creator_id', '_id user_name first_name last_name')
if (!advertising) {
return res.status(404).json({ message: 'ویترین مورد نظر یافت نشد' })
}
const creator = await AdvertisingProfileModel.findOne({ user: advertising.creator_id._id })
// اضافه کردن تعداد لایک‌ها، تعداد کامنت‌ها و وضعیت لایک به تبلیغ
const advertisingData = {
...advertising._doc
}
res.status(200).json({
advertising: advertisingData,
creator
})
} catch (error) {
next(error)
}
}
const acceptAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { advertisingId } = req.body
// پیدا کردن تبلیغ
const advertising = await AdvertisingModel.findById(advertisingId)
if (!advertising) {
return res.status(404).json({ message: 'تبلیغ مورد نظر یافت نشد' })
}
// تغییر وضعیت به accepted و ذخیره زمان قبول شدن
advertising.status = 'accepted'
advertising.acceptedAt = new Date()
await advertising.save()
const notification = new NotificationModel({
user_id: advertising?.creator_id,
project_post_id: advertising?._id,
type: 'vitrine',
title: 'تایید ویترین',
description: `ویترین شما با عنوان: ${advertising?.title} تایید و منتشر شد `
})
await notification.save()
res.status(200).json({ message: 'تبلیغ اکسپت شد و پس از 15 روز منقضی خواهد شد' })
} catch (error) {
next(error)
}
}
const rejectAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { advertisingId, rejectReason } = req.body
// پیدا کردن تبلیغ
const advertising = await AdvertisingModel.findById(advertisingId)
if (!advertising) {
return res.status(404).json({ message: 'تبلیغ مورد نظر یافت نشد' })
}
// تغییر وضعیت به rejected و ذخیره دلیل رد شدن
advertising.status = 'rejected'
advertising.reject_reason = rejectReason
await advertising.save()
const notification = new NotificationModel({
user_id: advertising?.creator_id,
project_post_id: advertising?._id,
type: 'vitrine',
title: 'رد ویترین',
description: `ویترین شما با عنوان: ${advertising?.title} رد شد، برای دیدن علت رد، لمس کنید `
})
await notification.save()
res.status(200).json({ message: 'تبلیغ رد شد', advertising })
} catch (error) {
next(error)
}
}
const deleteAdvertisingCategory = async (req, res, next) => {
try {
const { id } = req.params
// چک کنه که ID معتبره
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return res.status(400).json({
success: false,
message: 'شناسه معتبر نمی‌باشد'
})
}
// پیدا کنه دسته‌بندی رو
const category = await AdvertisingCategoryModel.findById(id)
if (!category) {
return res.status(404).json({
success: false,
message: 'دسته‌بندی مورد نظر یافت نشد'
})
}
// حذف کنه
await category.deleteOne()
return res.status(200).json({
success: true,
message: 'دسته‌بندی تبلیغات با موفقیت حذف شد',
data: { id }
})
} catch (error) {
next(error)
}
}
const createAdvertisingCategory = async (req, res, next) => {
try {
const { title, status } = req.body
// اعتبارسنجی ورودی‌ها
if (!title || title.trim().length < 1) {
return res.status(400).json({
success: false,
message: 'عنوان دسته‌بندی الزامی است'
})
}
if (title.length > 255) {
return res.status(400).json({
success: false,
message: 'عنوان دسته‌بندی نباید بیشتر از ۲۵۵ کاراکتر باشد'
})
}
// بررسی اینکه دسته‌بندی تکراری نباشد
const exists = await AdvertisingCategoryModel.findOne({ title: title.trim() })
if (exists) {
return res.status(409).json({
success: false,
message: 'این دسته‌بندی از قبل وجود دارد'
})
}
// ایجاد دسته‌بندی جدید
const newCategory = await AdvertisingCategoryModel.create({
title: title.trim(),
status: status ?? true
})
return res.status(201).json({
success: true,
message: 'دسته‌بندی تبلیغات با موفقیت ایجاد شد',
data: newCategory
})
} catch (error) {
next(error) // میره به errorHandler مرکزی
}
}
const getAdvertisingCategories = async (req, res, next) => {
try {
const page = Math.max(parseInt(req.query.page || '1', 10), 1);
const limit = Math.max(Math.min(parseInt(req.query.limit || '20', 10), 100), 1);
const { status, q, sort } = req.query;
const query = {};
if (typeof status !== 'undefined') {
// accept 'true'/'false' or boolean
if (status === 'true' || status === 'false') query.status = status === 'true';
else if (status === '1' || status === '0') query.status = status === '1';
}
if (q) {
query.title = { $regex: q.trim(), $options: 'i' };
}
const options = {
page,
limit,
sort: sort || '-createdAt',
lean: true,
};
// اگر mongoose-paginate-v2 نصب و فعال است:
if (typeof AdvertisingCategoryModel.paginate === 'function') {
const result = await AdvertisingCategoryModel.paginate(query, options);
return res.status(200).json({
success: true,
totalDocs: result.totalDocs,
totalPages: result.totalPages,
page: result.page,
limit: result.limit,
docs: result.docs,
});
}
// fallback بدون paginate
const docs = await AdvertisingCategoryModel.find(query)
.sort(options.sort)
.skip((page - 1) * limit)
.limit(limit)
.lean();
const totalDocs = await AdvertisingCategoryModel.countDocuments(query);
const totalPages = Math.ceil(totalDocs / limit);
return res.status(200).json({
success: true,
totalDocs,
totalPages,
page,
limit,
docs,
});
} catch (error) {
next(error);
}
};
/**
* GET /advertising/advertising-categories/:id
*/
const getAdvertisingCategoryById = async (req, res, next) => {
try {
const { id } = req.params;
if (!id || !id.match(/^[0-9a-fA-F]{24}$/)) {
return res.status(400).json({ success: false, message: 'شناسه معتبر نیست' });
}
const category = await AdvertisingCategoryModel.findById(id).lean();
if (!category) {
return res.status(404).json({ success: false, message: 'دسته‌بندی یافت نشد' });
}
return res.status(200).json({ success: true, data: category });
} catch (error) {
next(error);
}
};
module.exports = {
getSingleAdvertising,
getAdvertisings,
deleteAdvertisingCategory,
createAdvertisingCategory,
getAdvertisingCategories,
getAdvertisingCategoryById,
acceptAdvertising,
rejectAdvertising
}
/* eslint-disable eqeqeq */
/* eslint-disable camelcase */
const { ProvinceModel, CityModel } = require('../../../models/StateCity')
const AdvertisingModel = require('../../../models/AdvertisingModel')
// const AdvertisingLikeModel = require('../../../models/AdvertisingLikeModel')
// const AdvertisingComment = require('../../../models/AdvertisingCommentModel')
const AdvertisingProfileModel = require('../../../models/AdvertisingProfile')
const NotificationModel = require('../../../models/NotificationModel')
const AdvertisingCategoryModel = require('../../../models/AdvertisingCategoryModel')
const getAdvertisings = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10, province, city, category, search,
startDate,
endDate,
status
} = req.query
const filter = {
}
if (province) {
const provinceFind = await ProvinceModel.findOne({ id: province }, { _id: 0 })
filter.province = provinceFind
}
if (city) {
const cityFind = await CityModel.findOne({ id: city })
filter.city = cityFind
}
if (category) {
filter.category = category
}
if (search) {
filter.$or = [
{ title: { $regex: search, $options: 'i' } },
{ category: { $regex: search, $options: 'i' } }
]
}
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: [
{ path: 'creator_id', select: 'user_name first_name last_name' }
]
}
const advertisings = await AdvertisingModel.paginate(filter, options)
const newAds = advertisings.docs.map(ad => {
return {
// فیلدهای مشخص‌شده از ad._doc
_id: ad._doc._id,
creator_id: ad._doc.creator_id,
category: ad._doc.category,
title: ad._doc.title,
province: ad._doc.province,
city: ad._doc.city,
status: ad._doc.status,
neighbourhood: ad._doc.neighbourhood
}
})
res.status(200).json({
advertisings: newAds,
totalPages: advertisings.totalPages,
totalItems: advertisings.totalDocs
})
} catch (error) {
next(error)
}
}
const getSingleAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const advertisingId = req.query.advertisingId
const advertising = await AdvertisingModel.findById(advertisingId)
.populate('creator_id', '_id user_name first_name last_name')
if (!advertising) {
return res.status(404).json({ message: 'ویترین مورد نظر یافت نشد' })
}
const creator = await AdvertisingProfileModel.findOne({ user: advertising.creator_id._id })
// اضافه کردن تعداد لایک‌ها، تعداد کامنت‌ها و وضعیت لایک به تبلیغ
const advertisingData = {
...advertising._doc
}
res.status(200).json({
advertising: advertisingData,
creator
})
} catch (error) {
next(error)
}
}
const acceptAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { advertisingId } = req.body
// پیدا کردن تبلیغ
const advertising = await AdvertisingModel.findById(advertisingId)
if (!advertising) {
return res.status(404).json({ message: 'تبلیغ مورد نظر یافت نشد' })
}
// تغییر وضعیت به accepted و ذخیره زمان قبول شدن
advertising.status = 'accepted'
advertising.acceptedAt = new Date()
await advertising.save()
const notification = new NotificationModel({
user_id: advertising?.creator_id,
project_post_id: advertising?._id,
type: 'vitrine',
title: 'تایید ویترین',
description: `ویترین شما با عنوان: ${advertising?.title} تایید و منتشر شد `
})
await notification.save()
res.status(200).json({ message: 'تبلیغ اکسپت شد و پس از 15 روز منقضی خواهد شد' })
} catch (error) {
next(error)
}
}
const rejectAdvertising = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { advertisingId, rejectReason } = req.body
// پیدا کردن تبلیغ
const advertising = await AdvertisingModel.findById(advertisingId)
if (!advertising) {
return res.status(404).json({ message: 'تبلیغ مورد نظر یافت نشد' })
}
// تغییر وضعیت به rejected و ذخیره دلیل رد شدن
advertising.status = 'rejected'
advertising.reject_reason = rejectReason
await advertising.save()
const notification = new NotificationModel({
user_id: advertising?.creator_id,
project_post_id: advertising?._id,
type: 'vitrine',
title: 'رد ویترین',
description: `ویترین شما با عنوان: ${advertising?.title} رد شد، برای دیدن علت رد، لمس کنید `
})
await notification.save()
res.status(200).json({ message: 'تبلیغ رد شد', advertising })
} catch (error) {
next(error)
}
}
const deleteAdvertisingCategory = async (req, res, next) => {
try {
const { id } = req.params
// چک کنه که ID معتبره
if (!id.match(/^[0-9a-fA-F]{24}$/)) {
return res.status(400).json({
success: false,
message: 'شناسه معتبر نمی‌باشد'
})
}
// پیدا کنه دسته‌بندی رو
const category = await AdvertisingCategoryModel.findById(id)
if (!category) {
return res.status(404).json({
success: false,
message: 'دسته‌بندی مورد نظر یافت نشد'
})
}
// حذف کنه
await category.deleteOne()
return res.status(200).json({
success: true,
message: 'دسته‌بندی تبلیغات با موفقیت حذف شد',
data: { id }
})
} catch (error) {
next(error)
}
}
const createAdvertisingCategory = async (req, res, next) => {
try {
const { title, status } = req.body
// اعتبارسنجی ورودی‌ها
if (!title || title.trim().length < 1) {
return res.status(400).json({
success: false,
message: 'عنوان دسته‌بندی الزامی است'
})
}
if (title.length > 255) {
return res.status(400).json({
success: false,
message: 'عنوان دسته‌بندی نباید بیشتر از ۲۵۵ کاراکتر باشد'
})
}
// بررسی اینکه دسته‌بندی تکراری نباشد
const exists = await AdvertisingCategoryModel.findOne({ title: title.trim() })
if (exists) {
return res.status(409).json({
success: false,
message: 'این دسته‌بندی از قبل وجود دارد'
})
}
// ایجاد دسته‌بندی جدید
const newCategory = await AdvertisingCategoryModel.create({
title: title.trim(),
status: status ?? true
})
return res.status(201).json({
success: true,
message: 'دسته‌بندی تبلیغات با موفقیت ایجاد شد',
data: newCategory
})
} catch (error) {
next(error) // میره به errorHandler مرکزی
}
}
const getAdvertisingCategories = async (req, res, next) => {
try {
const page = Math.max(parseInt(req.query.page || '1', 10), 1);
const limit = Math.max(Math.min(parseInt(req.query.limit || '20', 10), 100), 1);
const { status, q, sort } = req.query;
const query = {};
if (typeof status !== 'undefined') {
// accept 'true'/'false' or boolean
if (status === 'true' || status === 'false') query.status = status === 'true';
else if (status === '1' || status === '0') query.status = status === '1';
}
if (q) {
query.title = { $regex: q.trim(), $options: 'i' };
}
const options = {
page,
limit,
sort: sort || '-createdAt',
lean: true,
};
// اگر mongoose-paginate-v2 نصب و فعال است:
if (typeof AdvertisingCategoryModel.paginate === 'function') {
const result = await AdvertisingCategoryModel.paginate(query, options);
return res.status(200).json({
success: true,
totalDocs: result.totalDocs,
totalPages: result.totalPages,
page: result.page,
limit: result.limit,
docs: result.docs,
});
}
// fallback بدون paginate
const docs = await AdvertisingCategoryModel.find(query)
.sort(options.sort)
.skip((page - 1) * limit)
.limit(limit)
.lean();
const totalDocs = await AdvertisingCategoryModel.countDocuments(query);
const totalPages = Math.ceil(totalDocs / limit);
return res.status(200).json({
success: true,
totalDocs,
totalPages,
page,
limit,
docs,
});
} catch (error) {
next(error);
}
};
/**
* GET /advertising/advertising-categories/:id
*/
const getAdvertisingCategoryById = async (req, res, next) => {
try {
const { id } = req.params;
if (!id || !id.match(/^[0-9a-fA-F]{24}$/)) {
return res.status(400).json({ success: false, message: 'شناسه معتبر نیست' });
}
const category = await AdvertisingCategoryModel.findById(id).lean();
if (!category) {
return res.status(404).json({ success: false, message: 'دسته‌بندی یافت نشد' });
}
return res.status(200).json({ success: true, data: category });
} catch (error) {
next(error);
}
};
module.exports = {
getSingleAdvertising,
getAdvertisings,
deleteAdvertisingCategory,
createAdvertisingCategory,
getAdvertisingCategories,
getAdvertisingCategoryById,
acceptAdvertising,
rejectAdvertising
}

View File

@@ -1,195 +1,195 @@
/* eslint-disable camelcase */
const AdvertisingComment = require('../../../models/AdvertisingCommentModel')
const jMoment = require('moment-jalaali')
const mongoose = require('mongoose')
const AdvertisingModel = require('../../../models/AdvertisingModel')
const NotificationModel = require('../../../models/NotificationModel')
// دریافت کامنت‌ها
const getAdvertisingComments = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {}
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: [
{ path: 'userId', select: 'user_name first_name last_name profile_image' },
{ path: 'advertisingId', select: 'title', populate: { path: 'creator_id', select: 'user_name first_name last_name' } }
// اضافه کردن اطلاعات سازنده
]
}
const comments = await AdvertisingComment.paginate(filter, options)
const commentList = comments.docs.map(comment => ({
_id: comment._id,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
text: comment.text,
advertising: comment.advertisingId ? comment.advertisingId.title : null,
user: comment.userId ? {
_id: comment.userId._id,
user_name: comment.userId.user_name,
first_name: comment.userId.first_name,
last_name: comment.userId.last_name,
profile_image: comment.userId.profile_image
} : null,
creator: (comment.advertisingId && comment.advertisingId.creator_id) ? {
_id: comment.advertisingId.creator_id._id,
user_name: comment.advertisingId.creator_id.user_name,
first_name: comment.advertisingId.creator_id.first_name,
last_name: comment.advertisingId.creator_id.last_name
} : null
}));
res.status(200).json({
comments: commentList,
totalPages: comments.totalPages,
totalItems: comments.totalDocs
})
} catch (error) {
next(error)
}
}
// دریافت جزئیات یک کامنت
const getAdvertisingCommentDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const comment_id = req.query.comment_id
if (!mongoose.Types.ObjectId.isValid(comment_id)) {
return res.status(400).json({ message: 'شناسه کامنت معتبر نیست' })
}
const comment = await AdvertisingComment.findById(comment_id)
.populate('userId', 'user_name first_name last_name profile_image')
.populate({
path: 'advertisingId',
select: 'title creator_id',
populate: {
path: 'creator_id',
select: 'user_name first_name last_name'
}
})
if (!comment) {
return res.status(404).json({ message: 'کامنت مورد نظر یافت نشد' })
}
const response = {
_id: comment._id,
text: comment.text,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
advertising: comment.advertisingId ? comment.advertisingId.title : null,
creator: {
_id: comment?.advertisingId?.creator_id._id,
user_name: comment?.advertisingId?.creator_id.user_name,
first_name: comment?.advertisingId?.creator_id.first_name,
last_name: comment?.advertisingId?.creator_id.last_name
},
user: {
_id: comment.userId._id,
user_name: comment.userId.user_name,
first_name: comment.userId.first_name,
last_name: comment.userId.last_name,
profile_image: comment.userId.profile_image
}
}
res.status(200).json({ comment: response })
} catch (error) {
next(error)
}
}
// تایید یک کامنت
const acceptAdvertisingComment = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, status, text } = req.body
if (!id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const comment = await AdvertisingComment.findById(id)
// افزایش تعداد کامنت‌های تبلیغ
await AdvertisingModel.findByIdAndUpdate(comment?.advertisingId, { $inc: { commentsCount: 1 } })
if (!comment) {
return res.status(404).json({
error: true,
message: 'کامنت مورد نظر یافت نشد'
})
}
if (text) {
comment.text = text
}
comment.status = status
await comment.save()
if (status === 'accepted') {
const notification = new NotificationModel({
user_id: comment?.userId,
project_post_id: comment?.advertisingId,
type: 'vitrine-comment',
title: 'انتشار نظر',
description: 'نظر شما منتشر شد.'
})
await notification.save()
} else {
const notification = new NotificationModel({
user_id: comment?.userId,
project_post_id: comment?.advertisingId,
type: 'vitrine-comment',
title: 'رد نظر',
description: 'نظر شما رد شد.'
})
await notification.save()
}
res.status(201).json({ message: 'کامنت با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getAdvertisingComments,
getAdvertisingCommentDetail,
acceptAdvertisingComment
}
/* eslint-disable camelcase */
const AdvertisingComment = require('../../../models/AdvertisingCommentModel')
const jMoment = require('moment-jalaali')
const mongoose = require('mongoose')
const AdvertisingModel = require('../../../models/AdvertisingModel')
const NotificationModel = require('../../../models/NotificationModel')
// دریافت کامنت‌ها
const getAdvertisingComments = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {}
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: [
{ path: 'userId', select: 'user_name first_name last_name profile_image' },
{ path: 'advertisingId', select: 'title', populate: { path: 'creator_id', select: 'user_name first_name last_name' } }
// اضافه کردن اطلاعات سازنده
]
}
const comments = await AdvertisingComment.paginate(filter, options)
const commentList = comments.docs.map(comment => ({
_id: comment._id,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
text: comment.text,
advertising: comment.advertisingId ? comment.advertisingId.title : null,
user: comment.userId ? {
_id: comment.userId._id,
user_name: comment.userId.user_name,
first_name: comment.userId.first_name,
last_name: comment.userId.last_name,
profile_image: comment.userId.profile_image
} : null,
creator: (comment.advertisingId && comment.advertisingId.creator_id) ? {
_id: comment.advertisingId.creator_id._id,
user_name: comment.advertisingId.creator_id.user_name,
first_name: comment.advertisingId.creator_id.first_name,
last_name: comment.advertisingId.creator_id.last_name
} : null
}));
res.status(200).json({
comments: commentList,
totalPages: comments.totalPages,
totalItems: comments.totalDocs
})
} catch (error) {
next(error)
}
}
// دریافت جزئیات یک کامنت
const getAdvertisingCommentDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const comment_id = req.query.comment_id
if (!mongoose.Types.ObjectId.isValid(comment_id)) {
return res.status(400).json({ message: 'شناسه کامنت معتبر نیست' })
}
const comment = await AdvertisingComment.findById(comment_id)
.populate('userId', 'user_name first_name last_name profile_image')
.populate({
path: 'advertisingId',
select: 'title creator_id',
populate: {
path: 'creator_id',
select: 'user_name first_name last_name'
}
})
if (!comment) {
return res.status(404).json({ message: 'کامنت مورد نظر یافت نشد' })
}
const response = {
_id: comment._id,
text: comment.text,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
advertising: comment.advertisingId ? comment.advertisingId.title : null,
creator: {
_id: comment?.advertisingId?.creator_id._id,
user_name: comment?.advertisingId?.creator_id.user_name,
first_name: comment?.advertisingId?.creator_id.first_name,
last_name: comment?.advertisingId?.creator_id.last_name
},
user: {
_id: comment.userId._id,
user_name: comment.userId.user_name,
first_name: comment.userId.first_name,
last_name: comment.userId.last_name,
profile_image: comment.userId.profile_image
}
}
res.status(200).json({ comment: response })
} catch (error) {
next(error)
}
}
// تایید یک کامنت
const acceptAdvertisingComment = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, status, text } = req.body
if (!id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const comment = await AdvertisingComment.findById(id)
// افزایش تعداد کامنت‌های تبلیغ
await AdvertisingModel.findByIdAndUpdate(comment?.advertisingId, { $inc: { commentsCount: 1 } })
if (!comment) {
return res.status(404).json({
error: true,
message: 'کامنت مورد نظر یافت نشد'
})
}
if (text) {
comment.text = text
}
comment.status = status
await comment.save()
if (status === 'accepted') {
const notification = new NotificationModel({
user_id: comment?.userId,
project_post_id: comment?.advertisingId,
type: 'vitrine-comment',
title: 'انتشار نظر',
description: 'نظر شما منتشر شد.'
})
await notification.save()
} else {
const notification = new NotificationModel({
user_id: comment?.userId,
project_post_id: comment?.advertisingId,
type: 'vitrine-comment',
title: 'رد نظر',
description: 'نظر شما رد شد.'
})
await notification.save()
}
res.status(201).json({ message: 'کامنت با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getAdvertisingComments,
getAdvertisingCommentDetail,
acceptAdvertisingComment
}

View File

@@ -1,172 +1,172 @@
/* eslint-disable camelcase */
const CommentModel = require('../../../models/CommentModel')
const jMoment = require('moment-jalaali')
const { default: mongoose } = require('mongoose')
// دریافت لیست کامنت‌ها با پیجینیشن
const getComments = async (req, res, next) => {
try {
console.log("gg6");
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {} // فیلتر بر اساس وضعیت کامنت
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
console.log("gg8");
if (status) {
filter.status = status
}
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'creator', select: 'user_name first_name last_name profile_image ' },
{ path: 'user', select: 'user_name first_name last_name' },
{ path: 'project', select: 'title' }
]
}
const comments = await CommentModel.paginate(filter, options)
const commentList = comments.docs.map(comment => ({
_id: comment._id,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
comment_for: comment.comment_for,
project: comment.project ? comment.project.title : null,
creator: comment.creator ? {
_id: comment.creator._id,
user_name: comment.creator.user_name,
first_name: comment.creator.first_name,
last_name: comment.creator.last_name,
profile_image: comment.creator.profile_image
} : null,
user: comment.user ? {
_id: comment.user._id,
user_name: comment.user.user_name,
first_name: comment.user.first_name,
last_name: comment.user.last_name
} : null
}));
console.log("gg9");
res.status(200).json({
comments: commentList,
totalPages: comments.totalPages,
totalItems: comments.totalDocs
})
} catch (error) {
console.log("gg");
next(error)
}
}
// دریافت جزئیات یک کامنت
const getCommentDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const comment_id = req.query.comment_id
if (!mongoose.Types.ObjectId.isValid(comment_id)) {
return res.status(400).json({ message: 'شناسه کامنت معتبر نیست' })
}
const comment = await CommentModel.findById(comment_id)
.populate('creator', 'user_name first_name last_name profile_image ')
.populate('user', 'user_name first_name last_name')
.populate('project', 'title')
if (!comment) {
return res.status(404).json({ message: 'کامنت مورد نظر یافت نشد' })
}
const response = {
_id: comment._id,
comment: comment.comment,
rating: comment.rating,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
comment_for: comment.comment_for,
project: comment.project ? comment.project.title : null,
creator: {
_id: comment.creator._id,
user_name: comment.creator.user_name,
first_name: comment.creator.first_name,
last_name: comment.creator.last_name,
profile_image: comment.creator.profile_image
},
user: {
_id: comment.user._id,
user_name: comment.user.user_name,
first_name: comment.user.first_name,
last_name: comment.user.last_name
}
}
res.status(200).json({ comment: response })
} catch (error) {
next(error)
}
}
// تایید یک کامنت
const acceptComment = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, status, text } = req.body
if (!id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(404).json({
error: true,
message: 'کامنت مورد نظر یافت نشد'
})
}
if (text) {
comment.comment = text
}
comment.status = status
await comment.save()
res.status(201).json({ message: 'کامنت با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getComments,
getCommentDetail,
acceptComment
}
/* eslint-disable camelcase */
const CommentModel = require('../../../models/CommentModel')
const jMoment = require('moment-jalaali')
const { default: mongoose } = require('mongoose')
// دریافت لیست کامنت‌ها با پیجینیشن
const getComments = async (req, res, next) => {
try {
console.log("gg6");
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {} // فیلتر بر اساس وضعیت کامنت
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
console.log("gg8");
if (status) {
filter.status = status
}
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'creator', select: 'user_name first_name last_name profile_image ' },
{ path: 'user', select: 'user_name first_name last_name' },
{ path: 'project', select: 'title' }
]
}
const comments = await CommentModel.paginate(filter, options)
const commentList = comments.docs.map(comment => ({
_id: comment._id,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
comment_for: comment.comment_for,
project: comment.project ? comment.project.title : null,
creator: comment.creator ? {
_id: comment.creator._id,
user_name: comment.creator.user_name,
first_name: comment.creator.first_name,
last_name: comment.creator.last_name,
profile_image: comment.creator.profile_image
} : null,
user: comment.user ? {
_id: comment.user._id,
user_name: comment.user.user_name,
first_name: comment.user.first_name,
last_name: comment.user.last_name
} : null
}));
console.log("gg9");
res.status(200).json({
comments: commentList,
totalPages: comments.totalPages,
totalItems: comments.totalDocs
})
} catch (error) {
console.log("gg");
next(error)
}
}
// دریافت جزئیات یک کامنت
const getCommentDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const comment_id = req.query.comment_id
if (!mongoose.Types.ObjectId.isValid(comment_id)) {
return res.status(400).json({ message: 'شناسه کامنت معتبر نیست' })
}
const comment = await CommentModel.findById(comment_id)
.populate('creator', 'user_name first_name last_name profile_image ')
.populate('user', 'user_name first_name last_name')
.populate('project', 'title')
if (!comment) {
return res.status(404).json({ message: 'کامنت مورد نظر یافت نشد' })
}
const response = {
_id: comment._id,
comment: comment.comment,
rating: comment.rating,
createdAt: jMoment(comment.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: comment.status,
comment_for: comment.comment_for,
project: comment.project ? comment.project.title : null,
creator: {
_id: comment.creator._id,
user_name: comment.creator.user_name,
first_name: comment.creator.first_name,
last_name: comment.creator.last_name,
profile_image: comment.creator.profile_image
},
user: {
_id: comment.user._id,
user_name: comment.user.user_name,
first_name: comment.user.first_name,
last_name: comment.user.last_name
}
}
res.status(200).json({ comment: response })
} catch (error) {
next(error)
}
}
// تایید یک کامنت
const acceptComment = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, status, text } = req.body
if (!id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const comment = await CommentModel.findById(id)
if (!comment) {
return res.status(404).json({
error: true,
message: 'کامنت مورد نظر یافت نشد'
})
}
if (text) {
comment.comment = text
}
comment.status = status
await comment.save()
res.status(201).json({ message: 'کامنت با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getComments,
getCommentDetail,
acceptComment
}

View File

@@ -1,111 +1,111 @@
/* eslint-disable camelcase */
const ExpertiseModel = require('../../../models/ExpertiseModel')
const createExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { expertise } = req.body
if (!expertise
) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// بررسی وجود تخصص با این نام در پایگاه داده
const existingExpertise = await ExpertiseModel.findOne({ expertise })
if (existingExpertise) {
return res.status(400).json({ message: 'تخصص با این نام قبلاً ثبت شده است' })
}
// ایجاد یک نمونه جدید از مدل ExpertiseModel
const newExpertise = new ExpertiseModel({
expertise
})
// ذخیره تخصص جدید در پایگاه داده
await newExpertise.save()
res.json({ message: 'تخصص با موفقیت اضافه شد' })
} catch (error) {
next(error)
}
}
const createSubExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const expertiseId = req.query.id
const { name } = req.body
if (!expertiseId || !name) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن تخصص موردنظر از طریق آیدی
const expertise = await ExpertiseModel.findById(expertiseId)
if (!expertise) {
return res.status(404).json({ message: 'تخصص موردنظر یافت نشد' })
}
// اضافه کردن زیرتخصص جدید به آرایه sub_expertise تخصص موجود
expertise.sub_expertise.push({ name })
await expertise.save()
res.json({ message: 'زیرتخصص با موفقیت به تخصص اضافه شد' })
} catch (error) {
next(error)
}
}
const getExpertise = async (req, res, next) => {
try {
const expertises = await ExpertiseModel.find().select('expertise sub_expertise')
res.json({ expertises })
} catch (error) {
next(error)
}
}
// ویرایش تخصص
const editExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { expertise } = req.body
const expertiseId = req.params.id
if (!expertise || !expertiseId) {
return res.status(422).json({ message: 'اطلاعات ارسالی اشتباه است' })
}
const updatedExpertise = await ExpertiseModel.findByIdAndUpdate(
expertiseId,
{ expertise },
{ new: true }
)
if (!updatedExpertise) {
return res.status(404).json({ message: 'تخصص یافت نشد' })
}
res.json({ message: 'تخصص با موفقیت ویرایش شد' })
} catch (error) {
next(error)
}
}
module.exports = {
createExpertise,
createSubExpertise,
getExpertise,
editExpertise
}
/* eslint-disable camelcase */
const ExpertiseModel = require('../../../models/ExpertiseModel')
const createExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { expertise } = req.body
if (!expertise
) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// بررسی وجود تخصص با این نام در پایگاه داده
const existingExpertise = await ExpertiseModel.findOne({ expertise })
if (existingExpertise) {
return res.status(400).json({ message: 'تخصص با این نام قبلاً ثبت شده است' })
}
// ایجاد یک نمونه جدید از مدل ExpertiseModel
const newExpertise = new ExpertiseModel({
expertise
})
// ذخیره تخصص جدید در پایگاه داده
await newExpertise.save()
res.json({ message: 'تخصص با موفقیت اضافه شد' })
} catch (error) {
next(error)
}
}
const createSubExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const expertiseId = req.query.id
const { name } = req.body
if (!expertiseId || !name) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن تخصص موردنظر از طریق آیدی
const expertise = await ExpertiseModel.findById(expertiseId)
if (!expertise) {
return res.status(404).json({ message: 'تخصص موردنظر یافت نشد' })
}
// اضافه کردن زیرتخصص جدید به آرایه sub_expertise تخصص موجود
expertise.sub_expertise.push({ name })
await expertise.save()
res.json({ message: 'زیرتخصص با موفقیت به تخصص اضافه شد' })
} catch (error) {
next(error)
}
}
const getExpertise = async (req, res, next) => {
try {
const expertises = await ExpertiseModel.find().select('expertise sub_expertise')
res.json({ expertises })
} catch (error) {
next(error)
}
}
// ویرایش تخصص
const editExpertise = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { expertise } = req.body
const expertiseId = req.params.id
if (!expertise || !expertiseId) {
return res.status(422).json({ message: 'اطلاعات ارسالی اشتباه است' })
}
const updatedExpertise = await ExpertiseModel.findByIdAndUpdate(
expertiseId,
{ expertise },
{ new: true }
)
if (!updatedExpertise) {
return res.status(404).json({ message: 'تخصص یافت نشد' })
}
res.json({ message: 'تخصص با موفقیت ویرایش شد' })
} catch (error) {
next(error)
}
}
module.exports = {
createExpertise,
createSubExpertise,
getExpertise,
editExpertise
}

View File

@@ -1,108 +1,108 @@
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const PaymentModel = require('../../../models/PaymentModel')
const jMoment = require('moment-jalaali')
const getFinancial = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{
path: 'user_id',
select: '_id user_name first_name mobile last_name '
},
{
path: 'project_id',
select: '_id title project_type'
}
]
}
const financial = await PaymentModel.paginate(
filter, // فیلتر
options // گزینه‌های پیجینیشن
)
const financialList = financial?.docs.map(financia => {
const jDate = jMoment(financia.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...financia._doc,
createdAt: jDate
}
})
res.json({
financials: financialList,
totalPages: financial.totalPages, // ارسال تعداد کل صفحات
totalItems: financial.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
console.error('Error occurred:', error)
res.status(500).json({ error: 'Internal server error' })
}
}
const getFinancialDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const financial_id = req.query.financial_id
if (!mongoose.Types.ObjectId.isValid(financial_id)) {
return res.status(400).json({ message: 'شناسه تراکنش معتبر نیست' })
}
const financial = await PaymentModel.findById(financial_id).populate([
{
path: 'user_id',
select: '_id user_name first_name mobile last_name shaba'
},
{
path: 'project_id',
select: '_id title project_type',
populate: {
path: 'selected_user',
select: '_id user_name first_name mobile last_name shaba'
}
}
])
if (!financial) {
return res.status(404).json({ message: 'تراکنش مورد نظر یافت نشد' })
}
const newfinancial = {
...financial._doc,
createdAt: jMoment(financial.createdAt).format('jYYYY-jMM-jDD HH:mm')
}
return res.status(200).json({ financial: newfinancial })
} catch (error) {
console.error('Error occurred:', error)
res.status(500).json({ error: 'Internal server error' })
}
}
module.exports = { getFinancial, getFinancialDetail }
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const PaymentModel = require('../../../models/PaymentModel')
const jMoment = require('moment-jalaali')
const getFinancial = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{
path: 'user_id',
select: '_id user_name first_name mobile last_name '
},
{
path: 'project_id',
select: '_id title project_type'
}
]
}
const financial = await PaymentModel.paginate(
filter, // فیلتر
options // گزینه‌های پیجینیشن
)
const financialList = financial?.docs.map(financia => {
const jDate = jMoment(financia.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...financia._doc,
createdAt: jDate
}
})
res.json({
financials: financialList,
totalPages: financial.totalPages, // ارسال تعداد کل صفحات
totalItems: financial.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
console.error('Error occurred:', error)
res.status(500).json({ error: 'Internal server error' })
}
}
const getFinancialDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const financial_id = req.query.financial_id
if (!mongoose.Types.ObjectId.isValid(financial_id)) {
return res.status(400).json({ message: 'شناسه تراکنش معتبر نیست' })
}
const financial = await PaymentModel.findById(financial_id).populate([
{
path: 'user_id',
select: '_id user_name first_name mobile last_name shaba'
},
{
path: 'project_id',
select: '_id title project_type',
populate: {
path: 'selected_user',
select: '_id user_name first_name mobile last_name shaba'
}
}
])
if (!financial) {
return res.status(404).json({ message: 'تراکنش مورد نظر یافت نشد' })
}
const newfinancial = {
...financial._doc,
createdAt: jMoment(financial.createdAt).format('jYYYY-jMM-jDD HH:mm')
}
return res.status(200).json({ financial: newfinancial })
} catch (error) {
console.error('Error occurred:', error)
res.status(500).json({ error: 'Internal server error' })
}
}
module.exports = { getFinancial, getFinancialDetail }

View File

@@ -1,94 +1,94 @@
/* eslint-disable camelcase */
const AdminModel = require('../../../models/AdminModel')
const bcrypt = require('bcryptjs')
const TokenService = require('../../../services/TokenService')
const adminLogin = async (req, res, next) => {
try {
// اعتبارسنجی ورودی ها
const { user_name, password } = req.body
if (!user_name || !password) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن کاربر با نام کاربری
const userLow = user_name.toLowerCase()
const user = await AdminModel.findOne({ user_name: userLow })
if (!user) {
return res.status(404).json({
error: true,
message: 'کاربری با این نام کاربری یافت نشد'
})
}
if (!user.password) {
return res.status(422).json({
error: true,
message: 'رمز عبور برای این کاربر تنظیم نشده است'
})
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
return res.status(422).json({
error: true,
message: 'نام کاربری یا رمز عبور اشتباه است'
})
}
// اگر هم نام کاربری و هم رمز عبور درست بود، ارسال پیام موفقیت آمیز
const token = TokenService.sign({ id: user._id })
return res.json({
message: 'کد تایید صحیح بود',
token,
id: user._id
})
} catch (error) {
next(error)
}
}
const changePassword = async (req, res, next) => {
try {
// اعتبارسنجی ورودی ها
const { user_name, password, new_password } = req.body
if (!user_name || !password || !new_password) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن کاربر با نام کاربری
const userLow = user_name.toLowerCase()
const user = await AdminModel.findOne({ user_name: userLow })
if (!user) {
return res.status(404).json({
error: true,
message: 'کاربری با این نام کاربری یا رمز عبور یافت نشد'
})
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
return res.status(422).json({
error: true,
message: 'نام کاربری یا رمز عبور اشتباه است'
})
}
// هش کردن پسورد جدید و ذخیره در دیتابیس
const hashedPassword = await bcrypt.hash(new_password, 10)
user.password = hashedPassword
await user.save()
return res.json({
message: 'کلمه عبور با موفقیت ذخیره شد'
})
} catch (error) {
next(error)
}
}
module.exports = {
adminLogin, changePassword
}
/* eslint-disable camelcase */
const AdminModel = require('../../../models/AdminModel')
const bcrypt = require('bcryptjs')
const TokenService = require('../../../services/TokenService')
const adminLogin = async (req, res, next) => {
try {
// اعتبارسنجی ورودی ها
const { user_name, password } = req.body
if (!user_name || !password) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن کاربر با نام کاربری
const userLow = user_name.toLowerCase()
const user = await AdminModel.findOne({ user_name: userLow })
if (!user) {
return res.status(404).json({
error: true,
message: 'کاربری با این نام کاربری یافت نشد'
})
}
if (!user.password) {
return res.status(422).json({
error: true,
message: 'رمز عبور برای این کاربر تنظیم نشده است'
})
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
return res.status(422).json({
error: true,
message: 'نام کاربری یا رمز عبور اشتباه است'
})
}
// اگر هم نام کاربری و هم رمز عبور درست بود، ارسال پیام موفقیت آمیز
const token = TokenService.sign({ id: user._id })
return res.json({
message: 'کد تایید صحیح بود',
token,
id: user._id
})
} catch (error) {
next(error)
}
}
const changePassword = async (req, res, next) => {
try {
// اعتبارسنجی ورودی ها
const { user_name, password, new_password } = req.body
if (!user_name || !password || !new_password) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
// یافتن کاربر با نام کاربری
const userLow = user_name.toLowerCase()
const user = await AdminModel.findOne({ user_name: userLow })
if (!user) {
return res.status(404).json({
error: true,
message: 'کاربری با این نام کاربری یا رمز عبور یافت نشد'
})
}
const isPasswordValid = await bcrypt.compare(password, user.password)
if (!isPasswordValid) {
return res.status(422).json({
error: true,
message: 'نام کاربری یا رمز عبور اشتباه است'
})
}
// هش کردن پسورد جدید و ذخیره در دیتابیس
const hashedPassword = await bcrypt.hash(new_password, 10)
user.password = hashedPassword
await user.save()
return res.json({
message: 'کلمه عبور با موفقیت ذخیره شد'
})
} catch (error) {
next(error)
}
}
module.exports = {
adminLogin, changePassword
}

View File

@@ -1,176 +1,176 @@
/* eslint-disable camelcase */
const NotificationModel = require('../../../models/NotificationModel')
const PostModel = require('../../../models/PostModel')
const UserModel = require('../../../models/UserModel')
const jMoment = require('moment-jalaali')
const { default: mongoose } = require('mongoose')
const getPosts = async (req, res, next) => {
try {
const authHeader = req.header('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Access Denied: No token provided' });
}
const token = authHeader.split(' ')[1];
const {
page = 1,
limit = 10,
startDate,
endDate,
status,
} = req.query;
const filter = {};
if (startDate || endDate) {
filter.createdAt = {};
if (startDate) {
filter.createdAt.$gte = new Date(startDate);
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate);
}
}
if (status) {
filter.status = status;
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: {
path: 'user_id',
select: '_id user_name first_name mobile last_name national_code user_type expertise',
},
};
const posts = await PostModel.paginate(filter, options);
const postList = posts.docs.map((post) => ({
_id: post._id,
post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
status: post.status,
post_images: post.post_images,
post_video: post.post_video,
type: post.type,
files: post.files,
user_id: post.user_id?._id || null,
user_name: post.user_id?.user_name || '-',
user_type: post.user_id?.user_type || '-',
expertise: post.user_id?.expertise || '-',
first_name: post.user_id?.first_name || '-',
last_name: post.user_id?.last_name || '-',
mobile: post.user_id?.mobile || '-',
national_code: post.user_id?.national_code || '-',
createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
}));
res.status(200).json({
posts: postList,
totalPages: posts.totalPages,
totalItems: posts.totalDocs,
});
} catch (error) {
console.error('Error in getPosts:', error);
res.status(500).json({ message: 'خطا در دریافت پست‌ها.' });
}
};
const getPostDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const post_id = req.query.post_id
// eslint-disable-next-line no-unused-vars
if (!mongoose.Types.ObjectId.isValid(post_id)) {
return res.status(400).json({ message: 'شناسه پست معتبر نیست' })
}
const post = await PostModel.findById(post_id).populate('user_id', '_id user_name first_name last_name profile_image user_level')
if (!post) {
return res.status(404).json({ message: 'پست مورد نظر یافت نشد' })
}
const response = {
_id: post._id,
post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
status: post.status,
caption: post.caption,
comments: post.comments,
post_images: post.post_images,
post_video: post.post_video,
type: post.type,
files: post.files,
user_id: post.user_id?._id || null,
user_name: post.user_id?.user_name || '-',
user_type: post.user_id?.user_type || '-',
expertise: post.user_id?.expertise || '-',
first_name: post.user_id?.first_name || '-',
last_name: post.user_id?.last_name || '-',
mobile: post.user_id?.mobile || '-',
national_code: post.user_id?.national_code || '-',
createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
}
return res.status(200).json({ post: response })
} catch (error) {
next(error)
}
}
const acceptPost = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, user_id, status } = req.body
if (!id || !user_id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const user = await UserModel.findById(user_id)
const post = await PostModel.findById(id)
if (!post) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
post.status = status
await post.save()
if (status === 'accept') {
user.last_post = post
await user.save()
const notification = new NotificationModel({
user_id: user?._id,
project_post_id: post?._id,
type: 'accept-post',
title: 'انتشار پست',
description: 'پست شما مورد تایید قرار گرفت.'
})
await notification.save()
} else {
const notification = new NotificationModel({
user_id: user?._id,
project_post_id: post?._id,
type: 'reject-post',
title: 'رد پست',
description: 'پست شما مورد تایید قرار نگرفت.'
})
await notification.save()
}
res.status(201).json({ message: 'پست با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
acceptPost, getPosts, getPostDetail
}
/* eslint-disable camelcase */
const NotificationModel = require('../../../models/NotificationModel')
const PostModel = require('../../../models/PostModel')
const UserModel = require('../../../models/UserModel')
const jMoment = require('moment-jalaali')
const { default: mongoose } = require('mongoose')
const getPosts = async (req, res, next) => {
try {
const authHeader = req.header('Authorization');
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ message: 'Access Denied: No token provided' });
}
const token = authHeader.split(' ')[1];
const {
page = 1,
limit = 10,
startDate,
endDate,
status,
} = req.query;
const filter = {};
if (startDate || endDate) {
filter.createdAt = {};
if (startDate) {
filter.createdAt.$gte = new Date(startDate);
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate);
}
}
if (status) {
filter.status = status;
}
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 },
populate: {
path: 'user_id',
select: '_id user_name first_name mobile last_name national_code user_type expertise',
},
};
const posts = await PostModel.paginate(filter, options);
const postList = posts.docs.map((post) => ({
_id: post._id,
post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
status: post.status,
post_images: post.post_images,
post_video: post.post_video,
type: post.type,
files: post.files,
user_id: post.user_id?._id || null,
user_name: post.user_id?.user_name || '-',
user_type: post.user_id?.user_type || '-',
expertise: post.user_id?.expertise || '-',
first_name: post.user_id?.first_name || '-',
last_name: post.user_id?.last_name || '-',
mobile: post.user_id?.mobile || '-',
national_code: post.user_id?.national_code || '-',
createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
}));
res.status(200).json({
posts: postList,
totalPages: posts.totalPages,
totalItems: posts.totalDocs,
});
} catch (error) {
console.error('Error in getPosts:', error);
res.status(500).json({ message: 'خطا در دریافت پست‌ها.' });
}
};
const getPostDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const post_id = req.query.post_id
// eslint-disable-next-line no-unused-vars
if (!mongoose.Types.ObjectId.isValid(post_id)) {
return res.status(400).json({ message: 'شناسه پست معتبر نیست' })
}
const post = await PostModel.findById(post_id).populate('user_id', '_id user_name first_name last_name profile_image user_level')
if (!post) {
return res.status(404).json({ message: 'پست مورد نظر یافت نشد' })
}
const response = {
_id: post._id,
post_image: post.post_images && post.post_images.length > 0 ? post.post_images[0] : post.post_video || null, // استفاده از اولین تصویر یا ویدئو
status: post.status,
caption: post.caption,
comments: post.comments,
post_images: post.post_images,
post_video: post.post_video,
type: post.type,
files: post.files,
user_id: post.user_id?._id || null,
user_name: post.user_id?.user_name || '-',
user_type: post.user_id?.user_type || '-',
expertise: post.user_id?.expertise || '-',
first_name: post.user_id?.first_name || '-',
last_name: post.user_id?.last_name || '-',
mobile: post.user_id?.mobile || '-',
national_code: post.user_id?.national_code || '-',
createdAt: post.createdAt ? jMoment(post.createdAt).format('jYYYY-jMM-jDD HH:mm') : '-',
}
return res.status(200).json({ post: response })
} catch (error) {
next(error)
}
}
const acceptPost = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, user_id, status } = req.body
if (!id || !user_id || !status) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const user = await UserModel.findById(user_id)
const post = await PostModel.findById(id)
if (!post) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
post.status = status
await post.save()
if (status === 'accept') {
user.last_post = post
await user.save()
const notification = new NotificationModel({
user_id: user?._id,
project_post_id: post?._id,
type: 'accept-post',
title: 'انتشار پست',
description: 'پست شما مورد تایید قرار گرفت.'
})
await notification.save()
} else {
const notification = new NotificationModel({
user_id: user?._id,
project_post_id: post?._id,
type: 'reject-post',
title: 'رد پست',
description: 'پست شما مورد تایید قرار نگرفت.'
})
await notification.save()
}
res.status(201).json({ message: 'پست با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
module.exports = {
acceptPost, getPosts, getPostDetail
}

View File

@@ -1,256 +1,256 @@
/* eslint-disable camelcase */
const ProjectModel = require('../../../models/ProjectModel')
const jMoment = require('moment-jalaali')
const RequestModel = require('../../../models/RequestModel')
const NotificationModel = require('../../../models/NotificationModel')
const getProjects = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
// eslint-disable-next-line no-unused-vars
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
// ساخت فیلتر برای استفاده در جستجوی MongoDB
const filter = {
} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
// دریافت لیست پروژه‌ها با استفاده از فیلتر و گزینه‌های صفحه‌بندی
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'creator_id', select: '_id user_name first_name last_name' },
{ path: 'selected_user', select: '_id user_name first_name last_name' }
]
}
const projects = await ProjectModel.paginate(filter, options)
const projectsList = projects.docs.map(project => ({
_id: project._id,
title: project.title,
expertise: project.expertise,
sub_expertise: project.sub_expertise,
offer_time: project.offer_time,
offer_price: project.offer_price,
final_price: project.final_price,
final_time: project.final_time,
createdAt: jMoment(project.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: project.status,
creator: project.creator_id
? {
_id: project.creator_id._id,
user_name: project.creator_id.user_name,
first_name: project.creator_id.first_name,
last_name: project.creator_id.last_name
}
: null,
selected_user: project.selected_user
? {
_id: project.selected_user._id,
user_name: project.selected_user.user_name,
first_name: project.selected_user.first_name,
last_name: project.selected_user.last_name
}
: null
}))
res.status(200).json({
projects: projectsList,
totalPages: projects.totalPages, // ارسال تعداد کل صفحات
totalItems: projects.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
next(error)
}
}
const getProjectDetails = async (req, res, next) => {
try {
const { project_id } = req.query
// بررسی وجود projectId
if (!project_id) {
return res.status(400).send('Project ID is required')
}
// یافتن پروژه و جمع‌آوری اطلاعات مرتبط با سازنده و کاربر انتخاب شده
const project = await ProjectModel.findById(project_id)
.populate('creator_id', '_id user_name first_name last_name mobile')
.populate('selected_user', '_id user_name first_name last_name mobile')
.lean()
// بررسی وجود پروژه
if (!project) {
return res.status(404).send('Project not found')
}
// دریافت لیست درخواست‌های پروژه
const projectRequests = await RequestModel.find({ project: project_id })
.populate('user', '_id first_name last_name user_name rate profile_image')
.sort({ status: 1 })
.lean()
// ساختاردهی پاسخ نهایی
const projectDetails = {
_id: project._id,
title: project.title,
description: project.description,
creator: project.creator_id
? {
_id: project.creator_id._id,
first_name: project.creator_id.first_name,
last_name: project.creator_id.last_name,
user_name: project.creator_id.user_name,
mobile: project.creator_id.mobile
}
: null,
selected_user: project.selected_user
? {
_id: project.selected_user._id,
first_name: project.selected_user.first_name,
last_name: project.creator_id.last_name,
user_name: project.selected_user.user_name,
mobile: project.selected_user.mobile
}
: null,
province: project.province,
city: project.city,
createdAt: jMoment(project.createdAt).format('jYYYY-jMM-jDD HH:mm'),
expertise: project.expertise,
sub_expertise: project.sub_expertise,
offer_time: project.offer_time,
offer_price: project.offer_price,
final_price: project.final_price,
final_time: project.final_time,
status: project.status,
reject_reason: project.reject_reason,
requested_users: projectRequests.map(request => ({
_id: request.user._id,
first_name: request.user.first_name,
last_name: request.user.last_name,
user_name: request.user.user_name,
profile_image: request.user.profile_image,
time: request.time,
price: request.price
}))
}
res.status(200).json({ project: projectDetails })
} catch (error) {
next(error)
}
}
const acceptProject = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, user_name } = req.body
if (!id) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const project = await ProjectModel.findById(id)
if (!project) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
project.acceptedAt = new Date()
project.status = 'accepted'
await project.save()
const notification = new NotificationModel({
user_id: project?.creator_id,
project_post_id: project?._id,
type: 'accept-project',
title: 'انتشار درخواست',
description: `درخواست شما با عنوان: ${project?.title} منتشر شد `
})
await notification.save()
if (project?.public_status === 'private' && project?.created_for_user) {
const notification = new NotificationModel({
user_id: project?.created_for_user,
project_post_id: project?._id,
type: 'recive-project',
title: 'دعوت به همکاری',
description: `کاربر ${user_name} برای شما پروژه ایجاد کرده است ، برای نمایش جزئیات لمس کنید`
})
await notification.save()
}
res.status(201).json({ message: 'پروژه با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
const rejectProject = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, rejectReason } = req.body
if (!id) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const project = await ProjectModel.findById(id)
if (!project) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
project.status = 'rejected'
project.reject_reason = rejectReason
await project.save()
const notification = new NotificationModel({
user_id: project?.creator_id,
project_post_id: project?._id,
type: 'reject-project',
title: 'رد درخواست',
description: `درخواست شما با عنوان: ${project?.title} رد شد، برای دیدن علت رد، لمس کنید `
})
await notification.save()
res.status(201).json({ message: 'پروژه با موفقیت رد شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getProjects,
getProjectDetails,
acceptProject,
rejectProject
}
/* eslint-disable camelcase */
const ProjectModel = require('../../../models/ProjectModel')
const jMoment = require('moment-jalaali')
const RequestModel = require('../../../models/RequestModel')
const NotificationModel = require('../../../models/NotificationModel')
const getProjects = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
// eslint-disable-next-line no-unused-vars
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query
// ساخت فیلتر برای استفاده در جستجوی MongoDB
const filter = {
} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
// دریافت لیست پروژه‌ها با استفاده از فیلتر و گزینه‌های صفحه‌بندی
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'creator_id', select: '_id user_name first_name last_name' },
{ path: 'selected_user', select: '_id user_name first_name last_name' }
]
}
const projects = await ProjectModel.paginate(filter, options)
const projectsList = projects.docs.map(project => ({
_id: project._id,
title: project.title,
expertise: project.expertise,
sub_expertise: project.sub_expertise,
offer_time: project.offer_time,
offer_price: project.offer_price,
final_price: project.final_price,
final_time: project.final_time,
createdAt: jMoment(project.createdAt).format('jYYYY-jMM-jDD HH:mm'),
status: project.status,
creator: project.creator_id
? {
_id: project.creator_id._id,
user_name: project.creator_id.user_name,
first_name: project.creator_id.first_name,
last_name: project.creator_id.last_name
}
: null,
selected_user: project.selected_user
? {
_id: project.selected_user._id,
user_name: project.selected_user.user_name,
first_name: project.selected_user.first_name,
last_name: project.selected_user.last_name
}
: null
}))
res.status(200).json({
projects: projectsList,
totalPages: projects.totalPages, // ارسال تعداد کل صفحات
totalItems: projects.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
next(error)
}
}
const getProjectDetails = async (req, res, next) => {
try {
const { project_id } = req.query
// بررسی وجود projectId
if (!project_id) {
return res.status(400).send('Project ID is required')
}
// یافتن پروژه و جمع‌آوری اطلاعات مرتبط با سازنده و کاربر انتخاب شده
const project = await ProjectModel.findById(project_id)
.populate('creator_id', '_id user_name first_name last_name mobile')
.populate('selected_user', '_id user_name first_name last_name mobile')
.lean()
// بررسی وجود پروژه
if (!project) {
return res.status(404).send('Project not found')
}
// دریافت لیست درخواست‌های پروژه
const projectRequests = await RequestModel.find({ project: project_id })
.populate('user', '_id first_name last_name user_name rate profile_image')
.sort({ status: 1 })
.lean()
// ساختاردهی پاسخ نهایی
const projectDetails = {
_id: project._id,
title: project.title,
description: project.description,
creator: project.creator_id
? {
_id: project.creator_id._id,
first_name: project.creator_id.first_name,
last_name: project.creator_id.last_name,
user_name: project.creator_id.user_name,
mobile: project.creator_id.mobile
}
: null,
selected_user: project.selected_user
? {
_id: project.selected_user._id,
first_name: project.selected_user.first_name,
last_name: project.creator_id.last_name,
user_name: project.selected_user.user_name,
mobile: project.selected_user.mobile
}
: null,
province: project.province,
city: project.city,
createdAt: jMoment(project.createdAt).format('jYYYY-jMM-jDD HH:mm'),
expertise: project.expertise,
sub_expertise: project.sub_expertise,
offer_time: project.offer_time,
offer_price: project.offer_price,
final_price: project.final_price,
final_time: project.final_time,
status: project.status,
reject_reason: project.reject_reason,
requested_users: projectRequests.map(request => ({
_id: request.user._id,
first_name: request.user.first_name,
last_name: request.user.last_name,
user_name: request.user.user_name,
profile_image: request.user.profile_image,
time: request.time,
price: request.price
}))
}
res.status(200).json({ project: projectDetails })
} catch (error) {
next(error)
}
}
const acceptProject = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, user_name } = req.body
if (!id) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const project = await ProjectModel.findById(id)
if (!project) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
project.acceptedAt = new Date()
project.status = 'accepted'
await project.save()
const notification = new NotificationModel({
user_id: project?.creator_id,
project_post_id: project?._id,
type: 'accept-project',
title: 'انتشار درخواست',
description: `درخواست شما با عنوان: ${project?.title} منتشر شد `
})
await notification.save()
if (project?.public_status === 'private' && project?.created_for_user) {
const notification = new NotificationModel({
user_id: project?.created_for_user,
project_post_id: project?._id,
type: 'recive-project',
title: 'دعوت به همکاری',
description: `کاربر ${user_name} برای شما پروژه ایجاد کرده است ، برای نمایش جزئیات لمس کنید`
})
await notification.save()
}
res.status(201).json({ message: 'پروژه با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
const rejectProject = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { id, rejectReason } = req.body
if (!id) {
return res.status(422).json({
error: true,
message: 'اطلاعات ارسالی اشتباه است'
})
}
const project = await ProjectModel.findById(id)
if (!project) {
return res.status(404).json({
error: true,
message: 'پست مورد نظر یافت نشد'
})
}
project.status = 'rejected'
project.reject_reason = rejectReason
await project.save()
const notification = new NotificationModel({
user_id: project?.creator_id,
project_post_id: project?._id,
type: 'reject-project',
title: 'رد درخواست',
description: `درخواست شما با عنوان: ${project?.title} رد شد، برای دیدن علت رد، لمس کنید `
})
await notification.save()
res.status(201).json({ message: 'پروژه با موفقیت رد شد' })
} catch (error) {
next(error)
}
}
module.exports = {
getProjects,
getProjectDetails,
acceptProject,
rejectProject
}

View File

@@ -1,63 +1,63 @@
const TypeAndPriceModel = require('../../../models/TypeAndPriceModel')
const jwt = require('jsonwebtoken')
const UserModel = require('../../../models/UserModel')
const getProjectTypes = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const decodedToken = jwt.verify(token, process.env.APP_SECRET)
const userId = decodedToken.id
const user = await UserModel.findById(userId)
if (!user) {
return res.status(422).json({
error: true,
message: 'کاربر یافت نشد'
})
}
// درخواست انواع پروژه از دیتابیس
let projectTypes = await TypeAndPriceModel.find({}, 'name price')
// بررسی برای مواردی مانند پیدا نشدن انواع پروژه
if (!projectTypes) {
return res.status(404).json({ message: 'انواع پروژه یافت نشد.' })
}
// اگر کاربر درخواست رایگان روزانه نداشته باشد، نوع پروژه رایگان را حذف کنید
if (user.daily_free_request <= 0) {
projectTypes = projectTypes.filter(projectType => projectType.name !== 'free')
}
// ارسال انواع پروژه به کاربر
res.status(200).json({ projectTypes })
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in getProjectTypes:', error)
res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
}
}
const createProjectTypes = async (req, res, next) => {
try {
const { name, price } = req.body
// بررسی اعتبار ورودی‌ها
if (!name || price == null || price === undefined) {
return res.status(400).json({ message: 'لطفا نام و قیمت پروژه را وارد کنید.' })
}
// ایجاد نوع پروژه جدید
const newType = new TypeAndPriceModel({ name, price })
await newType.save()
// ارسال پیام موفقیت آمیز به کاربر
res.status(201).json({ message: 'نوع پروژه جدید با موفقیت ایجاد شد.' })
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in createProjectTypes:', error)
res.status(500).json({ message: 'خطا در ایجاد نوع پروژه.' })
}
}
module.exports = {
getProjectTypes,
createProjectTypes
}
const TypeAndPriceModel = require('../../../models/TypeAndPriceModel')
const jwt = require('jsonwebtoken')
const UserModel = require('../../../models/UserModel')
const getProjectTypes = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const decodedToken = jwt.verify(token, process.env.APP_SECRET)
const userId = decodedToken.id
const user = await UserModel.findById(userId)
if (!user) {
return res.status(422).json({
error: true,
message: 'کاربر یافت نشد'
})
}
// درخواست انواع پروژه از دیتابیس
let projectTypes = await TypeAndPriceModel.find({}, 'name price')
// بررسی برای مواردی مانند پیدا نشدن انواع پروژه
if (!projectTypes) {
return res.status(404).json({ message: 'انواع پروژه یافت نشد.' })
}
// اگر کاربر درخواست رایگان روزانه نداشته باشد، نوع پروژه رایگان را حذف کنید
if (user.daily_free_request <= 0) {
projectTypes = projectTypes.filter(projectType => projectType.name !== 'free')
}
// ارسال انواع پروژه به کاربر
res.status(200).json({ projectTypes })
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in getProjectTypes:', error)
res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
}
}
const createProjectTypes = async (req, res, next) => {
try {
const { name, price } = req.body
// بررسی اعتبار ورودی‌ها
if (!name || price == null || price === undefined) {
return res.status(400).json({ message: 'لطفا نام و قیمت پروژه را وارد کنید.' })
}
// ایجاد نوع پروژه جدید
const newType = new TypeAndPriceModel({ name, price })
await newType.save()
// ارسال پیام موفقیت آمیز به کاربر
res.status(201).json({ message: 'نوع پروژه جدید با موفقیت ایجاد شد.' })
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in createProjectTypes:', error)
res.status(500).json({ message: 'خطا در ایجاد نوع پروژه.' })
}
}
module.exports = {
getProjectTypes,
createProjectTypes
}

View File

@@ -1,36 +1,36 @@
// controllers/settingController.js
const SettingModel = require('../../../models/SettingsModel')
// متد برای دریافت تنظیمات بر اساس key
const getSetting = async (req, res, next) => {
try {
const { key } = req.params
const setting = await SettingModel.findOne({ key })
if (!setting) {
return res.status(404).json({ message: 'تنظیمات مورد نظر یافت نشد' })
}
res.status(200).json(setting)
} catch (error) {
next(error)
}
}
// متد برای به‌روزرسانی تنظیمات بر اساس key
const updateSetting = async (req, res, next) => {
try {
const { key } = req.params
const { value } = req.body
// eslint-disable-next-line no-unused-vars
const setting = await SettingModel.findOneAndUpdate(
{ key },
{ value },
{ new: true, upsert: true } // اگر وجود نداشت، آن را ایجاد کن
)
res.status(200).json({ message: 'تنظیمات با موفقیت بروز شد' })
} catch (error) {
next(error)
}
}
module.exports = { getSetting, updateSetting }
// controllers/settingController.js
const SettingModel = require('../../../models/SettingsModel')
// متد برای دریافت تنظیمات بر اساس key
const getSetting = async (req, res, next) => {
try {
const { key } = req.params
const setting = await SettingModel.findOne({ key })
if (!setting) {
return res.status(404).json({ message: 'تنظیمات مورد نظر یافت نشد' })
}
res.status(200).json(setting)
} catch (error) {
next(error)
}
}
// متد برای به‌روزرسانی تنظیمات بر اساس key
const updateSetting = async (req, res, next) => {
try {
const { key } = req.params
const { value } = req.body
// eslint-disable-next-line no-unused-vars
const setting = await SettingModel.findOneAndUpdate(
{ key },
{ value },
{ new: true, upsert: true } // اگر وجود نداشت، آن را ایجاد کن
)
res.status(200).json({ message: 'تنظیمات با موفقیت بروز شد' })
} catch (error) {
next(error)
}
}
module.exports = { getSetting, updateSetting }

View File

@@ -1,161 +1,161 @@
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const jMoment = require('moment-jalaali')
const AdvertisingProfileModel = require('../../../models/AdvertisingProfile')
const AdvertisingModel = require('../../../models/AdvertisingModel')
const getShops = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
// eslint-disable-next-line no-unused-vars
const { page = 1, limit = 10, expertise, most_price, most_requests, age, gender } = req.query
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// if (expertise) {
// filter.expertise = expertise
// }
// if (age) {
// filter.age = age
// }
// if (gender) {
// filter.gender = gender
// }
// استفاده از مدل پیجینیت شده برای دریافت نتایج صفحه‌بندی شده
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'user', select: '_id user_name first_name last_name' }
]
}
const shops = await AdvertisingProfileModel.paginate(filter, options)
const newShops = shops.docs.map(user => ({
_id: user._id,
user_name: user?.user?.user_name,
first_name: user?.user?.first_name,
last_name: user?.user?.last_name,
user_id: user?.user?._id,
profile_image: user.profile_image,
category: user.category,
vitrine_name: user.vitrine_name,
province: user.province,
city: user.city,
neighbourhood: user.neighbourhood,
createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm')
}))
res.status(200).json({
shops: newShops,
totalPages: shops.totalPages, // ارسال تعداد کل صفحات
totalItems: shops.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in getProjectTypes:', error)
res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
}
}
const getShopDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const profile_id = req.query.profile_id
// eslint-disable-next-line no-unused-vars
// دریافت جزئیات فروشگاه با استفاده از profile_id
const shop = await AdvertisingProfileModel.findById(profile_id)
.populate('user', '_id user_name first_name last_name')
.exec()
const userAds = await AdvertisingModel.find({ creator_id: shop?.user })
// جمع‌آوری اطلاعات از تبلیغات‌ها
let allImages = []
let allServices = []
let allFeatures = []
for (const ad of userAds) {
allImages = allImages.concat(ad.images)
allServices = allServices.concat(ad.services)
allFeatures = allFeatures.concat(ad.features)
}
// حذف آیتم‌های null و تکراری از allFeatures
const uniqueFeatures = []
const featureTitles = new Set()
for (const feature of allFeatures) {
if (feature && !featureTitles.has(feature.title)) {
uniqueFeatures.push(feature)
featureTitles.add(feature.title)
}
}
if (!shop) {
return res.status(404).json({ message: 'فروشگاه مورد نظر یافت نشد' })
}
const response = {
_id: shop?._id,
user_name: shop?.user?.user_name,
first_name: shop?.user?.first_name,
last_name: shop?.user?.last_name,
user_id: shop?.user?._id,
profile_image: shop?.profile_image,
category: shop?.category,
vitrine_name: shop?.vitrine_name,
province: shop?.province,
city: shop?.city,
neighbourhood: shop?.neighbourhood,
contactInfo: shop?.contactInfo,
address: shop?.address,
allImages: allImages?.reverse(),
allServices,
allFeatures: uniqueFeatures,
about_us: shop?.about_us
// اطلاعات اضافی که بعداً به شما می‌گویم
}
return res.status(200).json({ shop: response })
} catch (error) {
next(error)
}
}
const updateShop = async (req, res, next) => {
try {
const shopId = req.query.shopId // دریافت شناسه کاربر از درخواست
// چک کردن اعتبار شناسه کاربر
if (!mongoose.Types.ObjectId.isValid(shopId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
// فیلدهایی که می‌خواهید آپدیت شوند را از درخواست دریافت کنید
const updateFields = req.body
// اجرای آپدیت و بازگشت مقدار آپدیت شده
const updatedUser = await AdvertisingProfileModel.findByIdAndUpdate(
shopId,
updateFields,
{ new: true }
)
// بررسی آیا کاربر وجود دارد یا نه
if (!updatedUser) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'کاربر با موفقیت ویرایش شد', id: updatedUser._id })
} catch (error) {
const errors = []
if (error.code === 11000) {
// Duplicate key error
for (const key in error.keyValue) {
errors.push({ message: `ارور در فیلد ${key}` })
}
} else {
errors.push({ message: 'خطا در آپدیت کاربر' })
}
res.status(500).json({ errors })
}
}
module.exports = {
getShops, getShopDetail, updateShop
}
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const jMoment = require('moment-jalaali')
const AdvertisingProfileModel = require('../../../models/AdvertisingProfile')
const AdvertisingModel = require('../../../models/AdvertisingModel')
const getShops = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
// eslint-disable-next-line no-unused-vars
const { page = 1, limit = 10, expertise, most_price, most_requests, age, gender } = req.query
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// if (expertise) {
// filter.expertise = expertise
// }
// if (age) {
// filter.age = age
// }
// if (gender) {
// filter.gender = gender
// }
// استفاده از مدل پیجینیت شده برای دریافت نتایج صفحه‌بندی شده
const options = {
page: parseInt(page), // تبدیل صفحه به عدد صحیح
limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
sort: { createdAt: -1 },
populate: [
{ path: 'user', select: '_id user_name first_name last_name' }
]
}
const shops = await AdvertisingProfileModel.paginate(filter, options)
const newShops = shops.docs.map(user => ({
_id: user._id,
user_name: user?.user?.user_name,
first_name: user?.user?.first_name,
last_name: user?.user?.last_name,
user_id: user?.user?._id,
profile_image: user.profile_image,
category: user.category,
vitrine_name: user.vitrine_name,
province: user.province,
city: user.city,
neighbourhood: user.neighbourhood,
createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm')
}))
res.status(200).json({
shops: newShops,
totalPages: shops.totalPages, // ارسال تعداد کل صفحات
totalItems: shops.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
// در صورت بروز خطا، ارسال پیام خطا به کاربر
console.error('Error in getProjectTypes:', error)
res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
}
}
const getShopDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const profile_id = req.query.profile_id
// eslint-disable-next-line no-unused-vars
// دریافت جزئیات فروشگاه با استفاده از profile_id
const shop = await AdvertisingProfileModel.findById(profile_id)
.populate('user', '_id user_name first_name last_name')
.exec()
const userAds = await AdvertisingModel.find({ creator_id: shop?.user })
// جمع‌آوری اطلاعات از تبلیغات‌ها
let allImages = []
let allServices = []
let allFeatures = []
for (const ad of userAds) {
allImages = allImages.concat(ad.images)
allServices = allServices.concat(ad.services)
allFeatures = allFeatures.concat(ad.features)
}
// حذف آیتم‌های null و تکراری از allFeatures
const uniqueFeatures = []
const featureTitles = new Set()
for (const feature of allFeatures) {
if (feature && !featureTitles.has(feature.title)) {
uniqueFeatures.push(feature)
featureTitles.add(feature.title)
}
}
if (!shop) {
return res.status(404).json({ message: 'فروشگاه مورد نظر یافت نشد' })
}
const response = {
_id: shop?._id,
user_name: shop?.user?.user_name,
first_name: shop?.user?.first_name,
last_name: shop?.user?.last_name,
user_id: shop?.user?._id,
profile_image: shop?.profile_image,
category: shop?.category,
vitrine_name: shop?.vitrine_name,
province: shop?.province,
city: shop?.city,
neighbourhood: shop?.neighbourhood,
contactInfo: shop?.contactInfo,
address: shop?.address,
allImages: allImages?.reverse(),
allServices,
allFeatures: uniqueFeatures,
about_us: shop?.about_us
// اطلاعات اضافی که بعداً به شما می‌گویم
}
return res.status(200).json({ shop: response })
} catch (error) {
next(error)
}
}
const updateShop = async (req, res, next) => {
try {
const shopId = req.query.shopId // دریافت شناسه کاربر از درخواست
// چک کردن اعتبار شناسه کاربر
if (!mongoose.Types.ObjectId.isValid(shopId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
// فیلدهایی که می‌خواهید آپدیت شوند را از درخواست دریافت کنید
const updateFields = req.body
// اجرای آپدیت و بازگشت مقدار آپدیت شده
const updatedUser = await AdvertisingProfileModel.findByIdAndUpdate(
shopId,
updateFields,
{ new: true }
)
// بررسی آیا کاربر وجود دارد یا نه
if (!updatedUser) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'کاربر با موفقیت ویرایش شد', id: updatedUser._id })
} catch (error) {
const errors = []
if (error.code === 11000) {
// Duplicate key error
for (const key in error.keyValue) {
errors.push({ message: `ارور در فیلد ${key}` })
}
} else {
errors.push({ message: 'خطا در آپدیت کاربر' })
}
res.status(500).json({ errors })
}
}
module.exports = {
getShops, getShopDetail, updateShop
}

View File

@@ -1,153 +1,153 @@
const NotificationModel = require('../../../models/NotificationModel')
const TicketMessageModel = require('../../../models/TicketMessageModel')
const TicketModel = require('../../../models/TicketModel')
const jwt = require('jsonwebtoken')
const jMoment = require('moment-jalaali')
const getAllTickets = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query // افزودن پارامترهای صفحه‌بندی به درخواست
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page, 10) || 1,
limit: parseInt(limit, 10) || 10,
populate: [
{ path: 'user', select: '_id user_name first_name last_name mobile expertise' }
],
sort: { updatedAt: -1 }
}
const tickets = await TicketModel.paginate(filter, options)
const ticketList = tickets?.docs.map(ticket => {
const jDate = jMoment(ticket.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...ticket._doc,
createdAt: jDate
}
})
res.json({
tickets: ticketList,
totalPages: tickets.totalPages, // ارسال تعداد کل صفحات
totalItems: tickets.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
const addAdminMessageToTicket = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const decodedToken = jwt.verify(token, process.env.APP_SECRET)
const adminId = decodedToken.id
const { text, ticketId } = req.body
const newMessage = new TicketMessageModel({
text,
senderType: 'Admin',
senderId: adminId,
ticket: ticketId
})
await newMessage.save()
const ticket = await TicketModel.findById(ticketId)
if (!ticket) {
return res.status(404).json({ error: 'Ticket not found' })
}
ticket.status = 'Answered'
ticket.new_message = true
await ticket.save()
const notification = new NotificationModel({
user_id: ticket?.user,
project_post_id: ticket?._id,
type: 'ticket-message',
title: 'پاسخ پشتیبانی',
description: `پاسخ جدید در تیکت: ${ticket?.title}`
})
await notification.save()
res.status(201).json(newMessage)
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
// senderId
const getTicketMessages = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { ticketId } = req.query
const { page = 1, limit = 10 } = req.query
const options = {
page: parseInt(page) || 1,
limit: parseInt(limit) || 10,
populate: [
{ path: 'senderId', select: '_id user_name first_name last_name mobile expertise' }
],
sort: { createdAt: -1 }
}
const messages = await TicketMessageModel.paginate({ ticket: ticketId }, options)
const messageList = messages?.docs.map(message => {
const jDate = jMoment(message.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...message._doc,
createdAt: jDate
}
})
res.json({
messages: messageList.reverse(),
totalPages: messages.totalPages, // ارسال تعداد کل صفحات
totalItems: messages.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
const closeTicket = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { ticketId } = req.body
if (!ticketId) return res.status(400).send('Ticket ID is required')
const ticket = await TicketModel.findById(ticketId)
if (!ticket) return res.status(404).send('Ticket not found')
ticket.status = 'Closed'
await ticket.save()
res.status(200).json({ message: 'Ticket has been closed successfully' })
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
module.exports = { getAllTickets, addAdminMessageToTicket, getTicketMessages, closeTicket }
const NotificationModel = require('../../../models/NotificationModel')
const TicketMessageModel = require('../../../models/TicketMessageModel')
const TicketModel = require('../../../models/TicketModel')
const jwt = require('jsonwebtoken')
const jMoment = require('moment-jalaali')
const getAllTickets = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const {
page = 1, limit = 10,
startDate,
endDate,
status
} = req.query // افزودن پارامترهای صفحه‌بندی به درخواست
const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// Date
if (startDate || endDate) {
filter.createdAt = {}
if (startDate) {
filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
}
if (endDate) {
filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
}
}
if (status) {
filter.status = status
}
const options = {
page: parseInt(page, 10) || 1,
limit: parseInt(limit, 10) || 10,
populate: [
{ path: 'user', select: '_id user_name first_name last_name mobile expertise' }
],
sort: { updatedAt: -1 }
}
const tickets = await TicketModel.paginate(filter, options)
const ticketList = tickets?.docs.map(ticket => {
const jDate = jMoment(ticket.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...ticket._doc,
createdAt: jDate
}
})
res.json({
tickets: ticketList,
totalPages: tickets.totalPages, // ارسال تعداد کل صفحات
totalItems: tickets.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
const addAdminMessageToTicket = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const decodedToken = jwt.verify(token, process.env.APP_SECRET)
const adminId = decodedToken.id
const { text, ticketId } = req.body
const newMessage = new TicketMessageModel({
text,
senderType: 'Admin',
senderId: adminId,
ticket: ticketId
})
await newMessage.save()
const ticket = await TicketModel.findById(ticketId)
if (!ticket) {
return res.status(404).json({ error: 'Ticket not found' })
}
ticket.status = 'Answered'
ticket.new_message = true
await ticket.save()
const notification = new NotificationModel({
user_id: ticket?.user,
project_post_id: ticket?._id,
type: 'ticket-message',
title: 'پاسخ پشتیبانی',
description: `پاسخ جدید در تیکت: ${ticket?.title}`
})
await notification.save()
res.status(201).json(newMessage)
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
// senderId
const getTicketMessages = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { ticketId } = req.query
const { page = 1, limit = 10 } = req.query
const options = {
page: parseInt(page) || 1,
limit: parseInt(limit) || 10,
populate: [
{ path: 'senderId', select: '_id user_name first_name last_name mobile expertise' }
],
sort: { createdAt: -1 }
}
const messages = await TicketMessageModel.paginate({ ticket: ticketId }, options)
const messageList = messages?.docs.map(message => {
const jDate = jMoment(message.createdAt).format('jYYYY-jMM-jDD HH:mm')
return {
...message._doc,
createdAt: jDate
}
})
res.json({
messages: messageList.reverse(),
totalPages: messages.totalPages, // ارسال تعداد کل صفحات
totalItems: messages.totalDocs // ارسال تعداد کل آیتم‌ها
})
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
const closeTicket = async (req, res) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const { ticketId } = req.body
if (!ticketId) return res.status(400).send('Ticket ID is required')
const ticket = await TicketModel.findById(ticketId)
if (!ticket) return res.status(404).send('Ticket not found')
ticket.status = 'Closed'
await ticket.save()
res.status(200).json({ message: 'Ticket has been closed successfully' })
} catch (error) {
res.status(500).json({ error: 'Internal Server Error' })
}
}
module.exports = { getAllTickets, addAdminMessageToTicket, getTicketMessages, closeTicket }

View File

@@ -1,410 +1,410 @@
/* eslint-disable no-unused-vars */
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const UserModel = require('../../../models/UserModel')
const jMoment = require('moment-jalaali')
const NotificationModel = require('../../../models/NotificationModel')
const { default: axios } = require('axios')
const getUsers = async (req, res, next) => {
try {
// بررسی توکن
const token = req.header('Authorization')?.split(' ')[1];
if (!token) return res.status(401).send('Access Denied');
// پارامترهای query
const {
page = 1,
limit = 20,
expertise,
most_price,
most_requests,
age,
gender,
startDate,
endDate,
status,
search
} = req.query;
const filter = {}; // شرط‌های فیلتر
// فیلتر تاریخ
if (startDate || endDate) {
filter.createdAt = {};
if (startDate) filter.createdAt.$gte = new Date(startDate);
if (endDate) filter.createdAt.$lte = new Date(endDate);
}
// فیلتر وضعیت
if (status) {
filter.is_verified = status;
}
// فیلتر سرچ
if (search) {
const regex = new RegExp(search, "i"); // i = ignore case
filter.$or = [
{ first_name: regex },
{ last_name: regex },
{ user_name: regex },
{ mobile: regex }
];
}
// فیلترهای دیگر (اختیاری)
if (expertise) filter.expertise = expertise;
if (age) filter.age = age;
if (gender) filter.gender = gender;
// گزینه‌های صفحه‌بندی
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 }
};
// گرفتن کاربران با paginate
const users = await UserModel.paginate(filter, options);
// آماده‌سازی خروجی
const newUsers = users.docs.map(user => ({
_id: user._id,
mobile: user.mobile,
user_name: user.user_name,
first_name: user.first_name,
last_name: user.last_name,
user_type: user.user_type,
is_verified: user.is_verified,
profile_image: user.profile_image,
expertise: user.expertise,
sub_expertise: user.sub_expertise,
gender: user.gender,
national_code: user.national_code,
province: user.province,
city: user.city,
last_online: jMoment(user.last_online).format('jYYYY-jMM-jDD HH:mm'),
createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm'),
block_status: user.block_status
}));
res.status(200).json({
users: newUsers,
totalPages: users.totalPages,
totalItems: users.totalDocs
});
} catch (error) {
console.error('Error in getUsers:', error);
res.status(500).json({ message: 'خطا در دریافت کاربران.' });
}
};
// const getUsers = async (req, res, next) => {
// try {
// const token = req.header('Authorization').split(' ')[1]
// if (!token) return res.status(401).send('Access Denied')
// // eslint-disable-next-line no-unused-vars
// const {
// page = 1,
// limit = 10,
// expertise,
// most_price,
// most_requests,
// age,
// gender,
// startDate,
// endDate,
// status
// } = req.query
// const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// // Date
// if (startDate || endDate) {
// filter.createdAt = {}
// if (startDate) {
// filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
// }
// if (endDate) {
// filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
// }
// }
// if (status) {
// filter.is_verified = status
// }
// // if (expertise) {
// // filter.expertise = expertise
// // }
// // if (age) {
// // filter.age = age
// // }
// // if (gender) {
// // filter.gender = gender
// // }
// // استفاده از مدل پیجینیت شده برای دریافت نتایج صفحه‌بندی شده
// const options = {
// page: parseInt(page), // تبدیل صفحه به عدد صحیح
// limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
// sort: { createdAt: -1 }
// }
// const users = await UserModel.paginate(filter, options)
// const newUsers = users.docs.map(user => ({
// _id: user._id,
// mobile: user.mobile,
// user_name: user.user_name,
// first_name: user.first_name,
// last_name: user.last_name,
// user_type: user.user_type,
// is_verified: user.is_verified,
// profile_image: user.profile_image,
// expertise: user.expertise,
// sub_expertise: user.sub_expertise,
// gender: user.gender,
// national_code: user.national_code,
// province: user.province,
// city: user.city,
// last_online: jMoment(user.last_online).format('jYYYY-jMM-jDD HH:mm'),
// createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm'),
// block_status: user.block_status
// }))
// res.status(200).json({
// users: newUsers,
// totalPages: users.totalPages, // ارسال تعداد کل صفحات
// totalItems: users.totalDocs // ارسال تعداد کل آیتم‌ها
// })
// } catch (error) {
// // در صورت بروز خطا، ارسال پیام خطا به کاربر
// console.error('Error in getProjectTypes:', error)
// res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
// }
// }
const getUserDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const user_id = req.query.user_id
// eslint-disable-next-line no-unused-vars
if (!mongoose.Types.ObjectId.isValid(user_id)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
const user = await UserModel.findById(user_id)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
const response = {
_id: user?._id,
profile_image: user?.profile_image,
first_name: user?.first_name,
last_name: user?.last_name,
user_name: user?.user_name,
mobile: user?.mobile,
national_code: user?.national_code,
province: user?.province,
city: user?.city,
address: user?.address,
height: user?.height,
weight: user?.weight,
size: user?.size,
birthday: user?.birthday,
show_location: user?.show_location,
cooperation_abroad: user?.cooperation_abroad,
conversation_projects: user?.conversation_projects,
expertise: user?.expertise,
sub_expertise: user?.sub_expertise,
shaba: user?.shaba,
national_card_image: user?.national_card_image,
last_online: jMoment(user?.last_online).format('jYYYY-jMM-jDD HH:mm'),
createdAt: jMoment(user?.createdAt).format('jYYYY-jMM-jDD HH:mm'),
block_status: user?.block_status,
user_level: user?.user_level,
user_type: user?.user_type,
user_score: user?.user_score,
services :user?.services,
is_verified: user?.is_verified,
rate: user?.rate,
bio: user?.bio,
eye_color: user?.eye_color,
hair_color: user?.hair_color,
lat: user?.lat,
lng: user?.lng
}
return res.status(200).json({ user: response })
} catch (error) {
next(error)
}
}
const updateUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
// چک کردن اعتبار شناسه کاربر
if (!mongoose.Types.ObjectId.isValid(userId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
// فیلدهایی که می‌خواهید آپدیت شوند را از درخواست دریافت کنید
const updateFields = req.body
// اجرای آپدیت و بازگشت مقدار آپدیت شده
const updatedUser = await UserModel.findByIdAndUpdate(
userId,
updateFields,
{ new: true }
)
// بررسی آیا کاربر وجود دارد یا نه
if (!updatedUser) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'کاربر با موفقیت ویرایش شد', id: updatedUser._id })
} catch (error) {
const errors = []
if (error.code === 11000) {
// Duplicate key error
for (const key in error.keyValue) {
errors.push({ message: `ارور در فیلد ${key}` })
}
} else {
errors.push({ message: 'خطا در آپدیت کاربر' })
}
res.status(500).json({ errors })
}
}
const verifyUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.is_verified = 'verified';
user.is_Register = true;
await user.save();
const notification = new NotificationModel({
user_id: userId,
type: 'verify',
title: 'تایید مدارک',
description: 'مدارک ارسالی شما با موفقیت تایید شد'
})
await notification.save()
// Sms
const userReciver = await UserModel.findById(userId)
const data = JSON.stringify({
mobile: userReciver?.mobile,
templateId: '632057',
parameters: [
{ name: 'USERS', value: userReciver?.first_name + ' ' + userReciver?.last_name }
]
})
const config = {
method: 'post',
url: 'https://api.sms.ir/v1/send/verify',
headers: {
'Content-Type': 'application/json',
Accept: 'text/plain',
'x-api-key': '2JKxGbTzE64t0YTkjip6RYHnm9mq1haMlidF8WWwQunwubHFVW6iaMmfFQbMXEDt'
},
data
}
axios(config)
.then(function (response) {
})
.catch(function (error) {
console.log(error)
})
// End Sms
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'مدارک کاربر با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
const updateUserStatus = async (req, res, next) => {
try {
const { userId, block_status } = req.body;
if (!mongoose.Types.ObjectId.isValid(userId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' });
}
const user = await UserModel.findByIdAndUpdate(
userId,
{ block_status },
{ new: true }
);
if (!user) return res.status(404).json({ message: 'کاربر یافت نشد' });
res.status(200).json({ message: 'وضعیت کاربر با موفقیت تغییر کرد', block_status: user.block_status });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'خطای سرور' });
}
};
const rejectUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.is_verified = 'rejected'
user.is_Register = false
await user.save()
const notification = new NotificationModel({
user_id: userId,
type: 'reject-user',
title: 'رد مدارک',
description: 'مدارک ارسالی شما رد شد، برای اطلاعات بیشتر از بخش تیکت به پشتیبانی پیام دهید.'
})
await notification.save()
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'مدارک کاربر با موفقیت رد شد' })
} catch (error) {
next(error)
}
}
const changePass = async (req, res, next) => {
try {
const { userId, password } = req.body;
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.password = password
await user.save()
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'رمز عبور با موفقیت تغییر کرد' });
} catch (error) {
next(error)
}
}
module.exports = {
getUsers, getUserDetail, updateUser, verifyUser, rejectUser, updateUserStatus, changePass
}
/* eslint-disable no-unused-vars */
/* eslint-disable camelcase */
const { default: mongoose } = require('mongoose')
const UserModel = require('../../../models/UserModel')
const jMoment = require('moment-jalaali')
const NotificationModel = require('../../../models/NotificationModel')
const { default: axios } = require('axios')
const getUsers = async (req, res, next) => {
try {
// بررسی توکن
const token = req.header('Authorization')?.split(' ')[1];
if (!token) return res.status(401).send('Access Denied');
// پارامترهای query
const {
page = 1,
limit = 20,
expertise,
most_price,
most_requests,
age,
gender,
startDate,
endDate,
status,
search
} = req.query;
const filter = {}; // شرط‌های فیلتر
// فیلتر تاریخ
if (startDate || endDate) {
filter.createdAt = {};
if (startDate) filter.createdAt.$gte = new Date(startDate);
if (endDate) filter.createdAt.$lte = new Date(endDate);
}
// فیلتر وضعیت
if (status) {
filter.is_verified = status;
}
// فیلتر سرچ
if (search) {
const regex = new RegExp(search, "i"); // i = ignore case
filter.$or = [
{ first_name: regex },
{ last_name: regex },
{ user_name: regex },
{ mobile: regex }
];
}
// فیلترهای دیگر (اختیاری)
if (expertise) filter.expertise = expertise;
if (age) filter.age = age;
if (gender) filter.gender = gender;
// گزینه‌های صفحه‌بندی
const options = {
page: parseInt(page),
limit: parseInt(limit),
sort: { createdAt: -1 }
};
// گرفتن کاربران با paginate
const users = await UserModel.paginate(filter, options);
// آماده‌سازی خروجی
const newUsers = users.docs.map(user => ({
_id: user._id,
mobile: user.mobile,
user_name: user.user_name,
first_name: user.first_name,
last_name: user.last_name,
user_type: user.user_type,
is_verified: user.is_verified,
profile_image: user.profile_image,
expertise: user.expertise,
sub_expertise: user.sub_expertise,
gender: user.gender,
national_code: user.national_code,
province: user.province,
city: user.city,
last_online: jMoment(user.last_online).format('jYYYY-jMM-jDD HH:mm'),
createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm'),
block_status: user.block_status
}));
res.status(200).json({
users: newUsers,
totalPages: users.totalPages,
totalItems: users.totalDocs
});
} catch (error) {
console.error('Error in getUsers:', error);
res.status(500).json({ message: 'خطا در دریافت کاربران.' });
}
};
// const getUsers = async (req, res, next) => {
// try {
// const token = req.header('Authorization').split(' ')[1]
// if (!token) return res.status(401).send('Access Denied')
// // eslint-disable-next-line no-unused-vars
// const {
// page = 1,
// limit = 10,
// expertise,
// most_price,
// most_requests,
// age,
// gender,
// startDate,
// endDate,
// status
// } = req.query
// const filter = {} // افزودن شرط‌های دیگر برای فیلتر
// // Date
// if (startDate || endDate) {
// filter.createdAt = {}
// if (startDate) {
// filter.createdAt.$gte = new Date(startDate) // تاریخ شروع
// }
// if (endDate) {
// filter.createdAt.$lte = new Date(endDate) // تاریخ پایان
// }
// }
// if (status) {
// filter.is_verified = status
// }
// // if (expertise) {
// // filter.expertise = expertise
// // }
// // if (age) {
// // filter.age = age
// // }
// // if (gender) {
// // filter.gender = gender
// // }
// // استفاده از مدل پیجینیت شده برای دریافت نتایج صفحه‌بندی شده
// const options = {
// page: parseInt(page), // تبدیل صفحه به عدد صحیح
// limit: parseInt(limit), // تبدیل محدودیت به عدد صحیح
// sort: { createdAt: -1 }
// }
// const users = await UserModel.paginate(filter, options)
// const newUsers = users.docs.map(user => ({
// _id: user._id,
// mobile: user.mobile,
// user_name: user.user_name,
// first_name: user.first_name,
// last_name: user.last_name,
// user_type: user.user_type,
// is_verified: user.is_verified,
// profile_image: user.profile_image,
// expertise: user.expertise,
// sub_expertise: user.sub_expertise,
// gender: user.gender,
// national_code: user.national_code,
// province: user.province,
// city: user.city,
// last_online: jMoment(user.last_online).format('jYYYY-jMM-jDD HH:mm'),
// createdAt: jMoment(user.createdAt).format('jYYYY-jMM-jDD HH:mm'),
// block_status: user.block_status
// }))
// res.status(200).json({
// users: newUsers,
// totalPages: users.totalPages, // ارسال تعداد کل صفحات
// totalItems: users.totalDocs // ارسال تعداد کل آیتم‌ها
// })
// } catch (error) {
// // در صورت بروز خطا، ارسال پیام خطا به کاربر
// console.error('Error in getProjectTypes:', error)
// res.status(500).json({ message: 'خطا در دریافت انواع پروژه.' })
// }
// }
const getUserDetail = async (req, res, next) => {
try {
const token = req.header('Authorization').split(' ')[1]
if (!token) return res.status(401).send('Access Denied')
const user_id = req.query.user_id
// eslint-disable-next-line no-unused-vars
if (!mongoose.Types.ObjectId.isValid(user_id)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
const user = await UserModel.findById(user_id)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
const response = {
_id: user?._id,
profile_image: user?.profile_image,
first_name: user?.first_name,
last_name: user?.last_name,
user_name: user?.user_name,
mobile: user?.mobile,
national_code: user?.national_code,
province: user?.province,
city: user?.city,
address: user?.address,
height: user?.height,
weight: user?.weight,
size: user?.size,
birthday: user?.birthday,
show_location: user?.show_location,
cooperation_abroad: user?.cooperation_abroad,
conversation_projects: user?.conversation_projects,
expertise: user?.expertise,
sub_expertise: user?.sub_expertise,
shaba: user?.shaba,
national_card_image: user?.national_card_image,
last_online: jMoment(user?.last_online).format('jYYYY-jMM-jDD HH:mm'),
createdAt: jMoment(user?.createdAt).format('jYYYY-jMM-jDD HH:mm'),
block_status: user?.block_status,
user_level: user?.user_level,
user_type: user?.user_type,
user_score: user?.user_score,
services :user?.services,
is_verified: user?.is_verified,
rate: user?.rate,
bio: user?.bio,
eye_color: user?.eye_color,
hair_color: user?.hair_color,
lat: user?.lat,
lng: user?.lng
}
return res.status(200).json({ user: response })
} catch (error) {
next(error)
}
}
const updateUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
// چک کردن اعتبار شناسه کاربر
if (!mongoose.Types.ObjectId.isValid(userId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' })
}
// فیلدهایی که می‌خواهید آپدیت شوند را از درخواست دریافت کنید
const updateFields = req.body
// اجرای آپدیت و بازگشت مقدار آپدیت شده
const updatedUser = await UserModel.findByIdAndUpdate(
userId,
updateFields,
{ new: true }
)
// بررسی آیا کاربر وجود دارد یا نه
if (!updatedUser) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'کاربر با موفقیت ویرایش شد', id: updatedUser._id })
} catch (error) {
const errors = []
if (error.code === 11000) {
// Duplicate key error
for (const key in error.keyValue) {
errors.push({ message: `ارور در فیلد ${key}` })
}
} else {
errors.push({ message: 'خطا در آپدیت کاربر' })
}
res.status(500).json({ errors })
}
}
const verifyUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.is_verified = 'verified';
user.is_Register = true;
await user.save();
const notification = new NotificationModel({
user_id: userId,
type: 'verify',
title: 'تایید مدارک',
description: 'مدارک ارسالی شما با موفقیت تایید شد'
})
await notification.save()
// Sms
const userReciver = await UserModel.findById(userId)
const data = JSON.stringify({
mobile: userReciver?.mobile,
templateId: '632057',
parameters: [
{ name: 'USERS', value: userReciver?.first_name + ' ' + userReciver?.last_name }
]
})
const config = {
method: 'post',
url: 'https://api.sms.ir/v1/send/verify',
headers: {
'Content-Type': 'application/json',
Accept: 'text/plain',
'x-api-key': '2JKxGbTzE64t0YTkjip6RYHnm9mq1haMlidF8WWwQunwubHFVW6iaMmfFQbMXEDt'
},
data
}
axios(config)
.then(function (response) {
})
.catch(function (error) {
console.log(error)
})
// End Sms
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'مدارک کاربر با موفقیت تایید شد' })
} catch (error) {
next(error)
}
}
const updateUserStatus = async (req, res, next) => {
try {
const { userId, block_status } = req.body;
if (!mongoose.Types.ObjectId.isValid(userId)) {
return res.status(400).json({ message: 'شناسه کاربر معتبر نیست' });
}
const user = await UserModel.findByIdAndUpdate(
userId,
{ block_status },
{ new: true }
);
if (!user) return res.status(404).json({ message: 'کاربر یافت نشد' });
res.status(200).json({ message: 'وضعیت کاربر با موفقیت تغییر کرد', block_status: user.block_status });
} catch (error) {
console.error(error);
res.status(500).json({ message: 'خطای سرور' });
}
};
const rejectUser = async (req, res, next) => {
try {
const userId = req.query.userId // دریافت شناسه کاربر از درخواست
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.is_verified = 'rejected'
user.is_Register = false
await user.save()
const notification = new NotificationModel({
user_id: userId,
type: 'reject-user',
title: 'رد مدارک',
description: 'مدارک ارسالی شما رد شد، برای اطلاعات بیشتر از بخش تیکت به پشتیبانی پیام دهید.'
})
await notification.save()
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'مدارک کاربر با موفقیت رد شد' })
} catch (error) {
next(error)
}
}
const changePass = async (req, res, next) => {
try {
const { userId, password } = req.body;
const user = await UserModel.findById(userId)
if (!user) {
return res.status(404).json({ message: 'کاربر مورد نظر یافت نشد' })
}
user.password = password
await user.save()
// ارسال پاسخ با مقادیر آپدیت شده
res.status(200).json({ message: 'رمز عبور با موفقیت تغییر کرد' });
} catch (error) {
next(error)
}
}
module.exports = {
getUsers, getUserDetail, updateUser, verifyUser, rejectUser, updateUserStatus, changePass
}

View File

@@ -1,37 +1,37 @@
const VersionModel = require('../../../models/VersionModel')
// Endpoint برای دریافت نسخه فعلی
const getVersion = async (req, res, next) => {
try {
const currentVersion = await VersionModel.findOne().sort({ _id: -1 }).exec()
if (!currentVersion) {
return res.status(200).json({ message: 'نسخه‌ای پیدا نشد' })
}
res.json(currentVersion)
} catch (error) {
res.status(500).json({ message: 'خطای سرور', error })
}
}
// متد برای ایجاد یا ویرایش نسخه
const upsertVersion = async (req, res, next) => {
try {
const { version, mandatory, releaseNotes, updateUrls } = req.body
if (!version || !Array.isArray(updateUrls) || updateUrls.length === 0) {
return res.status(400).json({ message: 'اطلاعات ناقص است' })
}
// پیدا کردن نسخه‌ای که مشابه باشد و ویرایش یا ایجاد
const updatedVersion = await VersionModel.findOneAndUpdate(
{ version }, // شرط برای پیدا کردن نسخه با همین شماره
{ mandatory, releaseNotes, updateUrls }, // به‌روزرسانی مقادیر
{ new: true, upsert: true } // ایجاد نسخه جدید اگر وجود ندارد
)
res.status(200).json({ message: 'نسخه به‌روزرسانی شد', version: updatedVersion })
} catch (error) {
res.status(500).json({ message: 'خطای سرور', error })
}
}
module.exports = { getVersion, upsertVersion }
const VersionModel = require('../../../models/VersionModel')
// Endpoint برای دریافت نسخه فعلی
const getVersion = async (req, res, next) => {
try {
const currentVersion = await VersionModel.findOne().sort({ _id: -1 }).exec()
if (!currentVersion) {
return res.status(200).json({ message: 'نسخه‌ای پیدا نشد' })
}
res.json(currentVersion)
} catch (error) {
res.status(500).json({ message: 'خطای سرور', error })
}
}
// متد برای ایجاد یا ویرایش نسخه
const upsertVersion = async (req, res, next) => {
try {
const { version, mandatory, releaseNotes, updateUrls } = req.body
if (!version || !Array.isArray(updateUrls) || updateUrls.length === 0) {
return res.status(400).json({ message: 'اطلاعات ناقص است' })
}
// پیدا کردن نسخه‌ای که مشابه باشد و ویرایش یا ایجاد
const updatedVersion = await VersionModel.findOneAndUpdate(
{ version }, // شرط برای پیدا کردن نسخه با همین شماره
{ mandatory, releaseNotes, updateUrls }, // به‌روزرسانی مقادیر
{ new: true, upsert: true } // ایجاد نسخه جدید اگر وجود ندارد
)
res.status(200).json({ message: 'نسخه به‌روزرسانی شد', version: updatedVersion })
} catch (error) {
res.status(500).json({ message: 'خطای سرور', error })
}
}
module.exports = { getVersion, upsertVersion }