transfer project in github
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
const ContactUs = require('../models/ContactUs')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {res404, res500} = require('../plugins/controllersHelperFunctions')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
|
||||
const limit = 20
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name),
|
||||
body('phone')
|
||||
.notEmpty().withMessage(_sr['fa'].required.phone_number)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.phone_number),
|
||||
body('email')
|
||||
.notEmpty().withMessage(_sr['fa'].required.email)
|
||||
.bail()
|
||||
.isEmail().withMessage(_sr['fa'].format.email),
|
||||
body('message')
|
||||
.notEmpty().withMessage(_sr['fa'].required.message)
|
||||
],
|
||||
(req, res) => {
|
||||
const errors = validationResult(req)
|
||||
if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})
|
||||
|
||||
const {name, phone, email, message} = req.body
|
||||
|
||||
const data = {
|
||||
name, phone, email, message, read: false
|
||||
}
|
||||
new ContactUs(data).save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAll = [
|
||||
(req, res) => {
|
||||
const filter = {}
|
||||
ContactUs.paginate(filter, {
|
||||
page: req.query.page || 1,
|
||||
limit,
|
||||
sort : {index : 1}
|
||||
} , (err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
ContactUs.findById(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
data.read = true
|
||||
data.save(err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,217 @@
|
||||
const FoodCategory = require('../models/FoodCategory')
|
||||
const Food = require('../models/Food')
|
||||
const MenuType = require('../models/MenuType')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
const fs = require('fs')
|
||||
const sharp = require('sharp')
|
||||
const StoreInfo = require("../models/StoreInfo");
|
||||
|
||||
// variables
|
||||
const coverWidth = 500
|
||||
const coverHeight = 500
|
||||
const coverQuality = 100
|
||||
const limit = 20
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return FoodCategory.findOne({name: value, branchId: req?.body?.branchId})
|
||||
.then(foodCategory => {
|
||||
if (foodCategory) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('type')
|
||||
.notEmpty().withMessage('نوع منو را انتخاب کنید')
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return MenuType.findOne({_id: value})
|
||||
.then(menuType => {
|
||||
if (!menuType) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (!req.files?.cover) return res.status(422).json({validation: {cover: {msg: _sr['fa'].required.cover}}})
|
||||
if (!_sr.supportedImageFormats.includes(req.files.cover.mimetype.split('/')[1])) return res.status(422).json({validation: {cover: {msg: _sr['fa'].format.image}}})
|
||||
try {
|
||||
const {name, type, index , branchId} = req.body
|
||||
const data = {name, type, index , branchId}
|
||||
|
||||
const cover = req.files.cover
|
||||
const coverName = 'category_' + Date.now() + '.png'
|
||||
data.cover = coverName
|
||||
|
||||
const target = await sharp(cover.data)
|
||||
await target
|
||||
.resize(coverWidth, coverHeight, {fit: 'cover'})
|
||||
.toFormat('png')
|
||||
.png({quality: coverQuality})
|
||||
.toFile(`./static/uploads/images/foodCategories/${coverName}`)
|
||||
|
||||
const foodCategory = new FoodCategory(data)
|
||||
foodCategory.save(err => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_panel = [
|
||||
(req, res) => {
|
||||
const filter = {branchId: req?.params?.branchId}
|
||||
FoodCategory.paginate(filter, {
|
||||
page: req.query.page || 1,
|
||||
limit,
|
||||
populate : 'type',
|
||||
sort : {index : 1}
|
||||
} , (err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_web = [
|
||||
(req, res) => {
|
||||
const branchId = req?.params?.branchId
|
||||
const query = {}
|
||||
if (branchId) query.branchId = branchId
|
||||
FoodCategory.find(query).populate('type').sort({index: 1}).exec((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_one = [
|
||||
(req, res) => {
|
||||
FoodCategory.findById(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.update = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return FoodCategory.findOne({name: value, branchId: req?.body?.branchId})
|
||||
.then(foodCategory => {
|
||||
if (foodCategory && foodCategory._id.toString() !== req.params.id) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('type')
|
||||
.notEmpty().withMessage('نوع منو را انتخاب کنید')
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return MenuType.findOne({_id: value})
|
||||
.then(menuType => {
|
||||
if (!menuType) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (req.files?.cover && !_sr.supportedImageFormats.includes(req.files.cover.mimetype.split('/')[1])) return res.status(422).json({validation: {cover: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
try {
|
||||
const {name, type, index , branchId} = req.body
|
||||
const data = {name, type, index, branchId}
|
||||
|
||||
if (req.files?.cover) {
|
||||
const cover = req?.files?.cover
|
||||
const coverName = 'category_' + Date.now() + '.png'
|
||||
data.cover = coverName
|
||||
|
||||
const target = await sharp(cover.data)
|
||||
await target
|
||||
.resize(coverWidth, coverHeight, {fit: 'cover'})
|
||||
.toFormat('png')
|
||||
.png({quality: coverQuality})
|
||||
.toFile(`./static/uploads/images/foodCategories/${coverName}`)
|
||||
}
|
||||
|
||||
|
||||
FoodCategory.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
if (req.files?.cover) {
|
||||
fs.unlink(`./static/${oldData.cover}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
Food.findOne({category: req.params.id}, (err, food) => {
|
||||
if (err) return res500(res, err)
|
||||
if (food) return res.status(403).json({message: 'نمیتوان دسته بندی هایی که دارای زیر مجموعه هستند را حذف کرد.'})
|
||||
else {
|
||||
FoodCategory.findByIdAndDelete(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
////////////////////////////////////////////// user
|
||||
|
||||
@@ -0,0 +1,488 @@
|
||||
const Food = require('../models/Food')
|
||||
const CartItem = require('../models/CartItem')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const fs = require('fs')
|
||||
const sharp = require('sharp')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {getID} = require('../authentication')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
const StoreInfo = require("../models/StoreInfo");
|
||||
|
||||
///// variables
|
||||
const foodImageWidth = 500
|
||||
const foodImageHeight = 500
|
||||
const foodImageQuality = 100
|
||||
const limit = 20
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// create
|
||||
module.exports.create = [
|
||||
[
|
||||
body('name')
|
||||
.isLength({min: 2}).withMessage(_sr['fa'].min_char.min2)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return Food.findOne({name: value, branchId: req?.body?.branchId})
|
||||
.then(food => {
|
||||
if (food) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('price')
|
||||
.notEmpty().withMessage(_sr['fa'].required.price)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('estimated_time')
|
||||
.if((value, {req}) => value)
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('static_discount')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('special')
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('stock')
|
||||
.notEmpty().withMessage(_sr['fa'].required.quantity)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('category')
|
||||
.notEmpty().withMessage(_sr['fa'].required.category),
|
||||
|
||||
body('havePoint')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('club')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
// body('point')
|
||||
// .custom((value, {req}) => {
|
||||
// if (req.body.club && !Boolean(Number(value))) return Promise.reject('لطفا مقدار امتیاز مورد نیاز برای خرید این محصول را وارد نمایید')
|
||||
// else return true
|
||||
// }),
|
||||
body('sale')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (req.files?.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
const {name, description, short_description, price, stock, static_discount, estimated_time, category, index, special, havePoint, club, point, sale , branchId} = req.body
|
||||
const data = {name, description, short_description, price, stock, static_discount, estimated_time, category, index, special, havePoint, club, point, sale , branchId}
|
||||
|
||||
if (req?.files?.image) {
|
||||
const image = req?.files?.image
|
||||
const imageName = 'food_' + Date.now() + '.png'
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target
|
||||
.resize(foodImageWidth, foodImageHeight, {fit: 'cover'})
|
||||
.toFormat('png')
|
||||
.png({quality: foodImageQuality})
|
||||
.toFile(`./static/uploads/images/food/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
const food = new Food(data)
|
||||
food.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get all
|
||||
module.exports.getAll = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const allFoods = await Food.find({branchId : req?.params?.branchId}).select('-ratings').sort({index: 1});
|
||||
const getCarts = await CartItem.find({branchId: req?.params?.branchId, user_id: req.user._id});
|
||||
|
||||
const clone = JSON.parse(JSON.stringify(allFoods))
|
||||
|
||||
for (const item of clone) {
|
||||
item.quantity = Number(getCarts.find(item2 => item2?.product_id?.toString() === item?._id?.toString())?.quantity) || 0;
|
||||
}
|
||||
|
||||
return res.json(clone);
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAllForWebSite = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const allFoods = await Food.find().select('-ratings').sort({index: 1});
|
||||
return res.json(allFoods);
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAllForPanel = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const allFoods = await Food.paginate({branchId: req?.params?.branchId}, {
|
||||
page: req.query.page || 1,
|
||||
limit,
|
||||
select: '-ratings',
|
||||
sort: {index: 1}
|
||||
});
|
||||
return res.json(allFoods);
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get one
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
Food.findById(req.params.id).populate('ratings.user_id', 'first_name last_name').exec((err, food) => {
|
||||
if (err || !food) return res404(res, `غذای مورد نظر پیدا نشد`)
|
||||
CartItem.findOne({user_id: req.user._id, product_id: req.params.id}).exec((error, cart) => {
|
||||
const clone = JSON.parse(JSON.stringify(food))
|
||||
clone.ratings = clone.ratings.filter(item => item.confirmed === true)
|
||||
let quantity = 0;
|
||||
if (error) return res500(res, _sr['fa'].response.unknownError)
|
||||
if (cart) quantity = cart.quantity
|
||||
|
||||
clone.quantity = quantity;
|
||||
return res.json(clone)
|
||||
})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getOneByAdmin = [
|
||||
(req, res) => {
|
||||
Food.findById(req.params.id).populate('ratings.user_id', 'first_name last_name').exec((err, food) => {
|
||||
if (err || !food) return res404(res, `غذای مورد نظر پیدا نشد`)
|
||||
CartItem.findOne({user_id: req.user._id, product_id: req.params.id}).exec((error, cart) => {
|
||||
const clone = JSON.parse(JSON.stringify(food))
|
||||
let quantity = 0;
|
||||
if (error) return res500(res, _sr['fa'].response.unknownError)
|
||||
if (cart) quantity = cart.quantity
|
||||
|
||||
clone.quantity = quantity;
|
||||
return res.json(clone)
|
||||
})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// update
|
||||
module.exports.update = [
|
||||
[
|
||||
body('name')
|
||||
.isLength({min: 2}).withMessage(_sr['fa'].min_char.min2)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return Food.findOne({name: value, branchId: req?.body?.branchId})
|
||||
.then(food => {
|
||||
if (food && food._id.toString() !== req.params.id) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('price')
|
||||
.notEmpty().withMessage(_sr['fa'].required.price)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('estimated_time')
|
||||
.if((value, {req}) => value)
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('static_discount')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('stock')
|
||||
.notEmpty().withMessage(_sr['fa'].required.quantity)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('category')
|
||||
.notEmpty().withMessage(_sr['fa'].required.category),
|
||||
|
||||
body('havePoint')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('club')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
// body('point')
|
||||
// .custom((value, {req}) => {
|
||||
// if (req.body.club && !Boolean(Number(value))) return Promise.reject('لطفا مقدار امتیاز مورد نیاز برای خرید این محصول را وارد نمایید')
|
||||
// else return true
|
||||
// }),
|
||||
|
||||
body('sale')
|
||||
.optional().isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (req.files?.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
const {name, description, short_description, price, stock, static_discount, estimated_time, category, index, special, havePoint, club, point, sale , branchId} = req.body
|
||||
const data = {name, description, short_description, price, stock, static_discount, estimated_time, category, index, special, havePoint, club, point, sale , branchId}
|
||||
|
||||
if (req.files?.image) {
|
||||
const image = req.files.image
|
||||
const imageName = 'food_' + Date.now() + '.png'
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target
|
||||
.resize(foodImageWidth, foodImageHeight, {fit: 'cover'})
|
||||
.toFormat('png')
|
||||
.png({quality: foodImageQuality})
|
||||
.toFile(`./static/uploads/images/food/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
|
||||
Food.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
if (req.files?.image && oldData.image) {
|
||||
fs.unlink(`./static/${oldData.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// delete
|
||||
module.exports.delete = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const food = await Food.findByIdAndDelete(req.params.id)
|
||||
// if (food.image) {
|
||||
// fs.unlink(`./static/${data.image}`, err => {
|
||||
// if (err) console.log(err)
|
||||
// })
|
||||
// }
|
||||
await CartItem.deleteMany({product_id : food._id})
|
||||
return res.json({message: _sr['fa'].response.success_remove})
|
||||
}catch (error) {
|
||||
return res500(res , _sr['fa'].response.unknownError)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// search
|
||||
module.exports.search = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
let {
|
||||
club,
|
||||
sale,
|
||||
name,
|
||||
category,
|
||||
branchId
|
||||
} = req.body;
|
||||
|
||||
let findQuery = { branchId };
|
||||
findQuery['$and'] = [];
|
||||
findQuery['$or'] = [];
|
||||
|
||||
/** search by name */
|
||||
if (name && !_.isEmpty(name)) {
|
||||
findQuery['$and'].push({
|
||||
name: {
|
||||
$regex: '.*' + name + '.*'
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/** search by sale */
|
||||
if (!_.isUndefined(sale) && _.isBoolean(sale)) {
|
||||
findQuery['$and'].push({
|
||||
sale
|
||||
})
|
||||
}
|
||||
|
||||
/** search by club */
|
||||
if (!_.isUndefined(club) && _.isBoolean(club)) {
|
||||
findQuery['$and'].push({
|
||||
club
|
||||
})
|
||||
}
|
||||
|
||||
/** search by category */
|
||||
if (category && !_.isEmpty(category)) {
|
||||
findQuery['$and'].push({
|
||||
category
|
||||
});
|
||||
}
|
||||
|
||||
_.isEmpty(findQuery['$and']) && delete findQuery['$and'];
|
||||
_.isEmpty(findQuery['$or']) && delete findQuery['$or'];
|
||||
|
||||
/** get news */
|
||||
const orders = await Food.paginate(findQuery, {
|
||||
page: req?.query?.page || 1,
|
||||
limit,
|
||||
populate: [{path: 'user_id', select: 'first_name last_name'}],
|
||||
sort: {
|
||||
_id: -1
|
||||
}
|
||||
});
|
||||
|
||||
/** show result */
|
||||
return res.json(orders);
|
||||
} catch (error) {
|
||||
console.log(error.message)
|
||||
return res500(res, _sr['fa'].response.unknownError)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
/////////////// rate foods
|
||||
module.exports.rate_food = [
|
||||
[
|
||||
body('rate')
|
||||
.notEmpty().withMessage('فیلد رتبه نباید خالی باشد')
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
if (Number(value) < 0) return Promise.reject('مقدار نباید کوچیکتر از 0 باشد')
|
||||
if (Number(value) > 5) return Promise.reject('مقدار نباید بزرگتر از 5 باشد')
|
||||
else return true
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const {rate, comment, orderId} = req.body
|
||||
const data = {rate, comment, order_id: orderId}
|
||||
userID = await getID(req)
|
||||
data.user_id = userID
|
||||
const food = await Food.findById(req.params.id)
|
||||
if (!food) return res404(res, 'غذا پیدا نشد')
|
||||
if (!food?.canReview || !food.canReview.includes(req.user._id)) return res.status(403).json({message: 'شما قبلا نظر خود را ثبت کرده اید'})
|
||||
const index = food.canReview.indexOf(req.user._id);
|
||||
if (index > -1) {
|
||||
food.canReview.splice(index, 1);
|
||||
}
|
||||
food.ratings.push(data)
|
||||
let rateSUM = 0
|
||||
food.ratings.forEach(item => rateSUM += Number(item.rate))
|
||||
food.rate = (rateSUM / food.ratings.length).toFixed(1)
|
||||
food.save(err => {
|
||||
if (err) console.log(err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.confirm_comment_by_admin = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const admin_id = await getID(req)
|
||||
Food.findOne({'ratings._id': req.params.id}, (err, food) => {
|
||||
if (err || !food) return res404(res, 'item id is incorrect')
|
||||
const comment = food.ratings.id(req.params.id)
|
||||
comment.confirmed = req.body.confirmed
|
||||
comment.confirmed_by = admin_id
|
||||
food.save(err => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
})
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.reply_comment_by_admin = [
|
||||
[
|
||||
body('replay')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const targetComment = await Food.findOne({'ratings._id': req.params.id})
|
||||
|
||||
if (!targetComment) return res404(res, `کامنت مورد نظر وجود ندارد`)
|
||||
|
||||
let comment = targetComment.ratings.id(req.params.id)
|
||||
comment.replay = req.body.replay
|
||||
comment.replied_by = req.user._id
|
||||
|
||||
await targetComment.save()
|
||||
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
} catch (e) {
|
||||
console.log(e.message)
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.remove_comment_by_admin = [
|
||||
(req, res) => {
|
||||
Food.findOne({'ratings._id': req.params.id}, (err, food) => {
|
||||
if (err || !food) return res404(res, 'item id is incorrect')
|
||||
const comment = food.ratings.id(req.params.id)
|
||||
comment.remove()
|
||||
food.save(err => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
const Gallery = require('../models/Gallery')
|
||||
const sharp = require('sharp')
|
||||
const fs = require('fs')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
|
||||
///// variables
|
||||
const thumbWidth = 420
|
||||
const thumbHeight = 280
|
||||
const thumbQuality = 80
|
||||
|
||||
const maxCaptionLength = 100
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////// create image
|
||||
module.exports.create = [
|
||||
[
|
||||
body('caption')
|
||||
.exists().withMessage(_sr['fa'].required.caption)
|
||||
],
|
||||
async (req, res) => {
|
||||
////////////// check validation result
|
||||
const errors = validationResult(req)
|
||||
if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})
|
||||
if (!req.files || !req.files.image) return res.status(422).json({validation: {image: {msg: _sr['fa'].required.image}}})
|
||||
if (!_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
|
||||
let image = req.files.image
|
||||
let imageName = 'gallery_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
|
||||
if (image) {
|
||||
//////// validate image format
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target.toFile(`./static/uploads/images/gallery/${imageName}`)
|
||||
await target
|
||||
.resize(thumbWidth, thumbHeight, {fit: 'cover'})
|
||||
.jpeg({quality: thumbQuality})
|
||||
.toFile(`./static/uploads/images/gallery/thumb/thumb_${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
////////////// pass values throw model
|
||||
let gallery = new Gallery({
|
||||
image: imageName,
|
||||
caption: req.body.caption,
|
||||
shortCaption: req.body.caption.slice(0, maxCaptionLength)
|
||||
})
|
||||
gallery.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////// get all images
|
||||
module.exports.getAll = [
|
||||
(req, res) => {
|
||||
Gallery.find({}, (err, images) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json(images)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////// get one image
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
Gallery.findById(req.params.id, (err, image) => {
|
||||
if (err || !image) return res404(res, err)
|
||||
return res.json(image)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////// update image
|
||||
module.exports.update = [
|
||||
[
|
||||
body('caption')
|
||||
.exists().withMessage(_sr['fa'].required.caption)
|
||||
],
|
||||
async (req, res) => {
|
||||
////////////// check validation result
|
||||
const errors = validationResult(req)
|
||||
if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})
|
||||
|
||||
let data = {}
|
||||
data.caption = req.body.caption.slice(0, maxCaptionLength) + ' ... '
|
||||
/////
|
||||
if (req.files?.image) {
|
||||
let image = req.files.image
|
||||
let imageName = 'gallery_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
|
||||
//////// validate image format
|
||||
if (!_sr.supportedImageFormats.includes(image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target.toFile(`./static/uploads/images/gallery/${imageName}`)
|
||||
await target
|
||||
.resize(thumbWidth, thumbHeight, {fit: 'cover'})
|
||||
.jpeg({quality: thumbQuality})
|
||||
.toFile(`./static/uploads/images/gallery/thumb/thumb_${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
////////////// pass values throw model
|
||||
Gallery.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
if (req.files?.image) {
|
||||
fs.unlink(`./static/${oldData.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
fs.unlink(`./static/${oldData.thumb}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////////////////// delete image
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
Gallery.findByIdAndRemove(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
fs.unlink(`./static/${data.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
fs.unlink(`./static/${data.thumb}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,103 @@
|
||||
const Job = require('../models/Job')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
|
||||
const limit = 20
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return Job.findOne({name: value})
|
||||
.then(menuType => {
|
||||
if (menuType) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
(req, res) => {
|
||||
const job = new Job(req.body)
|
||||
job.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_panel = [
|
||||
(req, res) => {
|
||||
const filter = {}
|
||||
Job.paginate(filter, {
|
||||
page: req.query.page,
|
||||
limit,
|
||||
sort: {index: 1}
|
||||
}, (err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_mobile = [
|
||||
(req, res) => {
|
||||
Job.find().sort({index: 1}).exec((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_one = [
|
||||
(req, res) => {
|
||||
Job.findById(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.update = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return Job.findOne({name: value})
|
||||
.then(menuType => {
|
||||
if (menuType && menuType._id.toString() !== req.params.id) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
(req, res) => {
|
||||
Job.findByIdAndUpdate(req.params.id, req.body, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
Job.findByIdAndDelete(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,142 @@
|
||||
const MenuType = require('../models/MenuType')
|
||||
const FoodCategory = require('../models/FoodCategory')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
const StoreInfo = require('../models/StoreInfo');
|
||||
|
||||
|
||||
const limit = 20
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return MenuType.findOne({name: value , branchId: req?.body?.branchId})
|
||||
.then(menuType => {
|
||||
if (menuType) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
(req, res) => {
|
||||
const menuType = new MenuType(req.body)
|
||||
menuType.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_panel = [
|
||||
(req, res) => {
|
||||
const filter = {branchId : req?.params?.branchId}
|
||||
MenuType.paginate(filter, {
|
||||
page: req.query.page,
|
||||
limit,
|
||||
sort : {index : 1}
|
||||
} , (err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_for_web = [
|
||||
(req, res) => {
|
||||
MenuType.find({branchId: req?.params?.branchId ,isCafeMenu:false}).sort({index: 1}).exec((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_all_wihout_paginate = [
|
||||
(req, res) => {
|
||||
MenuType.find({branchId : req?.params?.branchId}).sort({index: 1}).exec((err, data) => {
|
||||
if (err) return res500(res, err?.message)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.get_one = [
|
||||
(req, res) => {
|
||||
MenuType.findById(req?.params?.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.update = [
|
||||
[
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return MenuType.findOne({name: value , branchId: req?.body?.branchId})
|
||||
.then(menuType => {
|
||||
if (menuType && menuType._id.toString() !== req.params.id) return Promise.reject(_sr['fa'].duplicated.name)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('branchId')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return StoreInfo.findOne({_id: value})
|
||||
.then(store => {
|
||||
if (!store) return Promise.reject(_sr['fa'].not_found.item_id)
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
(req, res) => {
|
||||
MenuType.findByIdAndUpdate(req?.params?.id, req.body, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
else return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
FoodCategory.findOne({type: req.params.id}, (err, category) => {
|
||||
if (err) return res500(res, err)
|
||||
if (category) return res.status(403).json({message: 'نمیتوان منوهایی که شامل زیرمجموعه هستند را حذف کرد.'})
|
||||
else {
|
||||
MenuType.findByIdAndDelete(req.params.id, (err1, data) => {
|
||||
if (err1 || !data) return res404(res, err1)
|
||||
else return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,97 @@
|
||||
const User = require('./../models/User')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {sendSingle , sendMulti} = require('./../plugins/pushNotif').notification
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
|
||||
module.exports.send = [
|
||||
[
|
||||
body('multi')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('title')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field),
|
||||
|
||||
body('body')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field),
|
||||
|
||||
body('user_id')
|
||||
.if((value, {req})=>{
|
||||
return req.body.user_id
|
||||
})
|
||||
.custom((value,{req})=>{
|
||||
return User.findById(value)
|
||||
.then(user => {
|
||||
if (!user) return Promise.reject('کاربر وجود ندارد یا حذف شده است')
|
||||
else return true
|
||||
})
|
||||
})
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const {multi , user_id , title , body} = req.body
|
||||
|
||||
const objNotif = {
|
||||
title,
|
||||
body
|
||||
}
|
||||
|
||||
if(multi){
|
||||
const fcmTokens = []
|
||||
const users = await User.find({scope: 'user'})
|
||||
|
||||
for (const user of users) {
|
||||
if (user.fcmToken) fcmTokens.push(user.fcmToken)
|
||||
}
|
||||
|
||||
const payload = {
|
||||
notification: objNotif,
|
||||
// data: {
|
||||
// routeName: 'test',
|
||||
// type: "bazaar",
|
||||
// routeType: "viewBazaar",
|
||||
// },
|
||||
};
|
||||
|
||||
const input = {
|
||||
registrationTokens: fcmTokens,
|
||||
payload
|
||||
}
|
||||
|
||||
const status = await sendMulti(input)
|
||||
|
||||
// if (!status) return res500(res , _sr['fa'].response.unknownError)
|
||||
|
||||
return res.json({message : 'با موفقیت ارسال شد'})
|
||||
}else {
|
||||
const user = await User.findById(user_id)
|
||||
|
||||
const payload = {
|
||||
notification: objNotif,
|
||||
// data: {
|
||||
// routeName: 'test',
|
||||
// type: "bazaar",
|
||||
// routeType: "viewBazaar",
|
||||
// },
|
||||
};
|
||||
|
||||
const input = {
|
||||
registrationTokens: user?.fcmToken || '',
|
||||
payload
|
||||
}
|
||||
|
||||
const status = await sendSingle(input)
|
||||
|
||||
// if (!status) return res500(res , _sr['fa'].response.unknownError)
|
||||
|
||||
return res.json({message : 'با موفقیت ارسال شد'})
|
||||
}
|
||||
}catch (error) {
|
||||
return res500(res , _sr['fa'].response.unknownError)
|
||||
}
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,48 @@
|
||||
const {res404, res500} = require('./../plugins/controllersHelperFunctions')
|
||||
const {_sr} = require('./../plugins/serverResponses')
|
||||
let server = null
|
||||
global.io = null
|
||||
module.exports.send = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
if (!server) {
|
||||
server = res.connection.server
|
||||
io = socket(server)
|
||||
io.on('connection', async function (socket) {
|
||||
|
||||
socket.on('order', msg => {
|
||||
io.emit('order', {
|
||||
input: msg?.input,
|
||||
userId: req?.user?._id
|
||||
});
|
||||
})
|
||||
|
||||
socket.on('disconnect', () => {
|
||||
console.log('user disconnected');
|
||||
});
|
||||
})
|
||||
}
|
||||
return res.json({msg: 'server is set'})
|
||||
} catch (error) {
|
||||
console.log(error.message)
|
||||
return res500(res, _sr['fa'].response.unknownError)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.test = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
|
||||
io.emit('order', {
|
||||
|
||||
});
|
||||
|
||||
return res.json('test')
|
||||
|
||||
} catch (e) {
|
||||
console.log(e.message)
|
||||
return res500(res, _sr['fa'].response.problem)
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,180 @@
|
||||
const PartySet = require('../models/PartySet')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const sharp = require('sharp')
|
||||
const fs = require('fs')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
///// variables
|
||||
const foodImageWidth = 500
|
||||
const foodImageHeight = 500
|
||||
const foodImageQuality = 100
|
||||
const limit = 20
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// create
|
||||
module.exports.create = [
|
||||
[
|
||||
body('title')
|
||||
.isLength({min: 2}).withMessage(_sr['fa'].min_char.min2)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return PartySet.findOne({title: value})
|
||||
.then(item => {
|
||||
if (item) return Promise.reject(_sr['fa'].duplicated.title)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('price')
|
||||
.notEmpty().withMessage(_sr['fa'].required.price)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('description')
|
||||
.notEmpty().withMessage(_sr['fa'].required.description)
|
||||
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (req.files?.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
const {title, description, active, index} = req.body
|
||||
const data = {title, description, active, index}
|
||||
data.price = Number(req.body.price)
|
||||
|
||||
if (req.files?.image) {
|
||||
const image = req.files.image
|
||||
const imageName = 'partySet_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target.jpeg({quality: foodImageQuality}).resize(foodImageWidth, foodImageHeight, {fit: 'cover'}).toFile(`./static/uploads/images/partySet/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
const partySet = new PartySet(data)
|
||||
partySet.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get all
|
||||
module.exports.getAll = [
|
||||
(req, res) => {
|
||||
PartySet.find({active: true}).sort({index: 1}).exec((err, foods) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json(foods)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAll_for_admin = [
|
||||
(req, res) => {
|
||||
const filter = {}
|
||||
PartySet.paginate(filter, {
|
||||
page: req.query.page || 1,
|
||||
limit,
|
||||
sort : {index : 1}
|
||||
} , (err, foods) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json(foods)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get one
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
PartySet.findById(req.params.id, (err, food) => {
|
||||
if (err || !food) return res404(res, err)
|
||||
return res.json(food)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// update
|
||||
module.exports.update = [
|
||||
[
|
||||
body('title')
|
||||
.isLength({min: 2}).withMessage(_sr['fa'].min_char.min2)
|
||||
.bail()
|
||||
.custom((value, {req}) => {
|
||||
return PartySet.findOne({title: value})
|
||||
.then(item => {
|
||||
if (item && item._id.toString() !== req.params.id) return Promise.reject(_sr['fa'].duplicated.title)
|
||||
else return true
|
||||
})
|
||||
}),
|
||||
|
||||
body('index')
|
||||
.notEmpty().withMessage(_sr['fa'].required.index)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('price')
|
||||
.notEmpty().withMessage(_sr['fa'].required.price)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('description')
|
||||
.notEmpty().withMessage(_sr['fa'].required.description)
|
||||
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
if (req.files?.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
const {title, description, active, index} = req.body
|
||||
const data = {title, description, active, index}
|
||||
data.price = Number(req.body.price)
|
||||
|
||||
if (req.files?.image) {
|
||||
const image = req.files.image
|
||||
const imageName = 'partySet_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target
|
||||
.resize(foodImageWidth, foodImageHeight, {fit: 'cover'})
|
||||
.jpeg({quality: foodImageQuality})
|
||||
.toFile(`./static/uploads/images/partySet/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
|
||||
PartySet.findByIdAndUpdate(req.params.id, data, (err, oldData) => {
|
||||
if (err || !oldData) return res404(res, err)
|
||||
if (req.files && req.files.image && oldData.image) {
|
||||
fs.unlink(`./static/${oldData.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// delete
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
PartySet.findByIdAndRemove(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
if (data.image) {
|
||||
fs.unlink(`./static/${data.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
const Slide = require('../models/Slide')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const sharp = require('sharp')
|
||||
const fs = require('fs')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, re500} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
////// variables
|
||||
const maxCaptionLength = 65
|
||||
|
||||
const slideImageWidth = 1920
|
||||
const slideImageHeight = 1080
|
||||
const slideImageQuality = 100
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// create
|
||||
module.exports.create = [
|
||||
async (req, res) => {
|
||||
if (!req.files || !req.files.image) return res.status(422).json({validation: {image: {msg: _sr['fa'].required.image}}})
|
||||
if (req.files && req.files.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
let image = req.files.image
|
||||
let imageName = 'slide_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
|
||||
const data = {
|
||||
caption: req.body.caption.slice(0, maxCaptionLength),
|
||||
image: imageName
|
||||
}
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target
|
||||
.resize(slideImageWidth, slideImageHeight, {fit: 'cover'})
|
||||
.jpeg({quality: slideImageQuality})
|
||||
.toFile(`./static/uploads/images/slider/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
|
||||
const slider = new Slide(data)
|
||||
slider.save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get all
|
||||
module.exports.getAll = [
|
||||
(req, res) => {
|
||||
Slide.find({}, (err, slides) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json(slides)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// get one
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
Slide.findById(req.params.id, (err, slide) => {
|
||||
if (err || !slide) return res404(res, err)
|
||||
return res.json(slide)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// update
|
||||
module.exports.update = [
|
||||
async (req, res) => {
|
||||
if (req.files && req.files.image && !_sr.supportedImageFormats.includes(req.files.image.mimetype.split('/')[1])) return res.status(422).json({validation: {image: {msg: _sr['fa'].format.image}}})
|
||||
|
||||
const data = {caption: req.body.caption.slice(0, maxCaptionLength)}
|
||||
|
||||
if (req.files && req.files.image) {
|
||||
let image = req.files.image
|
||||
let imageName = 'slide_' + Date.now() + '.' + image.mimetype.split('/')[1]
|
||||
data.image = imageName
|
||||
try {
|
||||
const target = sharp(image.data)
|
||||
await target
|
||||
.resize(slideImageWidth, slideImageHeight, {fit: 'cover'})
|
||||
.jpeg({quality: slideImageQuality})
|
||||
.toFile(`./static/uploads/images/slider/${imageName}`)
|
||||
} catch (e) {
|
||||
return res500(res, e)
|
||||
}
|
||||
}
|
||||
|
||||
Slide.findByIdAndUpdate(req.params.id, data, (err, oldSlide) => {
|
||||
if (err || !oldSlide) return res404(res, err)
|
||||
if (req.files && req.files.image) {
|
||||
fs.unlink(`./static/${oldSlide.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// delete
|
||||
module.exports.delete = [
|
||||
(req, res) => {
|
||||
Slide.findByIdAndRemove(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
fs.unlink(`./static/${data.image}`, err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
return res.json({message: _sr['fa'].response.success_remove})
|
||||
})
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,436 @@
|
||||
const StoreInfo = require('../models/StoreInfo')
|
||||
const CartItem = require('../models/CartItem')
|
||||
const DiscountCode = require('../models/DiscountCode')
|
||||
const Food = require('../models/Food')
|
||||
const FoodCategory = require('../models/FoodCategory')
|
||||
const MenuType = require('../models/MenuType')
|
||||
const Order = require('../models/Order')
|
||||
const User = require('../models/User')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
///// variable
|
||||
const timeZone = "Asia/Tehran"
|
||||
|
||||
///// functions
|
||||
const convertTimeToUTC = (time, timezone) => {
|
||||
// const date = new Date(new Date().toLocaleString("en-US", {timeZone: timezone}))
|
||||
try {
|
||||
const date = new Date()
|
||||
const year = date.getFullYear()
|
||||
const month = date.getMonth() + 1
|
||||
const day = date.getDate()
|
||||
const makeDate = `${year}-${month}-${day} ${time}`
|
||||
const newDate = new Date(new Date(makeDate).toLocaleString("en-US", {timeZone: timezone}))
|
||||
return `${newDate.getUTCHours() || '00'}:${newDate.getUTCMinutes() || '00'}`
|
||||
} catch (e) {
|
||||
return '00:00'
|
||||
}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// admin
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('title')
|
||||
.notEmpty().withMessage(_sr['fa'].required.title),
|
||||
|
||||
body('caption')
|
||||
.notEmpty().withMessage(`نوع فیلد ارسالی نادرست می باشد`),
|
||||
|
||||
body('email')
|
||||
.isEmail().withMessage(_sr['fa'].format.email),
|
||||
|
||||
body('shippingCost')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('shippingType')
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('tax')
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('tel')
|
||||
.notEmpty().withMessage(_sr['fa'].required.phone_number)
|
||||
.bail()
|
||||
.isString().withMessage(_sr['fa'].format.phone_number),
|
||||
|
||||
body('address')
|
||||
.notEmpty().withMessage(_sr['fa'].required.address)
|
||||
.bail()
|
||||
.isString().withMessage(`آدرس از نوع رشته می باشد`),
|
||||
|
||||
body('location')
|
||||
.isObject().withMessage(`لوکیشن از نوع آبجکت می باشد`),
|
||||
|
||||
body('socials')
|
||||
.isObject().withMessage(`شبکه های اجتماعی از نوع آبجکت می باشد`),
|
||||
|
||||
body('firstStartTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('firstEndTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('secondStartTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('secondEndTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const {title, caption, email, shippingCost, shippingType, tax, tel, address, location, socials, firstStartTime, firstEndTime, secondStartTime , secondEndTime, timezone, closeStore, message , usePointWhenPay , userRegistrationScore , userEmailVerifyScore , pointBirthDate , pointMarriageDate , invitePoint , totalPricePoint , pointForBuy, priceForChange , pointForChange, limitPrice,useSpecialMenu,updateApp} = req.body;
|
||||
|
||||
const utcStartTime = convertTimeToUTC(firstStartTime, timezone)
|
||||
const utcEndTime = convertTimeToUTC(firstEndTime, timezone)
|
||||
|
||||
const data = {title, caption, message, email, shippingCost, shippingType, tax, tel, address, location, socials, firstStartTime, firstEndTime, secondStartTime , secondEndTime, timezone: timeZone, closeStore, utcEndTime, utcStartTime,pointForBuy,totalPricePoint , priceForChange , pointForChange , limitPrice,updateApp,useSpecialMenu};
|
||||
|
||||
|
||||
const add = await StoreInfo.create(data);
|
||||
|
||||
if (!add) return res500(res, _sr['fa'].response.unknownError);
|
||||
|
||||
// global.userRegistrationScore = userRegistrationScore
|
||||
// global.userEmailVerifyScore = userEmailVerifyScore
|
||||
// global.pointBirthDate = pointBirthDate
|
||||
// global.pointMarriageDate = pointMarriageDate
|
||||
// global.invitePoint = invitePoint
|
||||
// global.pointForBuy = pointForBuy
|
||||
// global.totalPricePoint = totalPricePoint
|
||||
// global.pricePoint = Math.floor(priceForChange/pointForChange)
|
||||
|
||||
return res.json({message: _sr['fa'].response.success_save});
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.update = [
|
||||
[
|
||||
body('title')
|
||||
.notEmpty().withMessage(_sr['fa'].required.title),
|
||||
|
||||
body('caption')
|
||||
.notEmpty().withMessage(`نوع فیلد ارسالی نادرست می باشد`),
|
||||
|
||||
body('email')
|
||||
.isEmail().withMessage(_sr['fa'].format.email),
|
||||
|
||||
body('shippingCost')
|
||||
.notEmpty().withMessage(_sr['fa'].required.field)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.number),
|
||||
|
||||
body('shippingType')
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('tax')
|
||||
.isBoolean().withMessage(_sr['fa'].format.boolean),
|
||||
|
||||
body('tel')
|
||||
.notEmpty().withMessage(_sr['fa'].required.phone_number)
|
||||
.bail()
|
||||
.isString().withMessage(_sr['fa'].format.phone_number),
|
||||
|
||||
body('address')
|
||||
.notEmpty().withMessage(_sr['fa'].required.address)
|
||||
.bail()
|
||||
.isString().withMessage(`آدرس از نوع رشته می باشد`),
|
||||
|
||||
body('location')
|
||||
.isObject().withMessage(`لوکیشن از نوع آبجکت می باشد`),
|
||||
|
||||
body('socials')
|
||||
.isObject().withMessage(`شبکه های اجتماعی از نوع آبجکت می باشد`),
|
||||
|
||||
body('firstStartTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('firstEndTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('secondStartTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
|
||||
body('secondEndTime')
|
||||
.custom((value, {req}) => {
|
||||
if (req.body.closeStore) return true
|
||||
else return Promise.resolve(_sr['fa'].required.field)
|
||||
}),
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
async (req, res) => {
|
||||
try {
|
||||
const {title, caption, email, shippingCost, shippingType, tax, tel, address, location, socials, firstStartTime, firstEndTime, secondStartTime , secondEndTime, timezone, closeStore, message , usePointWhenPay , userRegistrationScore , userEmailVerifyScore , pointBirthDate , pointMarriageDate , invitePoint , totalPricePoint , pointForBuy, priceForChange , pointForChange, limitPrice,useSpecialMenu,updateApp} = req.body;
|
||||
const id = req?.params?.id
|
||||
|
||||
const utcStartTime = convertTimeToUTC(firstStartTime, timezone)
|
||||
const utcEndTime = convertTimeToUTC(firstEndTime, timezone)
|
||||
|
||||
const checkStoreInfo = await StoreInfo.findOne({_id : id});
|
||||
|
||||
if (!checkStoreInfo) return res404(res , 'شعبه مورد نظر پیدا نشد')
|
||||
|
||||
|
||||
checkStoreInfo.title = title
|
||||
checkStoreInfo.caption = caption
|
||||
checkStoreInfo.message = message
|
||||
checkStoreInfo.email = email
|
||||
checkStoreInfo.shippingCost = shippingCost
|
||||
checkStoreInfo.shippingType = shippingType
|
||||
checkStoreInfo.tax = tax
|
||||
checkStoreInfo.tel = tel
|
||||
checkStoreInfo.address = address
|
||||
checkStoreInfo.location = location
|
||||
checkStoreInfo.socials = socials
|
||||
checkStoreInfo.firstStartTime = firstStartTime
|
||||
checkStoreInfo.firstEndTime = firstEndTime
|
||||
checkStoreInfo.secondStartTime = secondStartTime
|
||||
checkStoreInfo.secondEndTime = secondEndTime
|
||||
checkStoreInfo.timezone = timezone
|
||||
checkStoreInfo.closeStore = closeStore
|
||||
checkStoreInfo.utcStartTime = utcStartTime
|
||||
checkStoreInfo.utcEndTime = utcEndTime
|
||||
checkStoreInfo.usePointWhenPay = usePointWhenPay
|
||||
checkStoreInfo.userRegistrationScore = userRegistrationScore
|
||||
checkStoreInfo.userEmailVerifyScore = userEmailVerifyScore
|
||||
checkStoreInfo.pointBirthDate = pointBirthDate
|
||||
checkStoreInfo.pointMarriageDate = pointMarriageDate
|
||||
checkStoreInfo.invitePoint = invitePoint
|
||||
checkStoreInfo.totalPricePoint = totalPricePoint
|
||||
checkStoreInfo.pointForBuy = pointForBuy
|
||||
checkStoreInfo.priceForChange = priceForChange
|
||||
checkStoreInfo.pointForChange = pointForChange
|
||||
checkStoreInfo.limitPrice = limitPrice
|
||||
checkStoreInfo.useSpecialMenu = useSpecialMenu
|
||||
checkStoreInfo.updateApp = updateApp
|
||||
|
||||
await checkStoreInfo.save();
|
||||
|
||||
// global.userRegistrationScore = userRegistrationScore
|
||||
// global.userEmailVerifyScore = userEmailVerifyScore
|
||||
// global.pointBirthDate = pointBirthDate
|
||||
// global.pointMarriageDate = pointMarriageDate
|
||||
// global.invitePoint = invitePoint
|
||||
// global.totalPricePoint = totalPricePoint
|
||||
// global.pointForBuy = pointForBuy
|
||||
// global.pricePoint = Math.floor(priceForChange/pointForChange)
|
||||
|
||||
return res.json({message: _sr['fa'].response.success_save});
|
||||
// } else {
|
||||
// const data = {title, caption, message, email, shippingCost, shippingType, tax, tel, address, location, socials, firstStartTime, firstEndTime, secondStartTime , secondEndTime, timezone: timeZone, closeStore, utcEndTime, utcStartTime,pointForBuy,totalPricePoint , priceForChange , pointForChange , limitPrice,updateApp,useSpecialMenu};
|
||||
//
|
||||
//
|
||||
// const add = await StoreInfo.create(data);
|
||||
//
|
||||
// if (!add) return res500(res, _sr['fa'].response.unknownError);
|
||||
//
|
||||
// // global.userRegistrationScore = userRegistrationScore
|
||||
// // global.userEmailVerifyScore = userEmailVerifyScore
|
||||
// // global.pointBirthDate = pointBirthDate
|
||||
// // global.pointMarriageDate = pointMarriageDate
|
||||
// // global.invitePoint = invitePoint
|
||||
// // global.pointForBuy = pointForBuy
|
||||
// // global.totalPricePoint = totalPricePoint
|
||||
// // global.pricePoint = Math.floor(priceForChange/pointForChange)
|
||||
//
|
||||
// return res.json({message: _sr['fa'].response.success_save});
|
||||
// }
|
||||
} catch (error) {
|
||||
console.log(error)
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getOne = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const id = req?.params?.id
|
||||
const targetStoreInfo = await StoreInfo.findOne({_id: id});
|
||||
|
||||
if (targetStoreInfo) {
|
||||
return res.json(targetStoreInfo);
|
||||
} else {
|
||||
return res.json({
|
||||
caption: '',
|
||||
message: '',
|
||||
email: '',
|
||||
shippingCost: 0,
|
||||
shippingType: true,
|
||||
tax: true,
|
||||
tel: '',
|
||||
address: '',
|
||||
location: {},
|
||||
socials: {},
|
||||
closeStore: false,
|
||||
startTime: '',
|
||||
endTime: '',
|
||||
utcStartTime: '',
|
||||
utcEndTime: '',
|
||||
usePointWhenPay: false,
|
||||
userRegistrationScore: 0,
|
||||
userEmailVerifyScore: 0,
|
||||
pointBirthDate: 0,
|
||||
pointMarriageDate: 0,
|
||||
invitePoint: 0,
|
||||
totalPricePoint: 0,
|
||||
priceForChange: 0,
|
||||
pointForChange: 0,
|
||||
minBuy: 0,
|
||||
useSpecialMenu : true,
|
||||
updateApp : ''
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAll = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const ids = req?.user?.branches
|
||||
|
||||
const filter = (req.user.private === true && req.user?.permissions?.includes('super-admin')) ? {} : {_id : {$in : ids}}
|
||||
// const query = {}
|
||||
// if (ids?.length) query._id = {$in : ids}
|
||||
|
||||
const targetStoreInfo = await StoreInfo.find(filter);
|
||||
|
||||
return res.json(targetStoreInfo);
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.addBranchIdForAllData=[
|
||||
async (req, res) => {
|
||||
try {
|
||||
|
||||
const getStore = await StoreInfo.findOne()
|
||||
|
||||
if (getStore){
|
||||
const queries = [
|
||||
CartItem.updateMany({} , {branchId : getStore?._id}),
|
||||
DiscountCode.updateMany({} , {branchId : getStore?._id}),
|
||||
Food.updateMany({} , {branchId : getStore?._id}),
|
||||
FoodCategory.updateMany({} , {branchId : getStore?._id}),
|
||||
MenuType.updateMany({} , {branchId : getStore?._id}),
|
||||
Order.updateMany({} , {branchId : getStore?._id}),
|
||||
User.updateMany({} , { branches: [getStore?._id] , currentBranch : getStore?._id})
|
||||
]
|
||||
//scope: ['user']} ,
|
||||
await Promise.all(queries)
|
||||
}
|
||||
|
||||
return res.json({message : _sr['fa'].response.success_save})
|
||||
}catch (e) {
|
||||
console.log(e.message)
|
||||
return res500(res , e.message)
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////////// public
|
||||
|
||||
module.exports.getStoreInfoForUser = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const id = req?.params?.id
|
||||
|
||||
const query = {}
|
||||
if (id) query._id = id
|
||||
|
||||
const targetStoreInfo = await StoreInfo.findOne(query).select('title message email tel address socials' +
|
||||
' closeStore' +
|
||||
' firstStartTime firstEndTime secondStartTime secondEndTime utcStartTime utcEndTime usePointWhenPay caption limitPrice useSpecialMenu updateApp');
|
||||
|
||||
let clone = JSON.parse(JSON.stringify(targetStoreInfo))
|
||||
|
||||
if (clone) {
|
||||
const date = new Date()
|
||||
const year = date.getFullYear()
|
||||
const month = date.getMonth() + 1
|
||||
const day = date.getDate()
|
||||
const currentDate = new Date().toISOString()
|
||||
const makeFirstStartDate = new Date(`${year}-${month}-${day} ${clone.firstStartTime}:00`).toISOString()
|
||||
const makeFirstEndDate = new Date(`${year}-${month}-${day} ${clone.firstEndTime === '00:00' ? '24:00' : clone.firstEndTime}:00`).toISOString()
|
||||
const makeSecondStartDate = new Date(`${year}-${month}-${day} ${clone.secondStartTime}:00`).toISOString()
|
||||
const makeSecondEndDate = new Date(`${year}-${month}-${day} ${clone.secondEndTime === '00:00' ? '24:00' : clone.secondEndTime}:00`).toISOString()
|
||||
|
||||
if (!clone.closeStore){
|
||||
if (((currentDate > makeFirstStartDate) && (currentDate < makeFirstEndDate)) || ((currentDate > makeSecondStartDate) && (currentDate < makeSecondEndDate))){
|
||||
clone.openNow = true
|
||||
}else {
|
||||
clone.openNow = false
|
||||
}
|
||||
}else {
|
||||
clone.openNow = false
|
||||
}
|
||||
|
||||
return res.json(clone);
|
||||
} else {
|
||||
return res.json({
|
||||
title: '',
|
||||
message: '',
|
||||
email: '',
|
||||
tel: '',
|
||||
address: '',
|
||||
socials: {},
|
||||
openNow: false,
|
||||
});
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
console.log(error.message)
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAllBranchForUser = [
|
||||
async (req, res) => {
|
||||
try {
|
||||
const targetStoreInfo = await StoreInfo.find().select('title message email tel address socials' +
|
||||
' closeStore' +
|
||||
' firstStartTime firstEndTime secondStartTime secondEndTime utcStartTime utcEndTime usePointWhenPay caption limitPrice useSpecialMenu updateApp');
|
||||
|
||||
return res.json(targetStoreInfo);
|
||||
} catch (error) {
|
||||
return res500(res, _sr['fa'].response.unknownError);
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,60 @@
|
||||
const Subscribers = require('../models/Subscribers')
|
||||
const {body, validationResult} = require('express-validator')
|
||||
const {_sr} = require('../plugins/serverResponses')
|
||||
const {res404, res500, checkValidations} = require('../plugins/controllersHelperFunctions')
|
||||
|
||||
module.exports.create = [
|
||||
[
|
||||
body('full_name')
|
||||
.notEmpty().withMessage(_sr['fa'].required.name),
|
||||
body('birth_date')
|
||||
.notEmpty().withMessage(_sr['fa'].required.birthdate),
|
||||
body('email')
|
||||
.notEmpty().withMessage(_sr['fa'].required.email)
|
||||
.bail()
|
||||
.isEmail().withMessage(_sr['fa'].format.email),
|
||||
body('mobile')
|
||||
.notEmpty().withMessage(_sr['fa'].required.phone_number)
|
||||
.bail()
|
||||
.isNumeric().withMessage(_sr['fa'].format.phone_number),
|
||||
body('address')
|
||||
.notEmpty().withMessage(_sr['fa'].required.address)
|
||||
],
|
||||
checkValidations(validationResult),
|
||||
(req, res) => {
|
||||
const {full_name, birth_date, job, marrage_date, email, mobile, address} = req.body
|
||||
const data = {full_name, birth_date, job, marrage_date, email, mobile, address}
|
||||
|
||||
new Subscribers(data).save((err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
return res.json({message: _sr['fa'].response.success_save})
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getAll = [
|
||||
(req, res) => {
|
||||
Subscribers.find({}, (err, data) => {
|
||||
if (err) return res500(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.deleteOne = [
|
||||
(req, res) => {
|
||||
Subscribers.findByIdAndRemove(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
|
||||
module.exports.getOne = [
|
||||
(req, res) => {
|
||||
Subscribers.findById(req.params.id, (err, data) => {
|
||||
if (err || !data) return res404(res, err)
|
||||
else return res.json(data)
|
||||
})
|
||||
}
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user