Files
hamid.zarghami1@gmail.com e644edbd65 transfer project in github
2024-05-12 15:29:27 +03:30

436 lines
16 KiB
JavaScript

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);
}
}
]