transfer project in github
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
const axios = require('axios')
|
||||
module.exports.sms = async (phoneNumber, message) => {
|
||||
try {
|
||||
|
||||
// get token
|
||||
const getToken = await axios.post('https://RestfulSms.com/api/Token', {
|
||||
UserApiKey: '4d1a116be65a637f9a8636c5',
|
||||
SecretKey: 'BargRestaurant@A!@#'
|
||||
})
|
||||
|
||||
if (!getToken.data.IsSuccessful) {
|
||||
return false
|
||||
}
|
||||
|
||||
const token = getToken.data.TokenKey
|
||||
|
||||
//get lines
|
||||
const getLineNumber = await axios.get('https://RestfulSms.com/api/SMSLine', {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-sms-ir-secure-token': token
|
||||
}
|
||||
})
|
||||
|
||||
// message details
|
||||
const data = {
|
||||
Messages: [message],
|
||||
MobileNumbers:Array.isArray(phoneNumber) ? phoneNumber : [phoneNumber],
|
||||
LineNumber : getLineNumber.data.SMSLines[0].LineNumber,
|
||||
SendDateTime: '',
|
||||
CanContinueInCaseOfError: 'false'
|
||||
}
|
||||
|
||||
return axios.post(`http://RestfulSms.com/api/MessageSend`, data, {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'x-sms-ir-secure-token': token
|
||||
}
|
||||
})
|
||||
} catch (e) {
|
||||
console.log(e)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
const jwt = require('jsonwebtoken')
|
||||
const User = require('./models/User')
|
||||
|
||||
const authentication = {
|
||||
// secret for generating jwt token
|
||||
secretKey: 'e0e8d636461367747ae3db04ca27a50ce141795c782e3999b8663cd92acf6fafad3d6c9655e1604ab2d6cc3c1b1272d588738ea3c2180542974eb02e017b4322',
|
||||
// check if just logged in (admin-or-user) (middleware)
|
||||
isLoggedIn: function (req, res, next) {
|
||||
const token = req?.headers?.authorization?.replace(/^Bearer\s/, '')
|
||||
if (token) {
|
||||
// check if token is not destroyed
|
||||
User.findOne({token: token}, (err, user) => {
|
||||
if (err) throw err
|
||||
if (user) {
|
||||
// verifies secret and checks if the token is expired
|
||||
jwt.verify(user.token.replace(/^Bearer\s/, ''), authentication.secretKey, (err, decoded) => {
|
||||
if (err) return res.status(401).json({message: 'unauthorized'})
|
||||
else {
|
||||
req.user = {
|
||||
_id : user._id,
|
||||
scope : user.scope,
|
||||
private : user.private,
|
||||
first_name : user.first_name,
|
||||
last_name : user.last_name,
|
||||
username : user.username,
|
||||
permissions : user.permissions,
|
||||
business_code : user.business_code,
|
||||
mobile_number : user.mobile_number,
|
||||
currentBranch: user?.currentBranch,
|
||||
branches: user?.branches,
|
||||
}
|
||||
return next()
|
||||
}
|
||||
})
|
||||
} else return res.status(401).json({message: 'unauthorized'})
|
||||
})
|
||||
} else {
|
||||
return res.status(401).json({message: 'unauthorized'})
|
||||
}
|
||||
},
|
||||
// check if admin logged in (middleware)
|
||||
isAdmin: function (req, res, next) {
|
||||
const token = req?.headers?.authorization?.replace(/^Bearer\s/, '')
|
||||
if (token) {
|
||||
// check if token is not destroyed
|
||||
User.findOne({token: token}, (err, user) => {
|
||||
if (err) throw err
|
||||
if (user) {
|
||||
// verifies secret and checks if the token is expired
|
||||
jwt.verify(user.token.replace(/^Bearer\s/, ''), authentication.secretKey, (err, decoded) => {
|
||||
if (err || !user.scope.includes('admin')) return res.status(401).json({message: 'unauthorized'})
|
||||
else {
|
||||
req.user = {
|
||||
_id : user._id,
|
||||
scope : user.scope,
|
||||
private : user.private,
|
||||
first_name : user.first_name,
|
||||
last_name : user.last_name,
|
||||
username : user.username,
|
||||
permissions : user.permissions,
|
||||
business_code : user.business_code,
|
||||
mobile_number : user.mobile_number,
|
||||
fcmToken : user.fcmToken,
|
||||
currentBranch: user?.currentBranch,
|
||||
branches: user?.branches,
|
||||
}
|
||||
return next()
|
||||
}
|
||||
})
|
||||
} else return res.status(401).json({message: 'unauthorized'})
|
||||
})
|
||||
} else {
|
||||
return res.status(401).json({message: 'unauthorized'})
|
||||
}
|
||||
},
|
||||
// check if admin logged in (middleware)
|
||||
isUser: function (req, res, next) {
|
||||
const token = req?.headers?.authorization?.replace(/^Bearer\s/, '')
|
||||
if (token) {
|
||||
// check if token is not destroyed
|
||||
User.findOne({token: token}, (err, user) => {
|
||||
if (err) throw err
|
||||
if (user) {
|
||||
// verifies secret and checks if the token is expired
|
||||
jwt.verify(user.token.replace(/^Bearer\s/, ''), authentication.secretKey, (err, decoded) => {
|
||||
if (err || !user.scope.includes('user')) return res.status(401).json({message: 'unauthorized'})
|
||||
else {
|
||||
req.user = {
|
||||
_id : user._id,
|
||||
scope : user.scope,
|
||||
private : user.private,
|
||||
first_name : user.first_name,
|
||||
last_name : user.last_name,
|
||||
username : user.username,
|
||||
permissions : user.permissions,
|
||||
business_code : user.business_code,
|
||||
mobile_number : user.mobile_number,
|
||||
fcmToken : user.fcmToken,
|
||||
currentBranch: user?.currentBranch,
|
||||
branches: user?.branches,
|
||||
}
|
||||
return next()
|
||||
}
|
||||
})
|
||||
} else return res.status(401).json({message: 'unauthorized'})
|
||||
})
|
||||
} else {
|
||||
return res.status(401).json({message: 'unauthorized'})
|
||||
}
|
||||
},
|
||||
// get user id from token
|
||||
getID: (req) => {
|
||||
const token = req.headers.authorization
|
||||
return jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey, (err, decoded) => {
|
||||
if (err) return 'unauthorized'
|
||||
else return decoded._id
|
||||
})
|
||||
},
|
||||
// check if user has permission (middleware)
|
||||
hasPermission: (permission) => {
|
||||
return (req, res, next) => {
|
||||
const token = req.headers.authorization
|
||||
if (token) {
|
||||
// check if token is not destroyed
|
||||
User.findOne({token: token}, (err, user) => {
|
||||
if (err || !user) return res.status(401).json({message: 'unauthorized'})
|
||||
if (user.permissions.includes('super-admin')) return next()
|
||||
if (!user.permissions.includes(permission)) return res.status(401).json({message: 'unauthorized'})
|
||||
else return next()
|
||||
})
|
||||
} else {
|
||||
return res.status(401).json({message: 'unauthorized'})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = authentication
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"type": "service_account",
|
||||
"project_id": "barg-336706",
|
||||
"private_key_id": "9be10ae71cf4430c2976c85503213c438b1619a7",
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCgbmnA76uEPOe5\ndPagMlrrn8rt8Lr98og/pDhlDfj6L6lRNNEzpw3H5EVQUHDlk855A7B6D1LlX+av\nZin3WQnJR618BYwX+ZkavbBj+9VamfVfYxOc+ez8S0ZpdmTGvAvIuA42n4afEPzN\nJn9knc9SopXZ9COdEYzhOZH2ICVzrdwq4l7HvK6xRdNvny4pScE1c9Dd/yAH/CUT\njq41sv0CoMAqkf8YQO46+14l6psyC20WVbmBn165MHTpzyScu19Te9dv0a9sp5bk\nbC3SZkGDwF/qyCwW6S8XGQu7rJqeMTsJdIQntoMFjPjEcrH40GRc65s1FlaD6KfQ\ngVBxRzNjAgMBAAECggEABP+rt+E/3Nzw82xbit5GyvStpABOMz9tU15Qi4WF7nWx\ntuAIbK2V1lacekYnXl/enRKqWwNDN/Zm/6wVPqm9jlH3a9fYZ57VUGn8pwDfwvTt\nGk3B/LAk3C+UQBD6Tt7pFxX1C2qpDSfAWLwMWBw6q355YNMkkO5ND291xs91m0cQ\n3DnevDxVUxqGbFgNilQK3RxJvNsS6A7VhoScC9FnjekWWW2FkzDNFgLqweARe+Ag\n+xgTPnnIXKBMLM++Rucb3QaMXEDOYvXF+IY2xNa4mqtdcT2/etXL48lXJ2PGZXWP\nVdjVOdUhlP3yftXJn0oi6N2nBTgkO19qZIAHHfDngQKBgQDbHFKVxnWWnN5pheOf\nhlhVBep8wq86t935zE0anx86ID2DAiIIdK+6xXtNCeopzZUgVoeypfGfGGg3HLf/\nhrf7fxqXLVI0Xz1YcUk7EjtP78uf2TDWg86s1gWPc3at1V6QKUvTTGfCoCr8e4FQ\nZGDppBmKrejBFlDwoDqcXnm7YQKBgQC7cQJAFzVY1v4qHhOUWwjXmzU54wu5y0LU\nGpvFLhb5YS3Mw6iA9IHfHD0GOnzjO6QTrd7Im1yoAfwLA4KS06VEuL9afIWrOQXV\nWsrHPdmGVwgK9lzSnjoCrr5eWmXXkWqDVXtMerrkPFJA41wjAwooWvmx5E4/fK5P\npVEIEszJQwKBgGKNAaQ2KEt+8RabTv9AaNiNGaPV2QTbEG87ce6oZV46hBA51F7j\nROsHyeajr/vvaMSrxssWkm/RhYZMV4IJ8RSgXbBjhRbjQ29VPO/hymWw4HBcOvgx\nPrNEbCnScC3Ny4Oh32YBdqX2bn8zeb1T+Lb9xTM393lpdSxVlSch4zThAoGBAIlN\nIH7eAT/QTGGBoon7nSCCGp0KiV5RW+SOkSgAuOd3ndruP5ImiLNrte/IDA9PcsLP\ni++ajmaq/Xr72TvAOMF8Kv8XU7q2jGVamksULTDQs52EFT5alNe+NMhco1kitcj6\nZtUA2cGxxfauFKG46knhSiJawE6VAAJrcE3fp46NAoGAFhjwT2MwMrp4qHZ8/XRJ\nw0lxgVX75mT8sle+SboxdqZDKOFMMwzxS5/l//N3lPNj/TIbQIQykVezQ8pAGBe2\nAStm3G+lN1CG1cu8qnB4MwZClYE29A0m9PUNdIkqicZ4XqfGXbeLz8dDWoHBvT2h\n1mKIRzTtEEXcYHKHYI+Hd1U=\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "firebase-adminsdk-j9xb6@barg-336706.iam.gserviceaccount.com",
|
||||
"client_id": "113966745548200447528",
|
||||
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
||||
"token_uri": "https://oauth2.googleapis.com/token",
|
||||
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
||||
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-j9xb6%40barg-336706.iam.gserviceaccount.com"
|
||||
}
|
||||
@@ -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
@@ -0,0 +1,52 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
mongoose.plugin(schema => {
|
||||
schema.set('toObject', {
|
||||
getters: true
|
||||
})
|
||||
schema.set('toJSON', {
|
||||
getters: true
|
||||
})
|
||||
schema.set('timestamps', {
|
||||
createdAt: 'created_at',
|
||||
updatedAt: 'updated_at'
|
||||
})
|
||||
})
|
||||
|
||||
// mongodb database connection string. change it as per your needs. here "mydb" is the name of the database. You don't need to create DB from mongodb terminal. mongoose create the database automatically.
|
||||
// mongoose.connect('mongodb://localhost:27017/bargrest_barg', {
|
||||
mongoose.connect('mongodb://bargrest_bargtest:barg123456@bargrestaurant.com:27017/bargrest_bargtest', {
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
useFindAndModify: false,
|
||||
useCreateIndex: true
|
||||
})
|
||||
//
|
||||
// mongoose.connect('mongodb://bargrest_admin:barg1234@localhost:27017/bargrest_barg', {
|
||||
// useNewUrlParser: true,
|
||||
// useUnifiedTopology: true,
|
||||
// useFindAndModify: false,
|
||||
// useCreateIndex: true
|
||||
// })
|
||||
|
||||
|
||||
/*mongoose.connect('mongodb://barg_database:D7pAAqDWxx4ZpgnC@cluster0-shard-00-00.dle1t.mongodb.net:27017,cluster0-shard-00-01.dle1t.mongodb.net:27017,cluster0-shard-00-02.dle1t.mongodb.net:27017/barg?ssl=true&replicaSet=atlas-zj3m2c-shard-0&authSource=admin&retryWrites=true&w=majority', {
|
||||
useNewUrlParser: true,
|
||||
useUnifiedTopology: true,
|
||||
useFindAndModify: false,
|
||||
useCreateIndex: true
|
||||
})*/
|
||||
// mongoose.connect('mongodb://bargrest_admin:barg1234@bargrestaurant.com:27017/bargrest_barg?authSource=bargrest_barg&readPreference=primary&appname=MongoDB%20Compass&directConnection=true&ssl=false', {
|
||||
// useNewUrlParser: true,
|
||||
// useUnifiedTopology: true,
|
||||
// useFindAndModify: false,
|
||||
// useCreateIndex: true
|
||||
// })
|
||||
|
||||
const database = mongoose.connection
|
||||
database.on('error', console.error.bind(console, 'connection error:'))
|
||||
database.once('open', function callback() {
|
||||
console.log("MongoDB Connected...")
|
||||
})
|
||||
|
||||
module.exports = database
|
||||
@@ -0,0 +1,10 @@
|
||||
const fireBase = require('firebase-admin');
|
||||
const serviceAccount = require('./barg-336706-firebase-adminsdk-j9xb6-9be10ae71c.json');
|
||||
fireBase.initializeApp({
|
||||
// credential: fireBase.credential.applicationDefault(),
|
||||
credential: fireBase.credential.cert(serviceAccount),
|
||||
// databaseURL: 'https://target-c336b.firebaseio.com',
|
||||
});
|
||||
|
||||
module.exports.admin = fireBase
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
const express = require('express')
|
||||
const database = require('./database')
|
||||
// global.socket = require("socket.io");
|
||||
const fileUpload = require('express-fileupload')
|
||||
const {isUser, isAdmin} = require('./authentication')
|
||||
const bodyParser = require('body-parser')
|
||||
const {removeUser , removeCartItem , birthdateJob , marriageDateJob} = require('./plugins/cronJobs')
|
||||
const {createAdmins} = require('./plugins/privateAdmin')
|
||||
// global.webPush = require('web-push');
|
||||
// const vapidKeys = webPush.generateVAPIDKeys();
|
||||
// const StoreInfo = require('./models/StoreInfo')
|
||||
// StoreInfo.findOne().then(store => {
|
||||
// if (store){
|
||||
// global.userRegistrationScore = Number(store.userRegistrationScore)
|
||||
// global.userEmailVerifyScore = Number(store.userEmailVerifyScore)
|
||||
// global.totalPricePoint = store.totalPricePoint
|
||||
// global.pointForBuy = store.pointForBuy
|
||||
// global.pricePoint = Math.floor(store.priceForChange/store.pointForChange)
|
||||
// global.pointBirthDate = Number(store.pointBirthDate)
|
||||
// global.pointMarriageDate = Number(store.pointMarriageDate)
|
||||
// global.invitePoint = Number(store.invitePoint)
|
||||
// }else {
|
||||
// global.userRegistrationScore = 0
|
||||
// global.userEmailVerifyScore = 0
|
||||
// global.totalPricePoint = 0
|
||||
// global.pointForBuy = 0
|
||||
// global.pricePoint = 0
|
||||
// global.pointBirthDate = 0
|
||||
// global.pointMarriageDate = 0
|
||||
// global.invitePoint = 0
|
||||
// }
|
||||
// }).catch(error => {
|
||||
// global.userRegistrationScore = 0
|
||||
// global.userEmailVerifyScore = 0
|
||||
// global.totalPricePoint = 0
|
||||
// global.pointForBuy = 0
|
||||
// global.pricePoint = 0
|
||||
// global.pointBirthDate = 0
|
||||
// global.pointMarriageDate = 0
|
||||
// global.invitePoint = 0
|
||||
// })
|
||||
global._ = require('lodash');
|
||||
const wss = require('./socket/init')
|
||||
|
||||
// Create express instnace
|
||||
const app = express()
|
||||
// removeUser()
|
||||
// removeCartItem()
|
||||
// createAdmins()
|
||||
// birth date job for add point and send sms
|
||||
birthdateJob().start()
|
||||
// marriage date job for add point and send sms
|
||||
marriageDateJob().start()
|
||||
// Init body-parser options (inbuilt with express)
|
||||
app.use(express.json())
|
||||
app.use(express.urlencoded({extended: true}))
|
||||
app.use(fileUpload())
|
||||
|
||||
|
||||
// const publicVapidKey = vapidKeys.publicKey;
|
||||
// const privateVapidKey = vapidKeys.privateKey;
|
||||
//
|
||||
// webPush.setVapidDetails('mailto:abedzadehalireza19@gmail.com', publicVapidKey, privateVapidKey);
|
||||
|
||||
// Require & Import API routes
|
||||
const Public = require('./routes/public')
|
||||
const admin = require('./routes/admin')
|
||||
const auth = require('./routes/auth')
|
||||
const user = require('./routes/user')
|
||||
|
||||
// Use API Routes
|
||||
app.use('/public', Public)
|
||||
app.use('/auth', auth)
|
||||
app.use('/admin', isAdmin, admin)
|
||||
app.use('/user', isUser, user)
|
||||
|
||||
wss()
|
||||
|
||||
// Export the server middleware
|
||||
module.exports = {
|
||||
path: '/api',
|
||||
handler: app
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
const Cart_ItemSchema = mongoose.Schema({
|
||||
user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
product_id: {type: mongoose.ObjectId, ref: 'Food'},
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
quantity: Number,
|
||||
// createdAt : {type : Date , expires : 3600 , default : Date.now()}
|
||||
})
|
||||
|
||||
module.exports = mongoose.model('CartItem', Cart_ItemSchema)
|
||||
@@ -0,0 +1,13 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const contactUsSchema = mongoose.Schema({
|
||||
name: String,
|
||||
phone: String,
|
||||
email: String,
|
||||
message: String,
|
||||
read: Boolean
|
||||
})
|
||||
contactUsSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('ContactUs', contactUsSchema)
|
||||
@@ -0,0 +1,17 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const DiscountSchema = mongoose.Schema({
|
||||
discount_code: String,
|
||||
discount_amount: Number,
|
||||
discount_expire_date: String,
|
||||
discount_user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
menuTypeId: {type: mongoose.ObjectId, ref: 'MenuType'},
|
||||
isPublic: {type: Boolean, default: false},
|
||||
used_by: [{type: mongoose.ObjectId, ref: 'User'}],
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'}
|
||||
})
|
||||
|
||||
DiscountSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('DiscountCode', DiscountSchema)
|
||||
@@ -0,0 +1,49 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function image(img) {
|
||||
if (img) return '/uploads/images/food/' + img
|
||||
}
|
||||
|
||||
const RateSchema = mongoose.Schema({
|
||||
user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
rate: {
|
||||
type: Number,
|
||||
enum: [0, 1, 2, 3, 4, 5],
|
||||
default: 0
|
||||
},
|
||||
comment: String,
|
||||
order_id : String,
|
||||
replay: String,
|
||||
replied_by: {type: mongoose.ObjectId, ref: 'User'},
|
||||
confirmed: {type: Boolean, default: false},
|
||||
confirmed_by: {type: mongoose.ObjectId, ref: 'User'},
|
||||
})
|
||||
|
||||
const FoodSchema = mongoose.Schema({
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
club : {type : Boolean , default : false},
|
||||
clubQuantity : {type : Number , default : 1},
|
||||
point: {type : Number , default : 0},
|
||||
sale : {type : Boolean , default : true},
|
||||
name: String,
|
||||
image: {type: String, get: image},
|
||||
price: {type: Number, default: 0},
|
||||
special : {type : Boolean , default : false},
|
||||
description: String,
|
||||
short_description: String,
|
||||
estimated_time: Number,
|
||||
stock: {type: Number, default: 0},
|
||||
category: {type: mongoose.ObjectId, ref: 'FoodCategory'},
|
||||
static_discount: {type: Number, default: 0},
|
||||
rate: {type: Number, default: 0},
|
||||
ratings: [RateSchema],
|
||||
index: Number,
|
||||
havePoint : {type: Boolean ,default : true},
|
||||
canReview : {type :Array , default: []},
|
||||
// deleted : {type: Boolean , default : false}
|
||||
})
|
||||
|
||||
FoodSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Food', FoodSchema)
|
||||
@@ -0,0 +1,18 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function cover(img) {
|
||||
return '/uploads/images/foodCategories/' + img
|
||||
}
|
||||
|
||||
const FoodCategorySchema = mongoose.Schema({
|
||||
name: String,
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
cover: {type: String, get: cover},
|
||||
type: {type: mongoose.ObjectId, ref: 'MenuType'},
|
||||
index: Number
|
||||
})
|
||||
|
||||
FoodCategorySchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('FoodCategory', FoodCategorySchema)
|
||||
@@ -0,0 +1,20 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function image(file) {
|
||||
return `/uploads/images/gallery/${file}`
|
||||
}
|
||||
|
||||
const gallerySchema = mongoose.Schema({
|
||||
image: {type: String, get: image},
|
||||
caption: String,
|
||||
shortCaption: String
|
||||
})
|
||||
|
||||
gallerySchema.virtual('thumb').get(function () {
|
||||
return '/uploads/images/gallery/thumb/thumb_' + this.image.split('gallery/')[1]
|
||||
})
|
||||
|
||||
gallerySchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Gallery', gallerySchema)
|
||||
@@ -0,0 +1,8 @@
|
||||
const mongoose = require('mongoose');
|
||||
|
||||
const GetTokenLimitSchema = mongoose.Schema({
|
||||
phone : String,
|
||||
createdAt : {type : Date , expires : 120 , default : Date.now()}
|
||||
});
|
||||
|
||||
module.exports = mongoose.model('GetTokenLimit', GetTokenLimitSchema);
|
||||
@@ -0,0 +1,11 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const JobSchema = mongoose.Schema({
|
||||
name: String,
|
||||
index: Number
|
||||
})
|
||||
|
||||
JobSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Job', JobSchema)
|
||||
@@ -0,0 +1,14 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const MenuTypeSchema = mongoose.Schema({
|
||||
name: String,
|
||||
showOnWebSite: {type: Boolean, default: true},
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
isCafeMenu: {type: Boolean, default: false},
|
||||
index: Number
|
||||
})
|
||||
|
||||
MenuTypeSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('MenuType', MenuTypeSchema)
|
||||
@@ -0,0 +1,71 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const StatusSchema = mongoose.Schema({
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['canceled', 'void', 'incomplete', 'processing', 'sent', 'delivered'],
|
||||
default: 'incomplete'
|
||||
},
|
||||
user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
})
|
||||
|
||||
const OrderItemsSchema = mongoose.Schema({
|
||||
product_id: {type: mongoose.ObjectId, ref: 'Food'},
|
||||
name: String,
|
||||
quantity: Number,
|
||||
price: Number,
|
||||
point : Number,
|
||||
static_discount: {type: Number, default: 0},
|
||||
havePoint: Boolean
|
||||
})
|
||||
|
||||
const OrderSchema = mongoose.Schema({
|
||||
user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
rating: {
|
||||
rate: {
|
||||
type: Number,
|
||||
enum: [0, 1, 2, 3, 4, 5],
|
||||
default: 0
|
||||
},
|
||||
reasonForBad: Array
|
||||
},
|
||||
description: String,
|
||||
orderType : {type : String , default : 'online'},
|
||||
bag: {type: Boolean, default: false},
|
||||
bagCost: {type: Number, default: 0},
|
||||
score: {type: Boolean, default: false},
|
||||
scoreCost: {type: Number, default: 0},
|
||||
scorePoint: {type: Number, default: 0},
|
||||
pricePoint: {type: Number, default: 0},
|
||||
number: Number,
|
||||
address: {type: Object, default: {}},
|
||||
statuses: [StatusSchema],
|
||||
createdOn: Date,
|
||||
payment: [{type: mongoose.ObjectId, ref: 'Payment' , default:[]}],
|
||||
paymentStatus: {
|
||||
type: String,
|
||||
enum: ['refund', 'unpaid', 'paid'],
|
||||
default: 'unpaid'
|
||||
},
|
||||
status: {
|
||||
type: String,
|
||||
enum: ['canceled', 'void', 'incomplete', 'processing', 'sent', 'delivered'],
|
||||
default: 'incomplete'
|
||||
},
|
||||
order_items: [OrderItemsSchema],
|
||||
discount_code: String,
|
||||
discount_amount: Number,
|
||||
discount_menuType: String,
|
||||
sum: Number,
|
||||
routePrice: Number,
|
||||
tax: Number,
|
||||
percent: Number,
|
||||
total: Number,
|
||||
payTotal: Number
|
||||
})
|
||||
|
||||
OrderSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Order', OrderSchema)
|
||||
@@ -0,0 +1,19 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function image(img) {
|
||||
if (img) return '/uploads/images/partySet/' + img
|
||||
}
|
||||
|
||||
const PartySetSchema = mongoose.Schema({
|
||||
title: String,
|
||||
description: String,
|
||||
index: Number,
|
||||
price: {type: Number, default: 0},
|
||||
active: {type: Boolean, default: true},
|
||||
image: {type: String, get: image}
|
||||
})
|
||||
|
||||
PartySetSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('PartySet', PartySetSchema)
|
||||
@@ -0,0 +1,29 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const PaymentSchema = mongoose.Schema({
|
||||
user_id: {type: mongoose.ObjectId, ref: 'User'},
|
||||
order_id : {type: mongoose.ObjectId, ref: 'Order'},
|
||||
transactionId : String,
|
||||
getPayment : {type : Boolean , default: false},
|
||||
action : {
|
||||
type : String,
|
||||
enum: ['increaseBag', 'decreaseBag', 'payOrder'],
|
||||
default: 'payOrder'
|
||||
},
|
||||
status : {
|
||||
type : String,
|
||||
enum: ['refund', 'unpaid', 'paid'],
|
||||
default: 'unpaid'
|
||||
},
|
||||
cost : Number,
|
||||
refId : String,
|
||||
fee_type: String,
|
||||
card_hash: String,
|
||||
card_pan:String,
|
||||
fee: Number
|
||||
})
|
||||
|
||||
PaymentSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Payment', PaymentSchema)
|
||||
@@ -0,0 +1,15 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function image(img) {
|
||||
return '/uploads/images/slider/' + img
|
||||
}
|
||||
|
||||
const SliderSchema = mongoose.Schema({
|
||||
image: {type: String, get: image},
|
||||
caption: String
|
||||
})
|
||||
|
||||
SliderSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Slide', SliderSchema)
|
||||
@@ -0,0 +1,52 @@
|
||||
const mongoose = require('mongoose')
|
||||
|
||||
function image(img) {
|
||||
return '/uploads/images/icon/' + img
|
||||
}
|
||||
|
||||
const StoreInfoSchema = mongoose.Schema({
|
||||
title: {type: String , default: ''},
|
||||
// image: {type: String, get: image},
|
||||
caption: String,
|
||||
message : {type : String , default:''},
|
||||
socials : {
|
||||
whatsaap : {type : String ,default : ''},
|
||||
twitter : {type : String ,default : ''},
|
||||
facebook : {type : String ,default : ''},
|
||||
instagram : {type : String ,default : ''},
|
||||
googlePlus : {type : String ,default : ''},
|
||||
},
|
||||
email : String,
|
||||
shippingCost : Number,
|
||||
shippingType : {type : Boolean , default: true}, /// true yani sabet va false yani bar asas kilometer
|
||||
tel : String,
|
||||
address : String,
|
||||
location : { type: {type : String , default : 'Point'} , coordinates: [Number]},
|
||||
tax : {type : Boolean , default : true},
|
||||
closeStore : {type : Boolean , default : false},
|
||||
firstStartTime : {type : String , default : '12:00'},
|
||||
firstEndTime : {type : String , default : '15:00'},
|
||||
secondStartTime : {type : String , default : '17:00'},
|
||||
secondEndTime : {type : String , default : '22:00'},
|
||||
utcStartTime : {type : String , default : '8:30'},
|
||||
utcEndTime : {type : String , default : '18:30'},
|
||||
timezone : {type : String , default : 'Asia/Tehran'},
|
||||
usePointWhenPay : {type : Boolean , default : false},
|
||||
userRegistrationScore : {type : Number , default : 0},
|
||||
userEmailVerifyScore : {type : Number , default : 0},
|
||||
pointBirthDate : {type : Number , default : 0},
|
||||
pointMarriageDate : {type : Number , default : 0},
|
||||
invitePoint : {type : Number , default : 0},
|
||||
pointForBuy : {type : Number , default : 0},
|
||||
totalPricePoint : {type : Number , default : 0},
|
||||
priceForChange : {type : Number , default : 0},
|
||||
pointForChange : {type : Number , default : 0},
|
||||
limitPrice : {type : Number , default : 0},
|
||||
useSpecialMenu : {type : Boolean , default : true},
|
||||
updateApp : {type : String , default : null},
|
||||
active : {type : Boolean , default : true}
|
||||
})
|
||||
|
||||
StoreInfoSchema.index({'location': '2dsphere'});
|
||||
|
||||
module.exports = mongoose.model('StoreInfo', StoreInfoSchema)
|
||||
@@ -0,0 +1,16 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
const subscribersSchema = mongoose.Schema({
|
||||
full_name: String,
|
||||
birth_date: String,
|
||||
job: String,
|
||||
marrage_date: String,
|
||||
email: String,
|
||||
mobile: String,
|
||||
address: String
|
||||
})
|
||||
|
||||
subscribersSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('Subscribers', subscribersSchema)
|
||||
@@ -0,0 +1,78 @@
|
||||
const mongoose = require('mongoose')
|
||||
const mongoosePaginate = require('mongoose-paginate-v2');
|
||||
|
||||
function image(img) {
|
||||
if (img) return '/uploads/images/users/' + img
|
||||
}
|
||||
|
||||
const AddressesSchema = mongoose.Schema({
|
||||
title : {type : String , default : null},
|
||||
province: String,
|
||||
city: String,
|
||||
address: String,
|
||||
used : {type : Boolean , default : true},
|
||||
useRate : {type : Number , default : 0},
|
||||
location : { type: {type : String , default : 'Point'} , coordinates: [Number]}
|
||||
})
|
||||
|
||||
const ScoreLogSchema = mongoose.Schema({
|
||||
score: Number,
|
||||
order_id : {type: mongoose.ObjectId, ref: 'Order'},
|
||||
branchId: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
forWhat : {
|
||||
type: String,
|
||||
enum: ['birthDate', 'marriageDate', 'buy', 'register', 'invite', 'emailVerify']
|
||||
},
|
||||
action : {
|
||||
type: String,
|
||||
enum: ['increase', 'decrease']
|
||||
},
|
||||
})
|
||||
|
||||
const UserSchema = mongoose.Schema({
|
||||
// mutual
|
||||
first_name: String,
|
||||
last_name: String,
|
||||
birth_date: Date,
|
||||
birthDateChange : {type : String, default : ''},
|
||||
showBirthDate : {type : Boolean , default : false},
|
||||
marriage_date : Date,
|
||||
marriageDateChange : {type : String , default : ''},
|
||||
job: String,
|
||||
national_code: String,
|
||||
password: String,
|
||||
scope: {type: Array, default: ['user']},
|
||||
branches: [{type: mongoose.ObjectId, ref: 'StoreInfo'}],
|
||||
token: String,
|
||||
currentBranch: {type: mongoose.ObjectId, ref: 'StoreInfo'},
|
||||
// for user
|
||||
business_code: Number,
|
||||
mobile_number: String,
|
||||
invitation : Number,
|
||||
// discount_codes: Array
|
||||
// this will be an Array and will be filled while querying database,
|
||||
bagAmount: {type : Number , default : 0},
|
||||
score: {type : Number , default : 0},
|
||||
scoreLogs:[ScoreLogSchema],
|
||||
email: String,
|
||||
addresses: [AddressesSchema],
|
||||
registration_done: {type: Boolean, default: false},
|
||||
// for admin
|
||||
profile_pic: {type: String, get: image},
|
||||
_creator: {type: mongoose.ObjectId, ref: 'User'},
|
||||
username: String,
|
||||
permissions: Array,
|
||||
branchPermission: Array,
|
||||
private: {type: Boolean, default: false},
|
||||
deviceId : String,
|
||||
platform : String,
|
||||
deviceName : String,
|
||||
fcmToken : String,
|
||||
fromWhere :{type : String, default : 'app'},
|
||||
})
|
||||
|
||||
UserSchema.index({'addresses.location': '2dsphere'});
|
||||
|
||||
UserSchema.plugin(mongoosePaginate);
|
||||
|
||||
module.exports = mongoose.model('User', UserSchema)
|
||||
@@ -0,0 +1,14 @@
|
||||
module.exports = function checkNationalCode(code) {
|
||||
var L = code.length
|
||||
|
||||
if (L < 8 || parseInt(code, 10) == 0) return false
|
||||
code = ('0000' + code).substr(L + 4 - 10)
|
||||
if (parseInt(code.substr(3, 6), 10) == 0) return false
|
||||
var c = parseInt(code.substr(9, 1), 10)
|
||||
var s = 0
|
||||
for (var i = 0; i < 9; i++) {
|
||||
s += parseInt(code.substr(i, 1), 10) * (10 - i)
|
||||
}
|
||||
s = s % 11;
|
||||
return (s < 2 && c == s) || (s >= 2 && c == (11 - s))
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
module.exports.res404 = (res, err) => {
|
||||
return res.status(404).json({message: err})
|
||||
}
|
||||
|
||||
module.exports.res500 = (res, err) => {
|
||||
return res.status(500).json({message: err})
|
||||
}
|
||||
|
||||
module.exports.checkValidations = validationResult => {
|
||||
return (req, res, next) => {
|
||||
const errors = validationResult(req)
|
||||
if (!errors.isEmpty()) return res.status(422).json({validation: errors.mapped()})
|
||||
else next()
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.removeWhiteSpaces = str => {
|
||||
return str.replace(/ /g, '')
|
||||
}
|
||||
|
||||
module.exports.nameOptimizer = name => {
|
||||
function regex(str) {
|
||||
return new RegExp(str)
|
||||
}
|
||||
|
||||
return name
|
||||
.replace(regex('آقای'), '')
|
||||
.replace(regex('آقا'), '')
|
||||
.replace(regex('جنابه'), '')
|
||||
.replace(regex('جناب'), '')
|
||||
.replace(regex('سرکار خانوم'), '')
|
||||
.replace(regex('سرکار خانم'), '')
|
||||
.replace(regex('سرکارخانوم'), '')
|
||||
.replace(regex('سرکارخانومه'), '')
|
||||
.replace(regex('سرکارخانمه'), '')
|
||||
.replace(regex('سرکارخانم'), '')
|
||||
.replace(regex('سرکار'), '')
|
||||
.replace(regex('خانوم'), '')
|
||||
.replace(regex('خانم'), '')
|
||||
}
|
||||
|
||||
module.exports.checkNationalCode = code => {
|
||||
var L = code.length
|
||||
|
||||
if (L < 8 || parseInt(code, 10) == 0) return false
|
||||
code = ('0000' + code).substr(L + 4 - 10)
|
||||
if (parseInt(code.substr(3, 6), 10) == 0) return false
|
||||
var c = parseInt(code.substr(9, 1), 10)
|
||||
var s = 0
|
||||
for (var i = 0; i < 9; i++) {
|
||||
s += parseInt(code.substr(i, 1), 10) * (10 - i)
|
||||
}
|
||||
s = s % 11;
|
||||
return (s < 2 && c == s) || (s >= 2 && c == (11 - s))
|
||||
}
|
||||
|
||||
module.exports.isLatinCharactersWithoutSymbol = str => {
|
||||
return str.match(/^[A-Za-z]+$/g)
|
||||
}
|
||||
|
||||
module.exports.isLatinCharactersWithSymbol = str => {
|
||||
return str.match(/^[a-zA-Z0-9()*_\-!#$%^&*,."\'\][]*$/g)
|
||||
}
|
||||
|
||||
module.exports.hasWhiteSpaces = str => {
|
||||
return str.includes(' ')
|
||||
}
|
||||
|
||||
module.exports.generateRandomDigits = digitsLength => {
|
||||
// temp (development tests)
|
||||
// return 111111
|
||||
var add = 1, max = 12 - add // 12 is the min safe number Math.random() can generate without it starting to pad the end with zeros.
|
||||
if (digitsLength > max) {
|
||||
return generateRandomDigits(max) + generateRandomDigits(digitsLength - max)
|
||||
}
|
||||
max = Math.pow(10, digitsLength + add)
|
||||
var min = max / 10 // Math.pow(10, n) basically
|
||||
var number = Math.floor(Math.random() * (max - min + 1)) + min
|
||||
|
||||
return ('' + number).substring(add)
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
const User = require('../models/User')
|
||||
const CartItem = require('../models/CartItem')
|
||||
const CronJob = require('cron').CronJob
|
||||
const {sms} = require('./../SMSModule')
|
||||
|
||||
const minute = 1000 * 60
|
||||
const hour = minute * 60
|
||||
const day = hour * 24
|
||||
|
||||
module.exports = {
|
||||
removeUser: () => {
|
||||
// check users for activation
|
||||
setInterval(() => {
|
||||
User.find({registration_done: false , scope : 'user'})
|
||||
.then(users => {
|
||||
if (users.length) {
|
||||
///////////////////////
|
||||
users.forEach((item, index) => {
|
||||
// item time and timeout
|
||||
const itemTime = Date.parse(item.created_at)
|
||||
const timeout = itemTime + day
|
||||
////////////////////////////
|
||||
if (Date.now() >= timeout) {
|
||||
item.remove()
|
||||
}
|
||||
if (index === users.length - 1) {
|
||||
// console.log('Unconfirmed users deleted.')
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch(err => {
|
||||
console.log(err)
|
||||
})
|
||||
}, hour)
|
||||
},
|
||||
//remove cart item every hour
|
||||
removeCartItem: () => {
|
||||
setInterval(() => {
|
||||
CartItem.remove({})
|
||||
}, hour)
|
||||
},
|
||||
//birth date job for add point and send sms
|
||||
birthdateJob: () => {
|
||||
return new CronJob('0 12 * * *', async () => {
|
||||
try {
|
||||
const now = new Date();
|
||||
// const birthPlus = new Date('2021-10-21T00:00:00.000+00:00');
|
||||
// birthPlus.setDate(birthPlus.getDate() + 7);
|
||||
|
||||
const users = await User.find({scope: ['user'], registration_done: true})
|
||||
for (const user of users) {
|
||||
const birthPlus = new Date(user?.birth_date);
|
||||
const tempBirth = new Date(now.getFullYear() , birthPlus.getMonth() , birthPlus.getDate())
|
||||
const tempBirthForDisableMessage = new Date(now.getFullYear() , birthPlus.getMonth() , birthPlus.getDate())
|
||||
tempBirthForDisableMessage?.setDate(tempBirth?.getDate() + 7);
|
||||
if (user.birth_date && tempBirthForDisableMessage <= now){
|
||||
user.showBirthDate = false
|
||||
await user.save()
|
||||
}
|
||||
if (user.birth_date && tempBirth.toDateString() === now.toDateString() && user.birthDateChange < now.getFullYear()) {
|
||||
//// add point
|
||||
user.score += pointBirthDate
|
||||
user.showBirthDate = true
|
||||
user.birthDateChange = now?.getFullYear()?.toString()
|
||||
user.scoreLogs = [
|
||||
{
|
||||
score : pointBirthDate,
|
||||
forWhat : 'birthDate',
|
||||
action : 'increase'
|
||||
}
|
||||
]
|
||||
await user.save()
|
||||
|
||||
//// send sms
|
||||
const smsTemplate = `${user.first_name} عزیز تولدت مبارک هدیه ما به شما ${pointBirthDate} امتیاز برای سفارش در اپلیکیشن برگ من لغو11`
|
||||
const smsResult = await sms(user.mobile_number, smsTemplate)
|
||||
|
||||
if (!smsResult || !smsResult.data.IsSuccessful) {
|
||||
console.log('birthdate sms', smsResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (error) {
|
||||
console.log('birthdate job' , error.message)
|
||||
return ''
|
||||
}
|
||||
});
|
||||
},
|
||||
//Marriage date job for add point and send sms
|
||||
marriageDateJob: () => {
|
||||
return new CronJob('0 12 * * *', async () => {
|
||||
try {
|
||||
const now = new Date();
|
||||
const users = await User.find({scope: ['user'], registration_done: true})
|
||||
for (const user of users) {
|
||||
const marriageDate = new Date(user?.marriage_date);
|
||||
const tempMarriageDate = new Date(now.getFullYear() , marriageDate.getMonth() , marriageDate.getDate())
|
||||
if (user.marriage_date && tempMarriageDate.toDateString() === now.toDateString() && user.marriageDateChange < now.getFullYear()) {
|
||||
//// add point
|
||||
user.score += pointMarriageDate
|
||||
user.marriageDateChange = now?.getFullYear()?.toString()
|
||||
user.scoreLogs = [
|
||||
{
|
||||
score : pointMarriageDate,
|
||||
forWhat : 'marriageDate',
|
||||
action : 'increase'
|
||||
}
|
||||
]
|
||||
await user.save()
|
||||
|
||||
//// send sms
|
||||
const smsTemplate = `${user.first_name} عزیز سالروز ازدواجتان مبارک هدیه ما به شما ${pointBirthDate} امتیاز برای سفارش در اپلیکیشن برگ من لغو11`
|
||||
const smsResult = await sms(user.mobile_number, smsTemplate)
|
||||
|
||||
if (!smsResult || !smsResult.data.IsSuccessful) {
|
||||
console.log('marriage_date sms', smsResult)
|
||||
}
|
||||
}
|
||||
}
|
||||
}catch (error) {
|
||||
console.log('marriage_date job' , error.message)
|
||||
return ''
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
// province cities
|
||||
const eastazarbaijan1 = ['آذرشهر', 'اسکو', 'اهر', 'بستانآباد', 'بناب', 'تبریز', 'جلفا', 'چاراویماق', 'سراب', 'شبستر', 'مراغه']
|
||||
const westazarbaijan2 = ['ارومیه', 'اشنویه', 'بوکان', 'پیرانشهر', 'تکاب', 'چالدران', 'خوی', 'سردشت', 'سلماس', 'شاهیندژ', 'ماکو', 'مهاباد', 'میاندوآب', 'نقده']
|
||||
const ardabil3 = ['اردبیل', 'بیلهسوار', 'پارسآباد', 'خلخال', 'کوثر', 'گِرمی', 'مِشگینشهر', 'نَمین', 'نیر']
|
||||
const esfahan4 = ['آران و بیدگل', 'اردستان', 'اصفهان', 'برخوار و میمه', 'تیران و کرون', 'چادگان', 'خمینیشهر', 'خوانسار', 'سمیرم', 'شهرضا', 'سمیرم سفلی', 'فریدن', 'فریدونشهر', 'فلاورجان', 'کاشان', 'گلپایگان', 'لنجان', 'مبارکه', 'نائین', 'نجفآباد', 'نطنز']
|
||||
const ilam5 = ['آبدانان', 'ایلام', 'ایوان', 'درهشهر', 'دهلران', 'شیروان و چرداول', 'مهران']
|
||||
const booshehr6 = ['بوشهر', 'تنگستان', 'جم', 'دشتستان', 'دشتی', 'دیر', 'دیلم', 'کنگان', 'گناوه']
|
||||
const tehran7 = ['اسلامشهر', 'پاکدشت', 'تهران', 'دماوند', 'رباطکریم', 'ری', 'ساوجبلاغ', 'شمیرانات', 'شهریار', 'فیروزکوه', 'ورامین']
|
||||
const chaharmahalobakhtiari8 = ['اردل', 'بروجن', 'شهرکرد', 'فارسان', 'کوهرنگ', 'لردگان']
|
||||
const khorasanjonoobi9 = ['بیرجند', 'درمیان', 'سرایان', 'سربیشه', 'فردوس', 'قائنات', 'نهبندان']
|
||||
const khorasanrazavi10 = ['بردسکن', 'تایباد', 'تربت جام', 'تربت حیدریه', 'چناران', 'خلیلآباد', 'خواف', 'درگز', 'رشتخوار', 'سبزوار', 'سرخس', 'فریمان', 'قوچان', 'کاشمر', 'کلات', 'گناباد', 'مشهد', 'مه ولات', 'نیشابور']
|
||||
const khorasanshomali11 = ['اسفراین', 'بجنورد', 'جاجرم', 'شیروان', 'فاروج', 'مانه و سملقان']
|
||||
const khoozestan12 = ['آبادان', 'امیدیه', 'اندیمشک', 'اهواز', 'ایذه', 'باغملک', 'بندر ماهشهر', 'بهبهان', 'خرمشهر', 'دزفول', 'دشت آزادگان', 'رامشیر', 'رامهرمز', 'شادگان', 'شوش', 'شوشتر']
|
||||
const zanjan13 = ['ابهر', 'ایجرود', 'خدابنده', 'خرمدره', 'زنجان', 'طارم', 'ماهنشان']
|
||||
const semnan14 = ['دامغان', 'سمنان', 'شاهرود', 'گرمسار', 'مهدیشهر']
|
||||
const sistanobaloochestan15 = ['ایرانشهر', 'چابهار', 'خاش', 'دلگان', 'زابل', 'زاهدان', 'زهک', 'سراوان', 'سرباز', 'کنارک', 'نیکشهر']
|
||||
const fars16 = ['آباده', 'ارسنجان', 'استهبان', 'اقلید', 'بوانات', 'پاسارگاد', 'جهرم', 'خرمبید', 'خنج', 'داراب', 'زریندشت', 'سپیدان', 'شیراز', 'فراشبند', 'فسا', 'فیروزآباد', 'قیر و کارزین', 'کازرون', 'لارستان', 'لامِرد', 'مرودشت', 'ممسنی', 'مهر', 'نیریز']
|
||||
const qazvin17 = ['آبیک', 'البرز', 'بوئینزهرا', 'تاکستان', 'قزوین']
|
||||
const qom18 = ['قم']
|
||||
const kordestan19 = ['بانه', 'بیجار', 'دیواندره', 'سروآباد', 'سقز', 'سنندج', 'قروه', 'کامیاران', 'مریوان']
|
||||
const kerman20 = ['بافت', 'بردسیر', 'بم', 'جیرفت', 'راور', 'رفسنجان', 'رودبار جنوب', 'زرند', 'سیرجان', 'شهر بابک', 'عنبرآباد', 'قلعه گنج', 'کرمان', 'کوهبنان', 'کهنوج', 'منوجان']
|
||||
const kermanshah21 = ['اسلامآباد غرب', 'پاوه', 'ثلاث باباجانی', 'جوانرود', 'دالاهو', 'روانسر', 'سرپل ذهاب', 'سنقر', 'صحنه', 'قصر شیرین', 'کرمانشاه', 'کنگاور', 'گیلان غرب', 'هرسین']
|
||||
const kohkilooyevaboyrahmad22 = ['بویراحمد', 'بهمئی', 'دنا', 'کهگیلویه', 'گچساران']
|
||||
const golestan23 = ['آزادشهر', 'آققلا', 'بندر گز', 'ترکمن', 'رامیان', 'علیآباد', 'کردکوی', 'کلاله', 'گرگان', 'گنبد کاووس', 'مراوهتپه', 'مینودشت']
|
||||
const gilan24 = ['آستارا', 'آستانه اشرفیه', 'اَملَش', 'بندر انزلی', 'رشت', 'رضوانشهر', 'رودبار', 'رودسر', 'سیاهکل', 'شَفت', 'صومعهسرا', 'طوالش', 'فومَن', 'لاهیجان', 'لنگرود', 'ماسال']
|
||||
const lorestan25 = ['ازنا', 'الیگودرز', 'بروجرد', 'پلدختر', 'خرمآباد', 'دورود', 'دلفان', 'سلسله ,کوهدشت']
|
||||
const mazandaran26 = ['آمل', 'بابل', 'بابلسر', 'بهشهر', 'تنکابن', 'جویبار', 'چالوس', 'رامسر', 'ساری', 'سوادکوه', 'قائمشهر', 'گلوگاه', 'محمودآباد', 'نکا', 'نور', 'نوشهر']
|
||||
const markazi27 = ['آشتیان', 'اراک', 'تفرش', 'خمین', 'دلیجان', 'زرندیه', 'ساوه', 'شازند', 'کمیجان', 'محلات']
|
||||
const hormozgan28 = ['ابوموسی', 'بستک', 'بندر عباس', 'بندر لنگه', 'جاسک', 'حاجیآباد', 'شهرستان خمیر', 'رودان', 'قشم', 'گاوبندی', 'میناب']
|
||||
const hamedan29 = ['اسدآباد', 'بهار', 'تویسرکان', 'رزن', 'کبودرآهنگ', 'ملایر', 'نهاوند', 'همدان']
|
||||
const yazd30 = ['ابرکوه', 'اردکان', 'بافق', 'تفت', 'خاتم', 'صدوق', 'طبس', 'مهریز', 'مِیبُد', 'یزد']
|
||||
const alborz31 = ['کرج', 'نظرآباد', 'فردیس', 'اشتهارد', 'هشتگرد', 'طالقان']
|
||||
|
||||
|
||||
// provinces list
|
||||
module.exports.iranCities = [
|
||||
{
|
||||
name: 'آذربایجان شرقی',
|
||||
cities: eastazarbaijan1
|
||||
},
|
||||
{
|
||||
name: 'آذربایجان غربی',
|
||||
cities: westazarbaijan2
|
||||
},
|
||||
{
|
||||
name: 'اردبیل',
|
||||
cities: ardabil3
|
||||
},
|
||||
{
|
||||
name: 'اصفهان',
|
||||
cities: esfahan4
|
||||
},
|
||||
{
|
||||
name: 'ایلام',
|
||||
cities: ilam5
|
||||
},
|
||||
{
|
||||
name: 'بوشهر',
|
||||
cities: booshehr6
|
||||
},
|
||||
{
|
||||
name: 'تهران',
|
||||
cities: tehran7
|
||||
},
|
||||
{
|
||||
name: 'چهارمحال بختیاری',
|
||||
cities: chaharmahalobakhtiari8
|
||||
},
|
||||
{
|
||||
name: 'خراسان جنوبی',
|
||||
cities: khorasanjonoobi9
|
||||
},
|
||||
{
|
||||
name: 'خراسان رضوی',
|
||||
cities: khorasanrazavi10
|
||||
},
|
||||
{
|
||||
name: 'خراسان شمالی',
|
||||
cities: khorasanshomali11
|
||||
},
|
||||
{
|
||||
name: 'خوزستان',
|
||||
cities: khoozestan12
|
||||
},
|
||||
{
|
||||
name: 'زنجان',
|
||||
cities: zanjan13
|
||||
},
|
||||
{
|
||||
name: 'سمنان',
|
||||
cities: semnan14
|
||||
},
|
||||
{
|
||||
name: 'سیستان بلوچستان',
|
||||
cities: sistanobaloochestan15
|
||||
},
|
||||
{
|
||||
name: 'فارس',
|
||||
cities: fars16
|
||||
},
|
||||
{
|
||||
name: 'قزوین',
|
||||
cities: qazvin17
|
||||
},
|
||||
{
|
||||
name: 'قم',
|
||||
cities: qom18
|
||||
},
|
||||
{
|
||||
name: 'کردستان',
|
||||
cities: kordestan19
|
||||
},
|
||||
{
|
||||
name: 'کرمان',
|
||||
cities: kerman20
|
||||
},
|
||||
{
|
||||
name: 'کرمانشاه',
|
||||
cities: kermanshah21
|
||||
},
|
||||
{
|
||||
name: 'کهکیلویه و بویراحمد',
|
||||
cities: kohkilooyevaboyrahmad22
|
||||
},
|
||||
{
|
||||
name: 'گلستان',
|
||||
cities: golestan23
|
||||
},
|
||||
{
|
||||
name: 'گیلان',
|
||||
cities: gilan24
|
||||
},
|
||||
{
|
||||
name: 'لرستان',
|
||||
cities: lorestan25
|
||||
},
|
||||
{
|
||||
name: 'مازندران',
|
||||
cities: mazandaran26
|
||||
},
|
||||
{
|
||||
name: 'مرکزی',
|
||||
cities: markazi27
|
||||
},
|
||||
{
|
||||
name: 'هرمزگان',
|
||||
cities: hormozgan28
|
||||
},
|
||||
{
|
||||
name: 'همدان',
|
||||
cities: hamedan29
|
||||
},
|
||||
{
|
||||
name: 'یزد',
|
||||
cities: yazd30
|
||||
},
|
||||
{
|
||||
name: 'البرز',
|
||||
cities: alborz31
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,30 @@
|
||||
module.exports = [
|
||||
{
|
||||
name: 'مدیریت کاربران',
|
||||
value: 'users'
|
||||
},
|
||||
{
|
||||
name: 'مدیریت سفارشات',
|
||||
value: 'orders'
|
||||
},
|
||||
{
|
||||
name: 'مدیریت محصولات',
|
||||
value: 'foods'
|
||||
},
|
||||
{
|
||||
name: 'مدیریت وبسایت',
|
||||
value: 'settings'
|
||||
},
|
||||
{
|
||||
name: 'مدیریت کد تخفیف',
|
||||
value: 'discounts'
|
||||
},
|
||||
{
|
||||
name: 'مدیریت مشتریان',
|
||||
value: 'customers'
|
||||
},
|
||||
{
|
||||
name : 'گزارشات',
|
||||
value: 'reports'
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,35 @@
|
||||
const User = require('../models/User')
|
||||
const _privateAdminInfo = require('./privateAdminData')
|
||||
const bcrypt = require('bcryptjs')
|
||||
const database = require('../database')
|
||||
|
||||
module.exports.createAdmins = () => {
|
||||
database.once('open', async cb => {
|
||||
for (const item of _privateAdminInfo) {
|
||||
try {
|
||||
const user = await User.findOne({username: item.username})
|
||||
if (!user) {
|
||||
const data = {
|
||||
first_name: item.first_name,
|
||||
last_name: item.last_name,
|
||||
username: item.username,
|
||||
scope: ['admin'],
|
||||
private: true,
|
||||
permissions: item.permissions
|
||||
}
|
||||
// hash password
|
||||
const salt = await bcrypt.genSalt(10)
|
||||
const hash = await bcrypt.hash(item.password, salt)
|
||||
data.password = hash
|
||||
const newUser = new User(data)
|
||||
newUser.save(err => {
|
||||
if (err) console.log(err)
|
||||
})
|
||||
}
|
||||
} catch
|
||||
(e) {
|
||||
console.log('Private admin creation has error -- ', e)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
////////////////////////////////// example
|
||||
//////////////////////////////////
|
||||
// module.exports = [
|
||||
// {
|
||||
// first_name: '',
|
||||
// last_name: '',
|
||||
// username: '',
|
||||
// password: ''
|
||||
// },
|
||||
// {
|
||||
// first_name: '',
|
||||
// last_name: '',
|
||||
// username: '',
|
||||
// password: ''
|
||||
// }
|
||||
// ]
|
||||
////////////////////////////////////
|
||||
//////////////////////////////////// example
|
||||
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////
|
||||
// *remove data from this file after first run* //
|
||||
//////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
|
||||
module.exports = [
|
||||
{
|
||||
first_name: 'negareh',
|
||||
last_name: 'support',
|
||||
password: 'barg@1234@A!@#$',
|
||||
scope: ['admin'],
|
||||
permissions: ['super-admin','development'],
|
||||
username: 'negareh_support'
|
||||
},
|
||||
{
|
||||
first_name: 'barg',
|
||||
last_name: 'admin',
|
||||
password: 'barg123456',
|
||||
scope: ['admin'],
|
||||
permissions: ['super-admin'],
|
||||
username: 'barg_admin'
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,185 @@
|
||||
const {admin} = require('./../fireBaseConfig')
|
||||
|
||||
// var objNotif = {
|
||||
// title:"",
|
||||
// body:""
|
||||
// }
|
||||
|
||||
// const payload = {
|
||||
// notification: objNotif,
|
||||
// data: {
|
||||
// routeName: result.id,
|
||||
// type: "bazaar",
|
||||
// routeType: "viewBazaar",
|
||||
// },
|
||||
// };
|
||||
|
||||
module.exports.notification = {
|
||||
sendBatch : async (inputs) => {
|
||||
const {data, payload} = inputs;
|
||||
|
||||
try {
|
||||
// set variables
|
||||
const failedTokens = [];
|
||||
|
||||
// Set message body
|
||||
const obj = {
|
||||
android: {
|
||||
notification: {
|
||||
sound: 'default',
|
||||
default_sound: true,
|
||||
default_vibrate_timings: true,
|
||||
},
|
||||
},
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
badge: 12,
|
||||
sound: 'default',
|
||||
},
|
||||
},
|
||||
},
|
||||
data: payload.data,
|
||||
notification: {},
|
||||
token: {},
|
||||
};
|
||||
|
||||
// Set ttl if exists
|
||||
if (payload?.android?.ttl) obj.android.ttl = payload.ttl;
|
||||
|
||||
// complete messages body
|
||||
const messages = [];
|
||||
data.map((item) => {
|
||||
const newData = JSON.parse(JSON.stringify(obj));
|
||||
newData.notification.title = item.title;
|
||||
newData.notification.body = item.body;
|
||||
newData.token = item.token;
|
||||
messages.push(newData);
|
||||
});
|
||||
|
||||
// run fcm
|
||||
const response = await admin.messaging().sendAll(messages);
|
||||
|
||||
// operate on result
|
||||
if (response.failureCount > 0) {
|
||||
response?.responses.forEach((resp, idx) => {
|
||||
if (!resp.success) {
|
||||
failedTokens.push({
|
||||
message: resp.error.message,
|
||||
cid: data[idx].cid,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return ;
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
return exits.error(e.message);
|
||||
}
|
||||
},
|
||||
sendMulti : async (inputs) => {
|
||||
const {registrationTokens, payload} = inputs;
|
||||
|
||||
try {
|
||||
// Set message main body
|
||||
const message = {
|
||||
android: {
|
||||
notification: {
|
||||
sound: 'default',
|
||||
default_sound: true,
|
||||
default_vibrate_timings: true,
|
||||
},
|
||||
},
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
badge: 12,
|
||||
sound: 'default',
|
||||
},
|
||||
},
|
||||
},
|
||||
notification: payload.notification,
|
||||
data: payload.data,
|
||||
tokens: registrationTokens,
|
||||
};
|
||||
|
||||
|
||||
// Run fcm
|
||||
const response = await admin.messaging().sendMulticast(message);
|
||||
|
||||
// get some data from response
|
||||
// result.failureCount = response.failureCount;
|
||||
// result.successCount = response.successCount;
|
||||
|
||||
// if there was any failer in sending messsage
|
||||
// if (response.failureCount > 0) {
|
||||
// response.responses.forEach((resp, idx) => {
|
||||
// if (!resp.success) {
|
||||
// failedTokens.push({
|
||||
// token: registrationTokens[idx],
|
||||
// message: resp.error.message,
|
||||
// cid: cid[idx],
|
||||
// });
|
||||
// }
|
||||
// });
|
||||
// }
|
||||
|
||||
// result.failedTokens = failedTokens;
|
||||
|
||||
// send response
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
sendSingle : async (inputs) => {
|
||||
const {registrationTokens, payload} = inputs;
|
||||
|
||||
try {
|
||||
// Set message main body
|
||||
var message = {
|
||||
android: {
|
||||
notification: {
|
||||
sound: 'default',
|
||||
default_sound: true,
|
||||
default_vibrate_timings: true,
|
||||
},
|
||||
},
|
||||
apns: {
|
||||
payload: {
|
||||
aps: {
|
||||
badge: 12,
|
||||
sound: 'default',
|
||||
},
|
||||
},
|
||||
},
|
||||
webpush:{
|
||||
headers:{
|
||||
TTL:"86400"
|
||||
}
|
||||
},
|
||||
notification: payload.notification,
|
||||
data: payload.data,
|
||||
token: registrationTokens,
|
||||
// priority: "high",
|
||||
// timeToLive: 60 * 60 * 24
|
||||
};
|
||||
|
||||
// Check if there is any ttl in payload
|
||||
if (payload?.android?.ttl) message.android.ttl = payload.ttl;
|
||||
|
||||
// Run fcm
|
||||
const response = await admin.messaging().send(message);
|
||||
|
||||
// Check response
|
||||
if (!response) return false;
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.log(e.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,745 @@
|
||||
module.exports._sr = {
|
||||
fa: {
|
||||
required: {
|
||||
token: 'توکن را وارد کنید',
|
||||
field: 'این فیلد نباید خالی باشد',
|
||||
// developer validations
|
||||
remember_me: 'پارامتر remember_me الزامی است',
|
||||
// registration validations
|
||||
name: 'نام را وارد کنید',
|
||||
first_name: 'نام را وارد کنید',
|
||||
last_name: 'نام خانوادگی را وارد کنید',
|
||||
email: 'ایمیل را وارد کنید',
|
||||
national_code: 'کد ملی الزامی است',
|
||||
email_personal: 'ایمیل شخصی الزامی است',
|
||||
email_company: 'ایمیل کمپانی برای اشخاص حقوقی الزامی است',
|
||||
company_name: 'درصورتی که شخص حقوقی هستید، نام کمپانی را وارد کنید',
|
||||
username: 'نام کاربری را وارد کنید',
|
||||
phone_number: 'شماره تماس را وارد کنید',
|
||||
password: 'پسورد را وارد کنید',
|
||||
birthdate: 'تاریخ تولد را وارد کنید',
|
||||
// addressing validations
|
||||
country: 'کشور را وارد کنید',
|
||||
province: 'استان را وارد کنید',
|
||||
city: 'شهر را وارد کنید',
|
||||
address: 'آدرس را وارد کنید',
|
||||
postal_code: 'کد پستی را وارد کنید',
|
||||
plaque: 'پلاک را وارد کنید',
|
||||
receiver_first_name: 'نام گیرنده را وارد کنید',
|
||||
receiver_last_name: 'نام خانوادگی گیرنده را وارد کنید',
|
||||
receiver_mobile: 'شماره موبایل گیرنده را وارد کنید',
|
||||
// global (post - gallery - ...)
|
||||
title: 'عنوان را وارد کنید',
|
||||
caption: 'متن را وارد کنید',
|
||||
description: 'توضیحات را وارد کنید',
|
||||
category: 'دسته بندی را انتخاب کنید',
|
||||
image: 'عکس اجباری است',
|
||||
cover: 'کاور اجباری است',
|
||||
file: 'فایل اجباری است',
|
||||
message: 'پیام را بنویسید',
|
||||
quantity: 'تعداد را وارد کنید',
|
||||
date: 'تاریخ را وارد کنید',
|
||||
reason: 'دلیل را انتخاب کنید',
|
||||
question: 'سوال را بنویسید',
|
||||
answer: 'جواب را بنویسید',
|
||||
price: 'قیمت را وارد کنید',
|
||||
type: 'نوع را انتخاب کنید',
|
||||
discount_code: 'کد تخفیف را وارد کنید',
|
||||
discount_amount: 'مقدار تخفیف را وارد کنید',
|
||||
discount_expire_date: 'تاریخ انقضای کد تخفیف را مشخص کنید',
|
||||
user_id: 'کاربر را انتخاب کنید',
|
||||
index: 'ترتیب را انتخاب کنید'
|
||||
},
|
||||
format: {
|
||||
phone_number: 'فرمت شماره تماس صحیح نیست',
|
||||
email: 'فرمت ایمیل قابل قبول نیست',
|
||||
number: 'مقدار باید از جنس عدد باشد',
|
||||
boolean: 'مقدار باید از جنس Boolean باشد',
|
||||
image: 'فرمت عکس قابل قبول نیست',
|
||||
video: 'فرمت ویدیو قابل قبول نیست',
|
||||
national_code: 'کد ملی صحیح نیست'
|
||||
},
|
||||
min_char: {
|
||||
min2: 'حداقل 2 کاراکتر',
|
||||
min4: 'حداقل 4 کاراکتر',
|
||||
min8: 'حداقل 8 کاراکتر',
|
||||
min10: 'حداقل 10 کاراکتر',
|
||||
min20: 'حداقل 20 کاراکتر',
|
||||
min30: 'حداقل 30 کاراکتر',
|
||||
min40: 'حداقل 40 کاراکتر',
|
||||
min50: 'حداقل 50 کاراکتر',
|
||||
min60: 'حداقل 60 کاراکتر',
|
||||
min100: 'حداقل 100 کاراکتر',
|
||||
min120: 'حداقل 120 کاراکتر',
|
||||
min150: 'حداقل 150 کاراکتر',
|
||||
min200: 'حداقل 200 کاراکتر',
|
||||
data_size: 'حجم قابل قبول حداقل: ',
|
||||
image_width_size: 'عرض حداقل: ',
|
||||
image_height_size: 'ارتفاع حداقل: ',
|
||||
},
|
||||
max_char: {
|
||||
max4: 'حداکثر 4 کاراکتر',
|
||||
max8: 'حداکثر 8 کاراکتر',
|
||||
max10: 'حداکثر 10 کاراکتر',
|
||||
max15: 'حداکثر 15 کاراکتر',
|
||||
max20: 'حداکثر 20 کاراکتر',
|
||||
max30: 'حداکثر 30 کاراکتر',
|
||||
max40: 'حداکثر 40 کاراکتر',
|
||||
max50: 'حداکثر 50 کاراکتر',
|
||||
max60: 'حداکثر 60 کاراکتر',
|
||||
max100: 'حداکثر 100 کاراکتر',
|
||||
max120: 'حداکثر 120 کاراکتر',
|
||||
max150: 'حداکثر 150 کاراکتر',
|
||||
max200: 'حداکثر 200 کاراکتر',
|
||||
data_size: 'حجم قابل قبول حداکثر: ',
|
||||
image_width_size: 'عرض حداکثر: ',
|
||||
image_height_size: 'ارتفاع حداکثر: ',
|
||||
},
|
||||
not_found: {
|
||||
user_id: 'کاربری با این مشخصات وجود ندارد',
|
||||
admin_id: 'ادمینی با این مشخصات وجود ندارد',
|
||||
order_id: 'سفارشی با این مشخصات وجود ندارد',
|
||||
item_id: 'موردی با این مشخصات وجود ندارد',
|
||||
password: 'رمز عبور یا آیدی درست نیست'
|
||||
},
|
||||
duplicated: {
|
||||
username: 'این نام کاربری از قبل وجود دارد',
|
||||
email: 'این ایمیل از قبل وجود دارد',
|
||||
name: 'نام تکراری است',
|
||||
title: 'عنوان تکراری است',
|
||||
phone_number: 'این شماره تماس از قبل وجود دارد'
|
||||
},
|
||||
response: {
|
||||
logged_in: 'شما وارد سیستم شدید',
|
||||
not_logged_in: 'شما وارد سیستم نشدید',
|
||||
logged_out: 'شما از سیستم خارج شدید',
|
||||
unauthenticated: 'غیرمجاز',
|
||||
recovery_link: 'لینک بازیابی فرستاده شد',
|
||||
success_save: 'با موفقیت ثبت شد',
|
||||
success_remove: 'با موفقیت حذف شد',
|
||||
cart_empty: 'سبد خرید خالی است',
|
||||
already_has_address: 'آدرس قبلا اضافه شده',
|
||||
activation_code: 'کد فعالسازی برای شما ارسال شد',
|
||||
activation_email: 'ایمیل فعال سازی برای شما ارسال شد',
|
||||
expired_reset_link: 'این لینک بازیابی منقضی شده است',
|
||||
email_not_confirmed: 'ابتدا ایمیل خود را تایید کنید،لینک فعال سازی قبلا برای شما فرستاده شده است.',
|
||||
expired_activation_link: 'این لینک فعال سازی منقضی شده است',
|
||||
success_activation: 'اکانت شما با موفقیت فعال شد',
|
||||
passwords_not_match: 'پسورد ها یکی نیست',
|
||||
problem: 'مشکلی پیش آمده، لطفا دوباره تلاش کنید.',
|
||||
latinChar: 'لطفا با حروف لاتین بنویسید',
|
||||
persianChar: 'لطفا با حروف فارسی بنویسید',
|
||||
whiteSpace: 'بین حروف و کلمات نباید فاصله باشد',
|
||||
unknownError : 'مشکلی در اجرای درخواست شما بوجود آمده است'
|
||||
},
|
||||
file_types: {
|
||||
jpg: 'فقط فرمت jpg قابل قبول است',
|
||||
png: 'فقط فرمت png قابل قبول است',
|
||||
gif: 'فقط فرمت gif قابل قبول است',
|
||||
pdf: 'فقط فرمت pdf قابل قبول است',
|
||||
txt: 'فقط فرمت txt قابل قبول است',
|
||||
log: 'فقط فرمت log قابل قبول است',
|
||||
mp3: 'فقط فرمت mp3 قابل قبول است',
|
||||
ogg: 'فقط فرمت ogg قابل قبول است',
|
||||
wmv: 'فقط فرمت wmv قابل قبول است',
|
||||
mp4: 'فقط فرمت mp4 قابل قبول است',
|
||||
mov: 'فقط فرمت mov قابل قبول است',
|
||||
mkv: 'فقط فرمت mkv قابل قبول است',
|
||||
flv: 'فقط فرمت flv قابل قبول است'
|
||||
}
|
||||
},
|
||||
en: {
|
||||
required: {
|
||||
token: 'Token is required',
|
||||
field: 'This field is required',
|
||||
// developer validations
|
||||
remember_me: 'Remember_me parameter required',
|
||||
// registration validations
|
||||
name: 'Enter name',
|
||||
first_name: 'Enter first name',
|
||||
last_name: 'Enter last name',
|
||||
national_code: 'National code is required',
|
||||
email: 'Enter email',
|
||||
email_personal: 'Personal email is required',
|
||||
email_company: 'Company email is required for legal entities',
|
||||
company_name: 'Enter company name if you are a legal entity',
|
||||
username: 'Enter username',
|
||||
phone_number: 'Enter phone number',
|
||||
password: 'Enter password',
|
||||
birthdate: 'Enter birthdate',
|
||||
// addressing validations
|
||||
country: 'Enter country',
|
||||
province: 'Enter province',
|
||||
city: 'Enter city',
|
||||
address: 'Enter address',
|
||||
postal_code: 'Enter postal code',
|
||||
plaque: 'Enter plaque',
|
||||
receiver_first_name: 'Enter recipient name',
|
||||
receiver_last_name: 'Enter recipient surname',
|
||||
receiver_mobile: 'Enter recipient\'s mobile number',
|
||||
// global (post - gallery - ...)
|
||||
title: 'Enter title',
|
||||
caption: 'Enter caption',
|
||||
description: 'Enter description',
|
||||
category: 'Select category',
|
||||
image: 'Image is required',
|
||||
cover: 'Cover is required',
|
||||
file: 'File is required',
|
||||
message: 'Write message',
|
||||
quantity: 'Enter quantity',
|
||||
date: 'Enter date',
|
||||
reason: 'Select reason',
|
||||
question: 'Write the question',
|
||||
answer: 'Write the answer',
|
||||
price: 'Enter Price',
|
||||
type: 'Select type',
|
||||
discount_code: 'Enter discount code',
|
||||
discount_amount: 'Enter discount amount',
|
||||
discount_expire_date: 'Specify discount code expiration date',
|
||||
user_id: 'Select user',
|
||||
index: 'Select index'
|
||||
},
|
||||
format: {
|
||||
phone_number: 'Phone number format in incorrect',
|
||||
email: 'Email format is not correct',
|
||||
number: 'Value must be number',
|
||||
boolean: 'Value must be Boolean',
|
||||
image: 'Photo format is not acceptable',
|
||||
video: 'Video format is not acceptable',
|
||||
national_code: 'National code format is not correct'
|
||||
},
|
||||
min_char: {
|
||||
min2: 'At least 2 characters',
|
||||
min4: 'At least 4 characters',
|
||||
min8: 'At least 8 characters',
|
||||
min10: 'At least 10 characters',
|
||||
min20: 'At least 20 characters',
|
||||
min30: 'At least 30 characters',
|
||||
min40: 'At least 40 characters',
|
||||
min50: 'At least 50 characters',
|
||||
min60: 'At least 60 characters',
|
||||
min100: 'At least 100 characters',
|
||||
min120: 'At least 120 characters',
|
||||
min150: 'At least 150 characters',
|
||||
min200: 'At least 200 characters',
|
||||
data_size: 'Acceptable minimum size: ',
|
||||
image_width_size: 'Minimum width: ',
|
||||
image_height_size: 'Minimum height: ',
|
||||
},
|
||||
max_char: {
|
||||
max4: 'Maximum 4 characters',
|
||||
max8: 'Maximum 8 characters',
|
||||
max10: 'Maximum 10 characters',
|
||||
max15: 'Maximum 15 characters',
|
||||
max20: 'Maximum 20 characters',
|
||||
max30: 'Maximum 30 characters',
|
||||
max40: 'Maximum 40 characters',
|
||||
max50: 'Maximum 50 characters',
|
||||
max60: 'Maximum 60 characters',
|
||||
max100: 'Maximum 100 characters',
|
||||
max120: 'Maximum 120 characters',
|
||||
max150: 'Maximum 150 characters',
|
||||
max200: 'Maximum 200 characters',
|
||||
data_size: 'Maximum acceptable size: ',
|
||||
image_width_size: 'Maximum width: ',
|
||||
image_height_size: 'Maximum height: ',
|
||||
},
|
||||
not_found: {
|
||||
user_id: 'There is no user with this profile',
|
||||
admin_id: 'There is no admin with this profile',
|
||||
order_id: 'There is no order with this profile',
|
||||
item_id: 'There is no item with this specification',
|
||||
password: 'Password or ID is incorrect'
|
||||
},
|
||||
duplicated: {
|
||||
username: 'This username already exists',
|
||||
email: 'This email already exists',
|
||||
name: 'Name already exists',
|
||||
title: 'Title already exists',
|
||||
phone_number: 'Phone number already exists'
|
||||
},
|
||||
response: {
|
||||
logged_in: 'You are logged in',
|
||||
not_logged_in: 'You are not logged in',
|
||||
logged_out: 'You are logged out',
|
||||
unauthenticated: 'unauthenticated',
|
||||
recovery_link: 'Recovery link sent',
|
||||
success_save: 'Successfully saved',
|
||||
success_remove: 'Successfully removed',
|
||||
cart_empty: 'Cart is empty',
|
||||
already_has_address: 'Already has address',
|
||||
activation_code: 'Activation code sent to you',
|
||||
activation_email: 'Activation email sent to you',
|
||||
expired_reset_link: 'The current reset pass link has been expired',
|
||||
email_not_confirmed: 'Confirm your email first, the activation link has already been sent to you.',
|
||||
expired_activation_link: 'This activation link has expired',
|
||||
success_activation: 'Your account has been successfully activated',
|
||||
passwords_not_match: 'Passwords are not the same',
|
||||
problem: 'There is a problem, please try again.',
|
||||
latinChar: 'Please write in Latin letters',
|
||||
persianChar: 'Please write in Persian letters',
|
||||
whiteSpace: 'There should be no space between letters and words'
|
||||
},
|
||||
file_types: {
|
||||
jpg: 'Only jpg format is acceptable',
|
||||
png: 'Only png format is acceptable',
|
||||
gif: 'Only gif format is acceptable',
|
||||
pdf: 'Only pdf format is acceptable',
|
||||
txt: 'Only txt format is acceptable',
|
||||
log: 'Only log format is acceptable',
|
||||
mp3: 'Only mp3 format is acceptable',
|
||||
ogg: 'Only ogg format is acceptable',
|
||||
wmv: 'Only wmv format is acceptable',
|
||||
mp4: 'Only mp4 format is acceptable',
|
||||
mov: 'Only mov format is acceptable',
|
||||
mkv: 'Only mkv format is acceptable',
|
||||
flv: 'Only flv format is acceptable'
|
||||
}
|
||||
},
|
||||
de: {
|
||||
required: {
|
||||
token: 'Token is required',
|
||||
field: 'This field is required',
|
||||
// developer validations
|
||||
remember_me: 'Remember_me-Parameter erforderlich',
|
||||
// registration validations
|
||||
name: 'Name eingeben',
|
||||
first_name: 'Name eingeben',
|
||||
last_name: 'Nachnamen eingeben',
|
||||
national_code: "Nationaler Code ist erforderlich",
|
||||
email: 'Email eingeben',
|
||||
email_personal: 'Persönliche E-Mail ist erforderlich',
|
||||
email_company: 'Für juristische Personen ist eine Unternehmens-E-Mail erforderlich',
|
||||
company_name: 'Geben Sie den Firmennamen ein, wenn Sie eine juristische Person sind',
|
||||
username: 'Geben Sie den Benutzernamen ein',
|
||||
phone_number: 'Telefonnummer eingeben',
|
||||
password: 'Passwort eingeben',
|
||||
birthdate: 'Enter birthdate',
|
||||
// addressing validations
|
||||
country: 'Land eingeben',
|
||||
province: 'Stadt betreten',
|
||||
city: 'Stadt betreten',
|
||||
address: 'Adresse eingeben',
|
||||
postal_code: 'Postleitzahl eingeben',
|
||||
plaque: 'Plakette eingeben',
|
||||
receiver_first_name: 'Empfängername eingeben',
|
||||
receiver_last_name: 'Nachname des Empfängers eingeben',
|
||||
receiver_mobile: 'Handynummer des Empfängers eingebenr',
|
||||
// global (post - gallery - ...)
|
||||
title: 'Titel eingeben',
|
||||
caption: 'Beschriftung eingeben',
|
||||
description: 'Beschreibung eingeben',
|
||||
category: 'Kategorie wählen',
|
||||
image: 'Bild ist erforderlich',
|
||||
cover: 'Bild ist erforderlich Abdeckung ist erforderlich',
|
||||
file: 'Datei ist erforderlich',
|
||||
message: 'Nachricht schreiben',
|
||||
quantity: 'Menge eingeben',
|
||||
date: 'Enter date',
|
||||
reason: 'Grund auswählen',
|
||||
question: 'Schreibe die Frage',
|
||||
answer: 'Schreibe die Antwort',
|
||||
price: 'Enter Price',
|
||||
type: 'Select type',
|
||||
discount_code: 'Enter discount code',
|
||||
discount_amount: 'Enter discount amount',
|
||||
discount_expire_date: 'Specify discount code expiration date',
|
||||
user_id: 'Select user',
|
||||
index: 'Select index'
|
||||
},
|
||||
format: {
|
||||
phone_number: 'Telefonnummernformat falsch',
|
||||
email: 'E-Mail-Format nicht korrekt',
|
||||
number: 'Wert muss Nummer sein',
|
||||
boolean: 'Wert muss Boolescher Wert sein',
|
||||
image: 'Photo format is not acceptable',
|
||||
video: 'Video format is not acceptable',
|
||||
national_code: "Nationales Codeformat ist nicht korrekt"
|
||||
},
|
||||
min_char: {
|
||||
min2: 'Mindestens 2 Zeichen',
|
||||
min4: 'Mindestens 4 Zeichen',
|
||||
min8: 'Mindestens 8 Zeichen',
|
||||
min10: 'Mindestens 10 Zeichen',
|
||||
min20: 'Mindestens 20 Zeichen',
|
||||
min30: 'Mindestens 30 Zeichen',
|
||||
min40: 'Mindestens 40 Zeichen',
|
||||
min50: 'Mindestens 50 Zeichen',
|
||||
min60: 'Mindestens 60 Zeichen',
|
||||
min100: 'Mindestens 100 Zeichen',
|
||||
min120: 'Mindestens 120 Zeichen',
|
||||
min150: 'Mindestens 150 Zeichen',
|
||||
min200: 'Mindestens 200 Zeichen',
|
||||
data_size: 'Akzeptable Mindestgröße: ',
|
||||
image_width_size: 'Mindestbreite: ',
|
||||
image_height_size: 'Mindesthöhe: ',
|
||||
},
|
||||
max_char: {
|
||||
max4: 'Maximal 4 Zeichen',
|
||||
max8: 'Maximal 8 Zeichen',
|
||||
max10: 'Maximal 10 Zeichen',
|
||||
max15: 'Maximal 15 Zeichen',
|
||||
max20: 'Maximal 20 Zeichen',
|
||||
max30: 'Maximal 30 Zeichen',
|
||||
max40: 'Maximal 40 Zeichen',
|
||||
max50: 'Maximal 50 Zeichen',
|
||||
max60: 'Maximal 60 Zeichen',
|
||||
max100: 'Maximal 100 Zeichen',
|
||||
max120: 'Maximal 120 Zeichen',
|
||||
max150: 'Maximal 150 Zeichen',
|
||||
max200: 'Maximal 200 Zeichen',
|
||||
data_size: 'Maximal zulässige Größe: ',
|
||||
image_width_size: 'Maximale Breite: ',
|
||||
image_height_size: 'Maximale Höhe: ',
|
||||
},
|
||||
not_found: {
|
||||
user_id: 'Es gibt keinen Benutzer mit diesem Profil',
|
||||
admin_id: 'Es gibt keinen Administrator mit diesem Profil',
|
||||
order_id: 'Es gibt keine Bestellung mit diesem Profil',
|
||||
item_id: 'Es gibt keinen Artikel mit dieser Spezifikation',
|
||||
password: 'Passwort oder ID ist falsch'
|
||||
},
|
||||
duplicated: {
|
||||
username: 'Dieser Benutzername existiert bereits',
|
||||
email: 'Diese E-Mail existiert bereits',
|
||||
name: 'Name ist doppelt',
|
||||
title: 'Titel ist doppelt',
|
||||
phone_number: 'Phone number already exists'
|
||||
},
|
||||
response: {
|
||||
logged_in: 'Sie sind angemeldet',
|
||||
not_logged_in: 'Sie sind nicht angemeldet',
|
||||
logged_out: 'Sie sind abgemeldet',
|
||||
unauthenticated: 'nicht authentifiziert',
|
||||
recovery_link: 'Wiederherstellungslink gesendet',
|
||||
success_save: 'Erfolgreich gespeichert',
|
||||
success_remove: 'Erfolgreich entfernt',
|
||||
cart_empty: 'Warenkorb ist leer',
|
||||
ready_has_address: 'Hat bereits Adresse',
|
||||
activation_code: 'Activation code sent to you',
|
||||
activation_email: 'Activation email sent to you',
|
||||
expired_reset_link: 'Der aktuelle Reset-Pass-Link ist abgelaufen',
|
||||
email_not_confirmed: "Bestätigen Sie zuerst Ihre E-Mail, der Aktivierungslink wurde bereits an Sie gesendet.",
|
||||
expired_activation_link: 'Dieser Aktivierungslink ist abgelaufen',
|
||||
success_activation: 'Ihr Konto wurde erfolgreich aktiviert',
|
||||
passwords_not_match: 'Passwörter sind nicht dasselbe',
|
||||
problem: "Es gibt ein Problem, bitte versuchen Sie es erneut.",
|
||||
latinChar: 'Please write in Latin letters',
|
||||
persianChar: 'Please write in Persian letters',
|
||||
whiteSpace: 'There should be no space between letters and words'
|
||||
},
|
||||
file_types: {
|
||||
jpg: 'Nur das jpg-Format ist akzeptabel',
|
||||
png: 'Nur das png-Format ist akzeptabel',
|
||||
gif: 'Nur das gif-Format ist akzeptabel',
|
||||
pdf: 'Nur das PDF-Format ist akzeptabel',
|
||||
txt: 'Nur das txt-Format ist akzeptabel',
|
||||
log: 'Nur das log-Format ist akzeptabel',
|
||||
mp3: 'Nur das mp3-Format ist akzeptabel',
|
||||
ogg: 'Nur das ogg-Format ist akzeptabel',
|
||||
wmv: 'Nur das wmv-Format ist akzeptabel',
|
||||
mp4: 'Nur das mp4-Format ist akzeptabel',
|
||||
mov: 'Nur das mov-Format ist akzeptabel',
|
||||
mkv: 'Nur das mkv-Format ist akzeptabel',
|
||||
flv: 'Nur das flv-Format ist akzeptabel'
|
||||
}
|
||||
},
|
||||
tr: {
|
||||
required: {
|
||||
token: 'Token is required',
|
||||
field: 'This field is required',
|
||||
// geliştirici doğrulamaları
|
||||
Remember_me: 'Remember_me parametresi gerekli',
|
||||
// kayıt doğrulamaları
|
||||
name: 'Adı girin',
|
||||
first_name: 'Adı girin',
|
||||
last_name: 'Soyadı girin',
|
||||
national_code: "Nationaler Kodu erforderlich",
|
||||
email: 'E-posta girin',
|
||||
email_personal: 'Kişisel e-posta gereklidir',
|
||||
email_company: 'Tüzel kişiler için şirket e-postası gereklidir',
|
||||
company_name: 'Tüzel kişiyseniz şirket adını girin',
|
||||
username: 'Kullanıcı adını girin',
|
||||
phone_number: 'Telefon numarasını girin',
|
||||
password: 'Şifre girin',
|
||||
birthdate: 'Enter birthdate',
|
||||
// doğrulamaları adresleme
|
||||
country: 'Ülke girin',
|
||||
province: 'İl girin',
|
||||
city: 'Şehir girin',
|
||||
address: 'Adres girin',
|
||||
postal_code: 'Posta kodunu girin',
|
||||
plaque: 'Plak girin',
|
||||
receiver_first_name: 'Alıcı adını girin',
|
||||
receiver_last_name: 'Alıcının soyadını girin',
|
||||
receiver_mobile: 'Alıcının cep telefonu numarasını girin',
|
||||
// global (post - galeri - ...)
|
||||
title: 'Başlığı girin',
|
||||
caption: 'Başlık girin',
|
||||
description: 'Açıklama girin',
|
||||
category: 'Kategori seçin',
|
||||
image: 'Resim gerekli',
|
||||
cover: 'Kapak gereklidir',
|
||||
file: 'Dosya gerekli',
|
||||
message: 'Mesaj yaz',
|
||||
quantity: 'Miktar girin',
|
||||
date: 'Enter date',
|
||||
reason: 'Nedeni seçin',
|
||||
question: 'Soruyu yazın',
|
||||
answer: 'Cevabı yaz',
|
||||
price: 'Enter Price',
|
||||
type: 'Select type',
|
||||
discount_code: 'Enter discount code',
|
||||
discount_amount: 'Enter discount amount',
|
||||
discount_expire_date: 'Specify discount code expiration date',
|
||||
user_id: 'Select user',
|
||||
index: 'Select index'
|
||||
},
|
||||
format: {
|
||||
phone_number: 'Telefon numarası biçimi yanlış',
|
||||
email: 'E-posta formatı doğru değil',
|
||||
number: 'Değer sayı olmalıdır',
|
||||
boolean: 'Değer Boole olmalıdır',
|
||||
image: 'Photo format is not acceptable',
|
||||
video: 'Video format is not acceptable',
|
||||
national_code: 'Ulusal kod formatı doğru değil'
|
||||
},
|
||||
min_char: {
|
||||
min2: 'En az 2 karakter',
|
||||
min4: 'En az 4 karakter',
|
||||
min8: 'En az 8 karakter',
|
||||
min10: 'En az 10 karakter',
|
||||
min20: 'En az 20 karakter',
|
||||
min30: 'En az 30 karakter',
|
||||
min40: 'En az 40 karakter',
|
||||
min50: 'En az 50 karakter',
|
||||
min60: 'En az 60 karakter',
|
||||
min100: 'En az 100 karakter',
|
||||
min120: 'En az 120 karakter',
|
||||
min150: 'En az 150 karakter',
|
||||
min200: 'En az 200 karakter',
|
||||
data_size: 'Kabul edilebilir minimum boyut: ',
|
||||
image_width_size: 'Minimum genişlik: ',
|
||||
image_height_size: 'Minimum yükseklik: ',
|
||||
},
|
||||
max_char: {
|
||||
max4: 'Maksimum 4 karakter',
|
||||
max8: 'Maksimum 8 karakter',
|
||||
max10: 'Maksimum 10 karakter',
|
||||
max15: 'Maksimum 15 karakter',
|
||||
max20: 'Maksimum 20 karakter',
|
||||
max30: 'Maksimum 30 karakter',
|
||||
max40: 'Maksimum 40 karakter',
|
||||
max50: 'Maksimum 50 karakter',
|
||||
max60: 'Maksimum 60 karakter',
|
||||
max100: 'Maksimum 100 karakter',
|
||||
max120: 'Maksimum 120 karakter',
|
||||
max150: 'Maksimum 150 karakter',
|
||||
max200: 'Maksimum 200 karakter',
|
||||
data_size: 'Kabul edilebilir maksimum boyut: ',
|
||||
image_width_size: 'Maksimum genişlik: ',
|
||||
image_height_size: 'Maksimum yükseklik: ',
|
||||
},
|
||||
not_found: {
|
||||
user_id: 'Bu profile sahip kullanıcı yok',
|
||||
admin_id: 'Bu profile sahip yönetici yok',
|
||||
order_id: 'Bu profilde sipariş yok',
|
||||
item_id: 'Bu spesifikasyona sahip hiçbir öğe yok',
|
||||
password: 'Şifre veya kimlik yanlış'
|
||||
},
|
||||
duplicated: {
|
||||
username: 'Bu kullanıcı adı zaten mevcut',
|
||||
email: 'Bu email zaten var',
|
||||
name: 'Ad çift',
|
||||
title: 'Başlık yineleniyor',
|
||||
phone_number: 'Phone number already exists'
|
||||
},
|
||||
response: {
|
||||
logged_in: 'Giriş yaptınız',
|
||||
not_logged_in: 'Giriş yapmadınız',
|
||||
logged_out: 'Çıkış yaptınız',
|
||||
unauthenticated: 'unauthenticated',
|
||||
recovery_link: 'Kurtarma bağlantısı gönderildi',
|
||||
success_save: 'Başarıyla kaydedildi',
|
||||
success_remove: 'Başarıyla kaldırıldı',
|
||||
cart_empty: 'Sepet boş',
|
||||
already_has_address: 'Zaten adresi var',
|
||||
activation_code: 'Activation code sent to you',
|
||||
activation_email: 'Activation email sent to you',
|
||||
expired_reset_link: 'Mevcut sıfırlama geçiş bağlantısının süresi doldu',
|
||||
email_not_confirmed: 'Önce e-postanızı onaylayın, aktivasyon bağlantısı size zaten gönderildi.',
|
||||
expired_activation_link: "Bu aktivasyon bağlantısının süresi doldu",
|
||||
success_activation: 'Hesabınız başarıyla etkinleştirildi',
|
||||
passwords_not_match: 'Şifreler aynı değil',
|
||||
problem: 'Bir sorun var, lütfen tekrar deneyin.',
|
||||
latinChar: 'Please write in Latin letters',
|
||||
persianChar: 'Please write in Persian letters',
|
||||
whiteSpace: 'There should be no space between letters and words'
|
||||
},
|
||||
file_types: {
|
||||
jpg: 'Yalnızca jpg formatı kabul edilebilir',
|
||||
png: 'Sadece png formatı kabul edilebilir',
|
||||
gif: 'Yalnızca gif formatı kabul edilebilir',
|
||||
pdf: 'Yalnızca pdf formatı kabul edilebilir',
|
||||
txt: 'Yalnızca txt formatı kabul edilebilir',
|
||||
log: 'Yalnızca log formatı kabul edilebilir',
|
||||
mp3: 'Yalnızca mp3 formatı kabul edilebilir',
|
||||
ogg: 'Yalnızca ogg formatı kabul edilebilir',
|
||||
wmv: 'Yalnızca wmv formatı kabul edilebilir',
|
||||
mp4: 'Yalnızca mp4 formatı kabul edilebilir',
|
||||
mov: 'Yalnızca mov formatı kabul edilebilir',
|
||||
mkv: 'Yalnızca mkv formatı kabul edilebilir',
|
||||
flv: 'Yalnızca flv biçimi kabul edilebilir'
|
||||
}
|
||||
},
|
||||
it: {
|
||||
required: {
|
||||
token: 'Token is required',
|
||||
field: 'This field is required',
|
||||
// convalide dello sviluppatore
|
||||
Remember_me: "Remember_me parameter required",
|
||||
// convalide della registrazione
|
||||
name: "Inserisci nome",
|
||||
first_name: "Inserisci nome",
|
||||
last_name: "Inserisci il cognome",
|
||||
national_code: "Il codice Nationaler è comune",
|
||||
email: "Enter email",
|
||||
email_personal: "L'email personale è obbligatoria",
|
||||
email_company: "L'email aziendale è obbligatoria per le persone giuridiche",
|
||||
company_name: "Inserisci il nome dell'azienda se sei una persona giuridica",
|
||||
username: "Inserisci nome utente",
|
||||
phone_number: "Inserisci numero di telefono",
|
||||
password: "Inserisci password",
|
||||
birthdate: 'Enter birthdate',
|
||||
// indirizzamento delle convalide
|
||||
country: "Inserisci paese",
|
||||
province: "Inserisci provincia",
|
||||
city: "Inserisci città",
|
||||
address: "Inserisci indirizzo",
|
||||
postal_code: "Inserisci codice postale",
|
||||
plaque: "Inserisci targa",
|
||||
receiver_first_name: "Inserisci il nome del destinatario",
|
||||
receiver_last_name: "Inserisci il cognome del destinatario",
|
||||
receiver_mobile: "Inserisci il numero di cellulare del destinatario",
|
||||
// globale (post - gallery - ...)
|
||||
title: "Inserisci titolo",
|
||||
caption: "Inserisci didascalia",
|
||||
description: "Inserisci descrizione",
|
||||
category: "Seleziona categoria",
|
||||
image: "L'immagine è obbligatoria",
|
||||
cover: "Cover is required",
|
||||
file: "Il file è obbligatorio",
|
||||
message: "Scrivi messaggio",
|
||||
quantity: "Inserisci quantità",
|
||||
date: 'Enter date',
|
||||
reason: 'Seleziona motivo',
|
||||
question: 'Scrivi la domanda',
|
||||
answer: 'Scrivi la risposta',
|
||||
price: 'Enter Price',
|
||||
type: 'Select type',
|
||||
discount_code: 'Enter discount code',
|
||||
discount_amount: 'Enter discount amount',
|
||||
discount_expire_date: 'Specify discount code expiration date',
|
||||
user_id: 'Select user',
|
||||
index: 'Select index'
|
||||
},
|
||||
format: {
|
||||
phone_number: "Formato del numero di telefono non corretto",
|
||||
email: "Formato email non corretto",
|
||||
number: "Il valore deve essere un numero",
|
||||
boolean: "Il valore deve essere booleano",
|
||||
image: 'Photo format is not acceptable',
|
||||
video: 'Video format is not acceptable',
|
||||
national_code: "Il formato del codice nazionale non è corretto"
|
||||
},
|
||||
min_char: {
|
||||
min2: "Almeno 2 caratteri",
|
||||
min4: "Almeno 4 caratteri",
|
||||
min8: "Almeno 8 caratteri",
|
||||
min10: "Almeno 10 caratteri",
|
||||
min20: "Almeno 20 caratteri",
|
||||
min30: "Almeno 30 caratteri",
|
||||
min40: "Almeno 40 caratteri",
|
||||
min50: "Almeno 50 caratteri",
|
||||
min60: "Almeno 60 caratteri",
|
||||
min100: "Almeno 100 caratteri",
|
||||
min120: "Almeno 120 caratteri",
|
||||
min150: "Almeno 150 caratteri",
|
||||
min200: "Almeno 200 caratteri",
|
||||
data_size: "Dimensione minima accettabile: ",
|
||||
image_width_size: "Larghezza minima: ",
|
||||
image_height_size: "Altezza minima: ",
|
||||
},
|
||||
max_char: {
|
||||
max4: "Massimo 4 caratteri",
|
||||
max8: "Massimo 8 caratteri",
|
||||
max10: "Massimo 10 caratteri",
|
||||
max15: "Massimo 15 caratteri",
|
||||
max20: "Massimo 20 caratteri",
|
||||
max30: "Massimo 30 caratteri",
|
||||
max40: "Massimo 40 caratteri",
|
||||
max50: "Massimo 50 caratteri",
|
||||
max60: "Massimo 60 caratteri",
|
||||
max100: "Massimo 100 caratteri",
|
||||
max120: "Massimo 120 caratteri",
|
||||
max150: "Massimo 150 caratteri",
|
||||
max200: "Massimo 200 caratteri",
|
||||
data_size: "Dimensione massima accettabile: ",
|
||||
image_width_size: "Larghezza massima: ",
|
||||
image_height_size: "Altezza massima: ",
|
||||
},
|
||||
not_found: {
|
||||
user_id: "Nessun utente con questo profilo",
|
||||
admin_id: "Nessun amministratore con questo profilo",
|
||||
order_id: "Nessun ordine con questo profilo",
|
||||
item_id: "Nessun articolo con questa specifica",
|
||||
password: "La password o l'ID non sono corretti"
|
||||
},
|
||||
duplicated: {
|
||||
username: "Questo nome utente esiste già",
|
||||
email: "Questa email esiste già",
|
||||
name: "Il nome è duplicato",
|
||||
title: "Il titolo è duplicato",
|
||||
phone_number: 'Phone number already exists'
|
||||
},
|
||||
response: {
|
||||
logged_in: "Hai effettuato l'accesso",
|
||||
not_logged_in: "Non sei loggato",
|
||||
logged_out: "Sei disconnesso",
|
||||
unauthenticated: "unauthenticated",
|
||||
recovery_link: "Link di ripristino inviato",
|
||||
success_save: "Salvataggio riuscito",
|
||||
success_remove: "Rimosso con successo",
|
||||
cart_empty: "Il carrello è vuoto",
|
||||
already_has_address: "Ha già indirizzo",
|
||||
activation_code: 'Activation code sent to you',
|
||||
activation_email: 'Activation email sent to you',
|
||||
expired_reset_link: "L'attuale link del passaggio di reimpostazione è scaduto",
|
||||
email_not_confirmed: "Conferma prima la tua email, il link di attivazione ti è già stato inviato.",
|
||||
expired_activation_link: "Questo link di attivazione è scaduto",
|
||||
success_activation: "Il tuo account è stato attivato con successo",
|
||||
passwords_not_match: "Le password non sono le stesse",
|
||||
problem: "Si è verificato un problema, riprova.",
|
||||
latinChar: 'Please write in Latin letters',
|
||||
persianChar: 'Please write in Persian letters',
|
||||
whiteSpace: 'There should be no space between letters and words'
|
||||
},
|
||||
file_types: {
|
||||
jpg: "È accettabile solo il formato jpg",
|
||||
png: "È accettabile solo il formato png",
|
||||
gif: "È accettabile solo il formato GIF",
|
||||
pdf: "È accettabile solo il formato pdf",
|
||||
txt: "È accettabile solo il formato txt",
|
||||
log: "È accettabile solo il formato log",
|
||||
mp3: "È accettabile solo il formato mp3",
|
||||
ogg: "È accettabile solo il formato ogg",
|
||||
wmv: "È accettabile solo il formato wmv",
|
||||
mp4: "È accettabile solo il formato mp4",
|
||||
mov: "È accettabile solo il formato mov",
|
||||
mkv: "È accettabile solo il formato mkv",
|
||||
flv: "È accettabile solo il formato flv"
|
||||
}
|
||||
},
|
||||
supportedImageFormats: ['jpg', 'jpeg', 'png', 'webp', 'svg', 'svg+xml'],
|
||||
supportedVideoFormats: ['mp4', 'avi', 'wmv']
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
const {Router} = require('express')
|
||||
const router = Router()
|
||||
/////////////////////////////////////////////////////////// controllers
|
||||
const sliderController = require('../controllers/sliderController')
|
||||
const foodsController = require('../controllers/foodsController')
|
||||
const galleryController = require('../controllers/galleryController')
|
||||
const contactUsController = require('../controllers/contactUsController')
|
||||
const userController = require('../controllers/userController')
|
||||
const menuTypeController = require('../controllers/menuTypeController')
|
||||
const jobController = require('../controllers/jobController')
|
||||
const foodCategoryController = require('../controllers/foodCategoryController')
|
||||
const partySetController = require('../controllers/partySetController')
|
||||
const subscribersController = require('../controllers/subscribersController')
|
||||
const storeInfoController = require('../controllers/storeInfoController')
|
||||
const orderController = require('../controllers/orderController')
|
||||
const notificationController = require('../controllers/notificationController')
|
||||
const pagerController = require('../controllers/pagerController')
|
||||
|
||||
//////////////// admins
|
||||
router.post('/admin', userController.register_admin)
|
||||
router.get('/admins/:branchId', userController.get_all_admins)
|
||||
router.get('/admin/:id', userController.get_one_admin)
|
||||
router.put('/admin/:id', userController.update_admin)
|
||||
router.put('/changeAdminPasswordByAdmin/:id', userController.change_admin_password_by_another)
|
||||
router.delete('/admin/:id', userController.remove_admin)
|
||||
router.get('/permissions', userController.permissions)
|
||||
//////////////// users
|
||||
router.get('/users/:branchId', userController.get_all_users)
|
||||
router.get('/users/forReport/:branchId', userController.get_all_users_for_reports)
|
||||
router.get('/users/getAll/:branchId', userController.get_all_users_without_paginate)
|
||||
router.get('/user/:id', userController.get_one_admin)
|
||||
router.post('/discountCode', userController.generate_discount_code_for_users)
|
||||
router.get('/discountCodes/:branchId', userController.get_all_discounts_for_admin)
|
||||
router.delete('/discountCode/:id', userController.delete_discount_code)
|
||||
router.put('/address/:id', userController.update_user_address_by_admin)
|
||||
router.delete('/address/:id', userController.remove_user_address)
|
||||
|
||||
//////////////// slider
|
||||
router.post('/slider', sliderController.create)
|
||||
router.put('/slider/:id', sliderController.update)
|
||||
router.delete('/slider/:id', sliderController.delete)
|
||||
|
||||
//////////////// menu types
|
||||
router.post('/menuType', menuTypeController.create)
|
||||
router.get('/menuType/getAll/:branchId', menuTypeController.get_all_for_panel)
|
||||
router.get('/allMenuType/getAll/:branchId', menuTypeController.get_all_wihout_paginate)
|
||||
router.put('/menuType/:id', menuTypeController.update)
|
||||
router.delete('/menuType/:id', menuTypeController.delete)
|
||||
|
||||
//////////////// job
|
||||
router.post('/job', jobController.create)
|
||||
router.get('/job', jobController.get_all_for_panel)
|
||||
router.get('/job/:id', jobController.get_one)
|
||||
router.put('/job/:id', jobController.update)
|
||||
router.delete('/job/:id', jobController.delete)
|
||||
|
||||
//////////////// food categories
|
||||
router.post('/foodCategory', foodCategoryController.create)
|
||||
router.get('/foodCategory/getAll/:branchId', foodCategoryController.get_all_for_panel)
|
||||
router.put('/foodCategory/:id', foodCategoryController.update)
|
||||
router.delete('/foodCategory/:id', foodCategoryController.delete)
|
||||
|
||||
//////////////// foods
|
||||
router.post('/food', foodsController.create)
|
||||
router.post('/food/search', foodsController.search)
|
||||
router.get('/food/getAll/:branchId', foodsController.getAllForPanel)
|
||||
router.get('/food/:id' , foodsController.getOneByAdmin)
|
||||
router.put('/food/:id', foodsController.update)
|
||||
router.delete('/food/:id', foodsController.delete)
|
||||
|
||||
//////////////// food comments
|
||||
router.post('/commentStatus/:id', foodsController.confirm_comment_by_admin)
|
||||
router.post('/replayComment/:id', foodsController.reply_comment_by_admin)
|
||||
router.delete('/deleteComment/:id', foodsController.remove_comment_by_admin)
|
||||
|
||||
//////////////// party set
|
||||
router.post('/partySet', partySetController.create)
|
||||
router.put('/partySet/:id', partySetController.update)
|
||||
router.delete('/partySet/:id', partySetController.delete)
|
||||
router.get('/partySets', partySetController.getAll_for_admin)
|
||||
|
||||
//////////////// gallery
|
||||
router.post('/gallery', galleryController.create)
|
||||
router.put('/gallery/:id', galleryController.update)
|
||||
router.delete('/gallery/:id', galleryController.delete)
|
||||
|
||||
//////////////// contact us
|
||||
router.get('/contactUsMessages', contactUsController.getAll)
|
||||
router.get('/contactUsMessages/:id', contactUsController.getOne)
|
||||
|
||||
//////////////// subscribers
|
||||
router.get('/subscribers', subscribersController.getAll)
|
||||
router.get('/subscriber/:id', subscribersController.getOne)
|
||||
router.delete('/subscriber/:id', subscribersController.deleteOne)
|
||||
|
||||
//////////////// store info
|
||||
router.post('/store/create', storeInfoController.create)
|
||||
router.post('/store/:id', storeInfoController.update)
|
||||
router.get('/store/getAll', storeInfoController.getAll)
|
||||
router.get('/store/:id', storeInfoController.getOne)
|
||||
|
||||
//////////////// order
|
||||
// router.delete('/order/:id', orderController)
|
||||
router.get('/order/getAll/:branchId', orderController.getAllOrders)
|
||||
router.get('/order/forReport/:branchId', orderController.getOrdersForReport)
|
||||
router.post('/order/report/:branchId', orderController.reports)
|
||||
router.post('/order/search', orderController.search)
|
||||
router.get('/order/:id', orderController.getOneOrder)
|
||||
router.delete('/order/:id', orderController.deleteOrder)
|
||||
router.put('/order/:order_id', orderController.addStatusToOrder)
|
||||
// router.get('/order/:id', orderController.getAll_for_admin)
|
||||
|
||||
/////////////// payments
|
||||
router.get('/payments/:id' , orderController.getAllPaymentByAdmin)
|
||||
router.put('/payments/:id' , orderController.changePayStatus)
|
||||
|
||||
router.post('/addFcmToken' , userController.addFcmToken)
|
||||
|
||||
/////////////// send notification
|
||||
router.post('/notification' , notificationController.send)
|
||||
|
||||
//////////////// page
|
||||
router.get('/pager' , pagerController.send)
|
||||
router.get('/test' , orderController.testNotif)
|
||||
|
||||
/////////////// convert data
|
||||
router.post('/addStoreId', storeInfoController.addBranchIdForAllData)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,17 @@
|
||||
const {Router} = require('express')
|
||||
const router = Router()
|
||||
const userController = require('../controllers/userController')
|
||||
|
||||
router.post('/registerUser', userController.get_phone_number)
|
||||
router.post('/resendRegisterToken/:mobile_number', userController.resend_user_resgistration_token)
|
||||
router.post('/validateRegisterToken', userController.validate_user_temp_token)
|
||||
router.post('/addNameToRegistration', userController.add_name_to_user_registration)
|
||||
router.post('/addPasswordToRegistration', userController.add_password_to_user_registration)
|
||||
router.post('/needTempToken/:mobile_number', userController.generate_temp_token_for_user)
|
||||
|
||||
router.post('/login', userController.login)
|
||||
router.post('/loginUser', userController.login_user)
|
||||
router.delete('/logout', userController.logout)
|
||||
router.get('/user', userController.getUser)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,90 @@
|
||||
const {Router} = require('express')
|
||||
const router = Router()
|
||||
const {isUser,isAdmin , isLoggedIn} = require('./../authentication');
|
||||
|
||||
/////////////////////////////////////////////////////////// controllers
|
||||
const sliderController = require('../controllers/sliderController')
|
||||
const foodsController = require('../controllers/foodsController')
|
||||
const orderController = require('../controllers/orderController')
|
||||
const galleryController = require('../controllers/galleryController')
|
||||
const subscribersController = require('../controllers/subscribersController')
|
||||
const contactUsController = require('../controllers/contactUsController')
|
||||
const partySetController = require('../controllers/partySetController')
|
||||
const foodCategoryController = require('../controllers/foodCategoryController')
|
||||
const menuTypeController = require('../controllers/menuTypeController')
|
||||
const jobController = require('../controllers/jobController')
|
||||
const storeInfoController = require('../controllers/storeInfoController')
|
||||
const userController = require('../controllers/userController')
|
||||
const pagerController = require('../controllers/pagerController')
|
||||
|
||||
/////////////////////////////////////////////////////////// routes
|
||||
// router.use('*' , isLoggedIn);
|
||||
|
||||
//////////////// slider
|
||||
router.get('/slider', sliderController.getAll)
|
||||
router.get('/slider/:id', sliderController.getOne)
|
||||
|
||||
//////////////// menu types
|
||||
router.get('/menuTypes/getAll/:branchId', menuTypeController.get_all_for_web)
|
||||
router.get('/menuType/:id', menuTypeController.get_one)
|
||||
|
||||
//////////////// food categories
|
||||
router.get('/foodCategories/getAll/:branchId', foodCategoryController.get_all_for_web)
|
||||
router.get('/foodCategories/getAll', foodCategoryController.get_all_for_web)
|
||||
router.get('/foodCategory/:id', foodCategoryController.get_one)
|
||||
|
||||
//////////////// foods
|
||||
router.get('/foods/allWebsite' , foodsController.getAllForWebSite)
|
||||
router.get('/foods/getAll/:branchId', isLoggedIn , foodsController.getAll)
|
||||
router.get('/food/:id', isLoggedIn , foodsController.getOne)
|
||||
|
||||
//////////////// party sets
|
||||
router.get('/partySets', partySetController.getAll)
|
||||
router.get('/partySet/:id', partySetController.getOne)
|
||||
|
||||
//////////////// gallery
|
||||
router.get('/gallery', galleryController.getAll)
|
||||
router.get('/gallery/:id', galleryController.getOne)
|
||||
|
||||
//////////////// subscribers
|
||||
router.post('/subscribers', subscribersController.create)
|
||||
|
||||
//////////////// contact us
|
||||
router.post('/contact', contactUsController.create)
|
||||
|
||||
//////////////// cart
|
||||
router.post('/cart' , isLoggedIn , orderController.addToCart)
|
||||
router.get('/cart/getAll/:branchId' , isLoggedIn , orderController.getCartItems) /// get all user cart items
|
||||
router.put('/cart/:item_id' , isLoggedIn , orderController.updateCart) /// change quantity
|
||||
router.delete('/cart' , isLoggedIn , orderController.deleteAllCartItem)
|
||||
|
||||
//////////////// order
|
||||
router.post('/reOrder/:orderId' , isLoggedIn , orderController.reOrder)
|
||||
|
||||
router.post('/order' , isLoggedIn , orderController.addOrder)
|
||||
router.get('/order' , isLoggedIn , orderController.getCartItems) /// get all user cart items
|
||||
router.get('/order/getAll/:branchId' , isLoggedIn , orderController.getOrders) /// get all user cart items
|
||||
router.get('/order/computeOrder/:branchId' , isLoggedIn , orderController.computePrice) /// compute order
|
||||
router.post('/order/payOrder' , isLoggedIn , orderController.orderPay) /// pay order
|
||||
router.get('/order/responsePayment' , orderController.getPaymentResponse) /// get response pay order
|
||||
router.get('/getAllFoodRate/:order_id' , isLoggedIn , orderController.getAllRateFood) /// get all food for rate
|
||||
|
||||
router.post('/buyClub' , isLoggedIn , orderController.buyClub)
|
||||
|
||||
//////////////// store info
|
||||
router.get('/storeInfo/:id' , storeInfoController.getStoreInfoForUser)
|
||||
router.get('/storeInfo' , storeInfoController.getAllBranchForUser)
|
||||
|
||||
/////////////// jobs
|
||||
router.get('/job' , jobController.get_all_for_mobile)
|
||||
|
||||
////////////// export exel
|
||||
router.get('/users/exportExel/:id', userController.exportExel)
|
||||
|
||||
/////////////// test notif
|
||||
router.post('/notif' , pagerController.test)
|
||||
// router.post('/notif' , orderController.testNotif)
|
||||
// router.post('/chromenotif' , orderController.chromeNotif)
|
||||
router.get('/test' , orderController.testNotif)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,43 @@
|
||||
const {Router} = require('express')
|
||||
const router = Router()
|
||||
const {isUser,isAdmin , isLoggedIn} = require('./../authentication');
|
||||
|
||||
/////// controllers
|
||||
const userController = require('../controllers/userController')
|
||||
const foodsController = require('../controllers/foodsController')
|
||||
const orderController = require('../controllers/orderController')
|
||||
|
||||
/////////// user address
|
||||
router.post('/address', userController.add_address_to_user)
|
||||
router.get('/address/:storeId', userController.getAlladdress)
|
||||
router.post('/address/:id', userController.setDefaultAddress) /// set default address
|
||||
router.put('/address/:id', userController.update_user_address)
|
||||
router.delete('/address/:id', userController.remove_user_address)
|
||||
|
||||
|
||||
////////// user info
|
||||
router.put('/updateUser', userController.update_user)
|
||||
router.put('/updateUserPassword', userController.change_user_password)
|
||||
|
||||
/////////// rate foods and order
|
||||
router.post('/rateFood/:id', foodsController.rate_food)
|
||||
router.get('/getFoods/:order_id', orderController.getAllRateFood)
|
||||
router.post('/orderRate/:order_id', orderController.rateOrderAndFood)
|
||||
router.get('/getAllComments/:branchId', userController.getAllComments);
|
||||
|
||||
////////// get one order
|
||||
router.get('/order/:id' , orderController.getOneOrderByUser)
|
||||
|
||||
////////// payments
|
||||
router.get('/payments' , orderController.getAllPaymentByUser)
|
||||
|
||||
///////// bag
|
||||
router.post('/bag' , orderController.increaseBag)
|
||||
|
||||
//////// discounts
|
||||
router.get('/getDiscounts/:branchId' , userController.getAllDiscountCodeOfUser)
|
||||
|
||||
//////// add token
|
||||
router.post('/addToken' , userController.addFcmTokenUser)
|
||||
|
||||
module.exports = router
|
||||
@@ -0,0 +1,28 @@
|
||||
const Order = require('../models/Order')
|
||||
module.exports.initAdmin = async () => {
|
||||
try {
|
||||
global.adminIo = io.of('/admin')
|
||||
|
||||
// admins middlewares1
|
||||
// admin.use(isAdmin)
|
||||
|
||||
// attach events
|
||||
adminIo.on('connection', socket => {
|
||||
console.log('admin connected')
|
||||
/// /////////////////////////////////////////////////////// handle connection error
|
||||
socket.on('connect_error', err => {
|
||||
console.log(err.message)
|
||||
})
|
||||
})
|
||||
}catch (e) {
|
||||
console.log(e.message)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports.sendNotifyOrder = async (branchId) => {
|
||||
try {
|
||||
adminIo.emit('order' , {branchId})
|
||||
}catch (e) {
|
||||
console.log(e.message)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
const {initAdmin} = require('./adminNotify')
|
||||
|
||||
function init(server) {
|
||||
// const http = require('http');
|
||||
// const server = http.createServer(app);
|
||||
const { Server } = require("socket.io");
|
||||
global.io
|
||||
|
||||
io = new Server(server);
|
||||
|
||||
initAdmin()
|
||||
}
|
||||
|
||||
|
||||
module.exports = init
|
||||
@@ -0,0 +1,79 @@
|
||||
const axios = require('axios')
|
||||
const requestUrl = 'https://api.zarinpal.com/pg/v4/payment/request.json'
|
||||
const verifyUrl = 'https://api.zarinpal.com/pg/v4/payment/verify.json'
|
||||
const merchant_id = '37d54b62-faf7-40c9-b831-768abe5b48db'
|
||||
// const merchant_id = 'c84c4594-a306-werd-asdd-d5d6eb042081'
|
||||
// const callback_url = 'http://localhost:9964/payresult'
|
||||
// const callback_url = 'https://app.bargrestaurant.com/payresult'
|
||||
const callback_url = 'https://bargrestaurant.com/payresult'
|
||||
|
||||
|
||||
module.exports = {
|
||||
request: async (amount , description , user) => {
|
||||
try {
|
||||
const data = {
|
||||
merchant_id,
|
||||
callback_url,
|
||||
amount,
|
||||
description,
|
||||
metadata : {mobile : user.mobile_number}
|
||||
}
|
||||
const request = await axios.post(requestUrl , data)
|
||||
|
||||
if (request?.data?.data?.code === 100){
|
||||
return {
|
||||
status : true,
|
||||
response : request.data.data
|
||||
}
|
||||
}else {
|
||||
return {
|
||||
status : false,
|
||||
response : request.data.errors
|
||||
}
|
||||
}
|
||||
}catch (error){
|
||||
return {
|
||||
status : false,
|
||||
response : error.message
|
||||
}
|
||||
}
|
||||
},
|
||||
verify : async (amount , transactionId) => {
|
||||
try {
|
||||
const data = {
|
||||
merchant_id,
|
||||
amount,
|
||||
authority : transactionId
|
||||
}
|
||||
const request = await axios.post(verifyUrl , data)
|
||||
|
||||
console.log('request',request)
|
||||
|
||||
if (request?.data?.data?.code === 100){
|
||||
return {
|
||||
status : true,
|
||||
code : 100,
|
||||
response : request.data.data
|
||||
}
|
||||
}else if (request?.data?.data?.code === 101){
|
||||
return {
|
||||
status : true,
|
||||
code : 101,
|
||||
response : 'این پرداخت یک بار قبلا تایید شده است'
|
||||
}
|
||||
} else {
|
||||
return {
|
||||
status : false,
|
||||
code : -1,
|
||||
response : request.data.errors
|
||||
}
|
||||
}
|
||||
}catch (error){
|
||||
return {
|
||||
status : false,
|
||||
code : -1,
|
||||
response : error.message
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user