feat: add route to update and add cardbank and fix
This commit is contained in:
@@ -4,69 +4,101 @@ const { checkValidations } = require('../plugins/controllersHelperFunctions')
|
|||||||
const User = require('../models/GPS.User')
|
const User = require('../models/GPS.User')
|
||||||
|
|
||||||
module.exports.addCard = [
|
module.exports.addCard = [
|
||||||
[
|
[
|
||||||
body('holderName').notEmpty().isString().withMessage(_sr.fa.required.name),
|
body('holderName').notEmpty().isString().withMessage(_sr.fa.required.name),
|
||||||
body('PAN').notEmpty().isInt().withMessage(_sr.fa.required.store_number),
|
body('PAN').notEmpty().isInt().withMessage(_sr.fa.required.store_number),
|
||||||
body('IBAN').notEmpty().isIBAN().withMessage(_sr.fa.required.address)
|
body('IBAN').notEmpty().isLength({ min: 24, max: 24 }).withMessage(_sr.fa.required.iban)
|
||||||
],
|
],
|
||||||
checkValidations(validationResult),
|
checkValidations(validationResult),
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const { holderName, PAN, IBAN } = req.body;
|
const { holderName, PAN, IBAN } = req.body
|
||||||
const userData = await User.findById(req.user_id).select('id cardBank')
|
const userData = await User.findById(req.user_id).select('id cardBank')
|
||||||
if (userData?.cardBank && Array.isArray(userData?.cardBank)) {
|
if (userData?.cardBank && Array.isArray(userData?.cardBank)) {
|
||||||
userData.cardBank.push({
|
userData.cardBank.push({
|
||||||
holderName,
|
holderName,
|
||||||
PAN,
|
PAN,
|
||||||
IBAN
|
IBAN
|
||||||
})
|
})
|
||||||
userData.save()
|
userData.save()
|
||||||
res.status(201).json({ msg: 'با موفقیت ثبت شد ' })
|
res.status(201).json({ msg: 'با موفقیت ثبت شد ' })
|
||||||
} else {
|
} else {
|
||||||
userData.cardBank = [{
|
userData.cardBank = [
|
||||||
holderName,
|
{
|
||||||
PAN,
|
holderName,
|
||||||
IBAN
|
PAN,
|
||||||
}];
|
IBAN
|
||||||
userData.save()
|
}
|
||||||
res.status(201).json({ msg: 'با موفقیت ثبت شد ' })
|
]
|
||||||
}
|
userData.save()
|
||||||
} catch (error) {
|
res.status(201).json({ msg: 'با موفقیت ثبت شد ' })
|
||||||
res.status(500).json({ msg: error })
|
}
|
||||||
|
} catch (error) {
|
||||||
}
|
res.status(500).json({ msg: error })
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
module.exports.getAll = [
|
module.exports.getAll = [
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const userData = await User.findById(req.user_id).select('id cardBank')
|
const userData = await User.findById(req.user_id).select('id cardBank')
|
||||||
res.status(200).json(userData)
|
res.status(200).json(userData)
|
||||||
}
|
}
|
||||||
|
]
|
||||||
|
module.exports.getOne = [
|
||||||
|
async (req, res) => {
|
||||||
|
const userCart = await User.findOne({ _id: req.user_id, 'cardBank._id': req.params.id }).select('id cardBank')
|
||||||
|
console.log(userCart)
|
||||||
|
res.status(200).json({ userCart: userCart.cardBank[0] })
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
module.exports.updateCard = [
|
||||||
|
[
|
||||||
|
param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه می باشد'),
|
||||||
|
body('holderName').notEmpty().isString().withMessage(_sr.fa.required.name),
|
||||||
|
body('PAN').notEmpty().isInt().withMessage(_sr.fa.required.store_number),
|
||||||
|
body('IBAN').notEmpty().isLength({ min: 24, max: 24 }).withMessage(_sr.fa.required.iban)
|
||||||
|
],
|
||||||
|
checkValidations(validationResult),
|
||||||
|
async (req, res) => {
|
||||||
|
try {
|
||||||
|
const { holderName, PAN, IBAN } = req.body
|
||||||
|
const userData = await User.findOneAndUpdate(
|
||||||
|
{ _id: req.user_id, 'cardBank._id': req.params.id },
|
||||||
|
{
|
||||||
|
$set: {
|
||||||
|
'cardBank.$.holderName': holderName,
|
||||||
|
'cardBank.$.PAN': PAN,
|
||||||
|
'cardBank.$.IBAN': IBAN
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ new: true }
|
||||||
|
).select('id cardBank')
|
||||||
|
res.status(200).json(userData)
|
||||||
|
} catch (error) {
|
||||||
|
res.status(500).json({ msg: error.message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
module.exports.deleteCard = [
|
module.exports.deleteCard = [
|
||||||
[
|
[param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه می باشد')],
|
||||||
param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه می باشد')
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
const userData = await User.findOneAndUpdate(
|
||||||
async (req, res) => {
|
{
|
||||||
const userData = await User.findOneAndUpdate(
|
_id: req.user_id,
|
||||||
{
|
'cardBank._id': req.params.id
|
||||||
_id: req.user_id,
|
},
|
||||||
"cardBank._id": req.params.id
|
{
|
||||||
},
|
$pull: {
|
||||||
{
|
cardBank: { _id: req.params.id }
|
||||||
$pull: {
|
}
|
||||||
cardBank: { _id: req.params.id }
|
},
|
||||||
}
|
{ new: true }
|
||||||
},
|
).select('id cardBank')
|
||||||
{ new:true }
|
// res.status(200).json({ msg: "با موفقیت حذف شد ", data: userData })
|
||||||
).select('id cardBank')
|
res.status(200).json(userData)
|
||||||
// res.status(200).json({ msg: "با موفقیت حذف شد ", data: userData })
|
}
|
||||||
res.status(200).json(userData)
|
|
||||||
|
|
||||||
}
|
|
||||||
]
|
]
|
||||||
+174
-182
@@ -1,212 +1,204 @@
|
|||||||
const readXlsxFile = require('read-excel-file/node')
|
const readXlsxFile = require('read-excel-file/node')
|
||||||
const { body, param, validationResult } = require('express-validator');
|
const { body, param, validationResult } = require('express-validator')
|
||||||
const xlsx = require("json-as-xlsx")
|
const xlsx = require('json-as-xlsx')
|
||||||
const { _sr } = require('../plugins/serverResponses');
|
const { _sr } = require('../plugins/serverResponses')
|
||||||
const { checkValidations, res500 } = require('../plugins/controllersHelperFunctions');
|
const { checkValidations, res500 } = require('../plugins/controllersHelperFunctions')
|
||||||
const Device = require('../models/GPS.Device');
|
const Device = require('../models/GPS.Device')
|
||||||
module.exports.addCode = [
|
module.exports.addCode = [
|
||||||
[
|
[
|
||||||
body('model').notEmpty().isString().withMessage(_sr.fa.required.name),
|
body('model').notEmpty().isString().withMessage(_sr.fa.required.name),
|
||||||
body('IMEI').notEmpty().isIMEI().trim().withMessage('لطفا IMEI را وارد یا تصحیح کنید').custom(async (v) => {
|
body('IMEI')
|
||||||
const device = await Device.findOne({ IMEI: v })
|
.notEmpty()
|
||||||
if (device) {
|
.isIMEI()
|
||||||
return Promise.reject(_sr.fa.duplicated.IMEI)
|
.trim()
|
||||||
} else {
|
.withMessage('لطفا IMEI را وارد یا تصحیح کنید')
|
||||||
return true
|
.custom(async v => {
|
||||||
}
|
const device = await Device.findOne({ IMEI: v })
|
||||||
}),
|
if (device) {
|
||||||
body('tomanPrice').notEmpty().isInt({ min: 0 }).withMessage("قیمت دستگاه را به تومتن وارد کنید"),
|
return Promise.reject(_sr.fa.duplicated.IMEI)
|
||||||
body('dollarProfit').notEmpty().isInt({ min: 0 }).withMessage("سود نصاب را به دلار وارد کنید"),
|
} else {
|
||||||
body('profit').notEmpty().isInt({ min: 0 }).withMessage("سود نصاب را به تومان وارد کنید"),
|
return true
|
||||||
body('score').notEmpty().isInt({ min: 0 }).withMessage("امتیاز دریافتی نصاب را وارد کنید"),
|
}
|
||||||
body('renewalProfit').notEmpty().isInt({ min: 0 }).withMessage("سود دریافتی نصاب را از تمدید اشتراک وارد کنید"),
|
}),
|
||||||
],
|
body('tomanPrice').notEmpty().isInt({ min: 0 }).withMessage('قیمت دستگاه را به تومتن وارد کنید'),
|
||||||
checkValidations(validationResult),
|
body('dollarProfit').notEmpty().isInt({ min: 0 }).withMessage('سود نصاب را به دلار وارد کنید'),
|
||||||
async (req, res) => {
|
body('profit').notEmpty().isInt({ min: 0 }).withMessage('سود نصاب را به تومان وارد کنید'),
|
||||||
const data = await Device.create(req.body)
|
body('score').notEmpty().isInt({ min: 0 }).withMessage('امتیاز دریافتی نصاب را وارد کنید'),
|
||||||
// res.status(201).json({ msg: _sr.fa.response.success_save, data })
|
body('renewalProfit').notEmpty().isInt({ min: 0 }).withMessage('سود دریافتی نصاب را از تمدید اشتراک وارد کنید')
|
||||||
res.status(201).json(data)
|
],
|
||||||
|
checkValidations(validationResult),
|
||||||
}
|
async (req, res) => {
|
||||||
|
const data = await Device.create(req.body)
|
||||||
|
// res.status(201).json({ msg: _sr.fa.response.success_save, data })
|
||||||
|
res.status(201).json(data)
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports.importExel = async (req, res) => {
|
module.exports.importExel = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
if (!req.files?.file) return res.status(422).json({ validation: { file: { msg: 'فایل را اضافه کنید' } } })
|
if (!req.files?.file) return res.status(422).json({ validation: { file: { msg: 'فایل را اضافه کنید' } } })
|
||||||
if (!req.files?.file.name.split('.').some(item => ['xlsx', 'xltx', 'xlsm', 'xlsb'].includes(item))) return res.status(422).json({ validation: { file: { msg: 'فرمت فایل درست نمیباشد' } } })
|
if (!req.files?.file.name.split('.').some(item => ['xlsx', 'xltx', 'xlsm', 'xlsb'].includes(item)))
|
||||||
const file = req.files.file
|
return res.status(422).json({ validation: { file: { msg: 'فرمت فایل درست نمیباشد' } } })
|
||||||
|
const file = req.files.file
|
||||||
const exelFile = await readXlsxFile(Buffer.from(file.data));
|
|
||||||
const data = await creator(exelFile)
|
|
||||||
// res.status(201).json({ msg: _sr.fa.response.success_save, data })
|
|
||||||
res.status(201).json(data)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
} catch (error) {
|
|
||||||
console.log(error);
|
|
||||||
res500(res, error)
|
|
||||||
}
|
|
||||||
|
|
||||||
|
const exelFile = await readXlsxFile(Buffer.from(file.data))
|
||||||
|
const data = await creator(exelFile)
|
||||||
|
// res.status(201).json({ msg: _sr.fa.response.success_save, data })
|
||||||
|
res.status(201).json(data)
|
||||||
|
} catch (error) {
|
||||||
|
console.log(error)
|
||||||
|
res500(res, error)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.getAll = [
|
module.exports.getAll = [
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
|
const data = await Device.find().sort({ created_at: -1 })
|
||||||
const data = await Device.find().sort({ created_at: -1 })
|
res.status(200).json(data)
|
||||||
res.status(200).json(data)
|
}
|
||||||
}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.downloadAll = [
|
module.exports.downloadAll = [
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
|
const device = await Device.find().sort({ created_at: -1 })
|
||||||
|
const data = [
|
||||||
|
{
|
||||||
|
sheet: 'device',
|
||||||
|
columns: [
|
||||||
|
{ label: 'IMEI', value: 'IMEI' },
|
||||||
|
{ label: 'مدل', value: 'model' },
|
||||||
|
{ label: 'قیمت به تومان', value: 'tomanPrice' },
|
||||||
|
{ label: 'سود به دلار', value: 'dollarProfit' },
|
||||||
|
{ label: 'سود به تومان', value: 'profit' },
|
||||||
|
{ label: 'امتیاز', value: 'score' },
|
||||||
|
{ label: 'سود از تمدید', value: 'renewalProfit' },
|
||||||
|
{ label: 'وضعیت نصب', value: 'status' }
|
||||||
|
],
|
||||||
|
content: device
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
const device = await Device.find().sort({ created_at: -1 })
|
const settings = {
|
||||||
const data = [
|
writeOptions: {
|
||||||
{
|
type: 'buffer',
|
||||||
sheet: "device",
|
bookType: 'csv'
|
||||||
columns: [
|
},
|
||||||
{ label: "IMEI", value: "IMEI" },
|
RTL: true
|
||||||
{ label: "مدل", value: "model" },
|
|
||||||
{ label: "قیمت به تومان", value: "tomanPrice" },
|
|
||||||
{ label: "سود به دلار", value: "dollarProfit" },
|
|
||||||
{ label: "سود به تومان", value: "profit" },
|
|
||||||
{ label: "امتیاز", value: "score" },
|
|
||||||
{ label: "سود از تمدید", value: "renewalProfit" },
|
|
||||||
{ label: "وضعیت نصب", value: "status" },
|
|
||||||
],
|
|
||||||
content: device,
|
|
||||||
}
|
|
||||||
]
|
|
||||||
|
|
||||||
const settings = {
|
|
||||||
writeOptions: {
|
|
||||||
type: "buffer",
|
|
||||||
bookType: "csv",
|
|
||||||
},
|
|
||||||
RTL: true
|
|
||||||
}
|
|
||||||
setTimeout(() => {
|
|
||||||
const buffer = xlsx(data, settings)
|
|
||||||
res.writeHead(200, {
|
|
||||||
"Content-Type": "application/octet-stream",
|
|
||||||
"Content-disposition": "attachment; filename=device.csv",
|
|
||||||
})
|
|
||||||
res.end(buffer)
|
|
||||||
}, 2000);
|
|
||||||
}
|
}
|
||||||
|
setTimeout(() => {
|
||||||
|
const buffer = xlsx(data, settings)
|
||||||
|
res.writeHead(200, {
|
||||||
|
'Content-Type': 'application/octet-stream',
|
||||||
|
'Content-disposition': 'attachment; filename=device.csv'
|
||||||
|
})
|
||||||
|
res.end(buffer)
|
||||||
|
}, 2000)
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.getOne = [
|
module.exports.getOne = [
|
||||||
[
|
[param('id').notEmpty().isMongoId().withMessage('ایدی اشتباه است')],
|
||||||
param('id').notEmpty().isMongoId().withMessage('ایدی اشتباه است')
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
const data = await Device.findById(req.params.id).sort({ created_at: -1 })
|
||||||
async (req, res) => {
|
if (!data) {
|
||||||
const data = await Device.findById(req.params.id).sort({ created_at: -1 })
|
res.status(404).json(_sr.fa.not_found.item_id)
|
||||||
if (!data) {
|
} else {
|
||||||
res.status(404).json(_sr.fa.not_found.item_id)
|
res.status(200).json(data)
|
||||||
} else {
|
|
||||||
res.status(200).json(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.getOneByIMEI = [
|
module.exports.getOneByIMEI = [
|
||||||
[
|
[param('imei').notEmpty().isString().withMessage('ایدی اشتباه است')],
|
||||||
param('imei').notEmpty().isString().withMessage('ایدی اشتباه است')
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
const data = await Device.findOne({ IMEI: req.params.imei }).sort({ created_at: -1 })
|
||||||
async (req, res) => {
|
if (!data) {
|
||||||
const data = await Device.findOne({ IMEI: req.params.imei }).sort({ created_at: -1 })
|
res.status(404).json(_sr.fa.not_found.item_id)
|
||||||
if (!data) {
|
} else {
|
||||||
res.status(404).json(_sr.fa.not_found.item_id)
|
res.status(200).json(data)
|
||||||
} else {
|
|
||||||
res.status(200).json(data)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
module.exports.updateDevice = [
|
module.exports.updateDevice = [
|
||||||
[
|
[
|
||||||
param('id').notEmpty().isMongoId().withMessage('ایدی اشتباه است').custom(async (v) => {
|
param('id')
|
||||||
const device = await Device.findById(v)
|
.notEmpty()
|
||||||
if (device) {
|
.isMongoId()
|
||||||
return true
|
.withMessage('ایدی اشتباه است')
|
||||||
} else {
|
.custom(async v => {
|
||||||
return Promise.reject(_sr.fa.not_found.item_id)
|
const device = await Device.findById(v)
|
||||||
|
if (device) {
|
||||||
}
|
return true
|
||||||
}),
|
} else {
|
||||||
body('model').notEmpty().isString().withMessage(_sr.fa.required.name),
|
return Promise.reject(_sr.fa.not_found.item_id)
|
||||||
body('tomanPrice').notEmpty().isInt({ min: 0 }).withMessage("قیمت دستگاه را به تومتن وارد کنید"),
|
}
|
||||||
body('dollarProfit').notEmpty().isInt({ min: 0 }).withMessage("سود نصاب را به دلار وارد کنید"),
|
}),
|
||||||
body('profit').notEmpty().isInt({ min: 0 }).withMessage("سود نصاب را به تومان وارد کنید"),
|
body('model').notEmpty().isString().withMessage(_sr.fa.required.name),
|
||||||
body('score').notEmpty().isInt({ min: 0 }).withMessage("امتیاز دریافتی نصاب را وارد کنید"),
|
body('tomanPrice').notEmpty().isInt({ min: 0 }).withMessage('قیمت دستگاه را به تومتن وارد کنید'),
|
||||||
body('renewalProfit').notEmpty().isInt({ min: 0 }).withMessage("سود دریافتی نصاب را از تمدید اشتراک وارد کنید"),
|
body('dollarProfit').notEmpty().isInt({ min: 0 }).withMessage('سود نصاب را به دلار وارد کنید'),
|
||||||
|
body('profit').notEmpty().isInt({ min: 0 }).withMessage('سود نصاب را به تومان وارد کنید'),
|
||||||
],
|
body('score').notEmpty().isInt({ min: 0 }).withMessage('امتیاز دریافتی نصاب را وارد کنید'),
|
||||||
checkValidations(validationResult),
|
body('renewalProfit').notEmpty().isInt({ min: 0 }).withMessage('سود دریافتی نصاب را از تمدید اشتراک وارد کنید')
|
||||||
async (req, res) => {
|
],
|
||||||
const { model, tomanPrice, dollarProfit, profit, score, renewalProfit } = req.body;
|
checkValidations(validationResult),
|
||||||
const data = await Device.findByIdAndUpdate(
|
async (req, res) => {
|
||||||
req.params.id,
|
const { model, tomanPrice, dollarProfit, profit, score, renewalProfit } = req.body
|
||||||
{
|
const data = await Device.findByIdAndUpdate(
|
||||||
model, tomanPrice, dollarProfit, profit, score, renewalProfit
|
req.params.id,
|
||||||
},
|
{
|
||||||
{ new: true }
|
model,
|
||||||
)
|
tomanPrice,
|
||||||
// res.status(200).json({ msg: _sr.fa.response.success_save, data })
|
dollarProfit,
|
||||||
res.status(200).json(data)
|
profit,
|
||||||
|
score,
|
||||||
}
|
renewalProfit
|
||||||
|
},
|
||||||
|
{ new: true }
|
||||||
|
)
|
||||||
|
// res.status(200).json({ msg: _sr.fa.response.success_save, data })
|
||||||
|
res.status(200).json(data)
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
const creator = exel => {
|
||||||
|
return new Promise(async (resolve, reject) => {
|
||||||
|
try {
|
||||||
|
for (const row of exel) {
|
||||||
|
console.log(row)
|
||||||
|
// eslint-disable-next-line no-constant-condition
|
||||||
|
if (/^[0-9]{15}$/gm.test(row?.[0]?.toString()?.trim())) {
|
||||||
|
const device = await Device.findOne({ IMEI: row?.[0]?.toString()?.trim() })
|
||||||
|
if (device) {
|
||||||
|
console.info('Repeated IMEI ', row[0])
|
||||||
|
|
||||||
const creator = (exel) => {
|
device.model = row[1]
|
||||||
return new Promise(async (resolve, reject) => {
|
device.tomanPrice = row[2]
|
||||||
try {
|
device.dollarProfit = row[3] || 1
|
||||||
for (const row of exel) {
|
device.profit = row[4] || 1
|
||||||
// eslint-disable-next-line no-constant-condition
|
device.score = row[5] || 1
|
||||||
if (/^[0-9]{15}$/gm.test(row[0].toString().trim())) {
|
device.renewalProfit = row[6] || 1
|
||||||
const device = await Device.findOne({ IMEI: row[0].trim() })
|
device.save()
|
||||||
if (device) {
|
} else {
|
||||||
console.info("Repeated IMEI ", row[0])
|
await Device.create({
|
||||||
|
IMEI: row[0].toString().trim(),
|
||||||
device.model = row[1]
|
model: row[1],
|
||||||
device.tomanPrice = row[2]
|
tomanPrice: row[2],
|
||||||
device.dollarProfit = row[3] || 1
|
dollarProfit: row[3] || 1,
|
||||||
device.profit = row[4] || 1
|
profit: row[4] || 1,
|
||||||
device.score = row[5] || 1
|
score: row[5] || 1,
|
||||||
device.renewalProfit = row[6] || 1
|
renewalProfit: row[6] || 1
|
||||||
device.save()
|
})
|
||||||
} else {
|
}
|
||||||
await Device.create(
|
} else {
|
||||||
{
|
console.warn('Wrong IMEI ', row[0])
|
||||||
IMEI: row[0].trim(),
|
|
||||||
model: row[1],
|
|
||||||
tomanPrice: row[2],
|
|
||||||
dollarProfit: row[3] || 1,
|
|
||||||
profit: row[4] || 1,
|
|
||||||
score: row[5] || 1,
|
|
||||||
renewalProfit: row[6] || 1
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
console.warn("Wrong IMEI ", row[0])
|
|
||||||
}
|
|
||||||
}
|
|
||||||
resolve("end")
|
|
||||||
} catch (error) {
|
|
||||||
reject(error.message)
|
|
||||||
}
|
}
|
||||||
})
|
}
|
||||||
|
resolve('end')
|
||||||
|
} catch (error) {
|
||||||
|
reject(error.message)
|
||||||
|
}
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,201 +1,184 @@
|
|||||||
const { body, param, validationResult } = require('express-validator');
|
const { body, param, validationResult } = require('express-validator')
|
||||||
const { checkValidations } = require('../plugins/controllersHelperFunctions');
|
const { checkValidations } = require('../plugins/controllersHelperFunctions')
|
||||||
const User = require('../models/GPS.User');
|
const User = require('../models/GPS.User')
|
||||||
const InstalledDevice = require('../models/GPS.InstalledDevice');
|
const InstalledDevice = require('../models/GPS.InstalledDevice')
|
||||||
const Device = require('../models/GPS.Device');
|
const Device = require('../models/GPS.Device')
|
||||||
const Score = require('../models/GPS.Score');
|
const Score = require('../models/GPS.Score')
|
||||||
const { _sr } = require('../plugins/serverResponses');
|
const { _sr } = require('../plugins/serverResponses')
|
||||||
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
|
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
|
||||||
|
|
||||||
module.exports.deviceRegistration = [
|
module.exports.deviceRegistration = [
|
||||||
[
|
[body('IMEI').notEmpty().isString().withMessage('لطفا IMEI را وارد یا تصحیح کنید')],
|
||||||
body('IMEI').notEmpty().isString().withMessage('لطفا IMEI را وارد یا تصحیح کنید')
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
const device = await Device.findOne({ IMEI: req.body.IMEI })
|
||||||
async (req, res) => {
|
if (!device) {
|
||||||
const device = await Device.findOne({ IMEI: req.body.IMEI });
|
throw res.status(404).json({ msg: 'این IMEI وجود ندارد' })
|
||||||
if (!device) {
|
// eslint-disable-next-line eqeqeq
|
||||||
throw res.status(404).json({ msg: 'این IMEI وجود ندارد' })
|
} else if (device.status == 1) {
|
||||||
// eslint-disable-next-line eqeqeq
|
throw res.status(404).json({ msg: 'این IMEI قبلا ثبت شده' })
|
||||||
} else if (device.status == 1 || device.status == 0) {
|
} else {
|
||||||
throw res.status(404).json({ msg: 'این IMEI قبلا ثبت شده' })
|
const data = {
|
||||||
|
deviceId: device.id,
|
||||||
|
status: 0,
|
||||||
|
registerDate: new Date(),
|
||||||
|
userId: req.user_id,
|
||||||
|
IMEI: req.body.IMEI
|
||||||
|
}
|
||||||
|
const newRequest = await InstalledDevice.create(data)
|
||||||
|
device.status = 1
|
||||||
|
device.save()
|
||||||
|
notifyAdmin('newInstallDeviceRequest')
|
||||||
|
|
||||||
} else {
|
// res.status(201).json({ msg: _sr.fa.response.success_save, data: newRequest })
|
||||||
const data = {
|
res.status(201).json(newRequest)
|
||||||
deviceId: device.id,
|
|
||||||
status: 0,
|
|
||||||
registerDate: new Date(),
|
|
||||||
userId: req.user_id,
|
|
||||||
IMEI: req.body.IMEI
|
|
||||||
}
|
|
||||||
const newRequest = await InstalledDevice.create(data);
|
|
||||||
device.status = 1;
|
|
||||||
device.save()
|
|
||||||
notifyAdmin('newInstallDeviceRequest')
|
|
||||||
|
|
||||||
// res.status(201).json({ msg: _sr.fa.response.success_save, data: newRequest })
|
|
||||||
res.status(201).json(newRequest)
|
|
||||||
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
module.exports.getAllForUser = async (req, res) => {
|
module.exports.getAllForUser = async (req, res) => {
|
||||||
let page;
|
let page
|
||||||
let rows;
|
let rows
|
||||||
|
|
||||||
if (!req.query?.rows || req.query?.rows <= 5) {
|
if (!req.query?.rows || req.query?.rows <= 5) {
|
||||||
rows = 10;
|
rows = 10
|
||||||
} else {
|
} else {
|
||||||
rows = parseInt(req.query.rows);
|
rows = parseInt(req.query.rows)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!req.query?.page || req.query.page <= 1) {
|
if (!req.query?.page || req.query.page <= 1) {
|
||||||
page = 0;
|
page = 0
|
||||||
} else {
|
} else {
|
||||||
page = (req.query.page - 1) * rows;
|
page = (req.query.page - 1) * rows
|
||||||
}
|
}
|
||||||
|
|
||||||
const search = req.query?.search || null;
|
const search = req.query?.search || null
|
||||||
|
|
||||||
let sort = {};
|
let sort = {}
|
||||||
|
|
||||||
if (req.query?.deviceId_dollarProfit) {
|
if (req.query?.deviceId_dollarProfit) {
|
||||||
sort.dollarProfit = parseInt(req.query.deviceId_dollarProfit);
|
sort.dollarProfit = parseInt(req.query.deviceId_dollarProfit)
|
||||||
}
|
}
|
||||||
if (req.query?.status) {
|
if (req.query?.status) {
|
||||||
sort.status = parseInt(req.query.status);
|
sort.status = parseInt(req.query.status)
|
||||||
}
|
}
|
||||||
if (req.query?.registerDate) {
|
if (req.query?.registerDate) {
|
||||||
sort.registerDate = parseInt(req.query.registerDate);
|
sort.registerDate = parseInt(req.query.registerDate)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (Object.keys(sort).length === 0) {
|
if (Object.keys(sort).length === 0) {
|
||||||
sort = { 'created_at': -1 };
|
sort = { created_at: -1 }
|
||||||
}
|
}
|
||||||
|
|
||||||
const filter = {
|
const filter = {
|
||||||
userId: req.user_id,
|
userId: req.user_id
|
||||||
};
|
}
|
||||||
|
|
||||||
if (search) {
|
if (search) {
|
||||||
filter.$or = [
|
filter.$or = [{ IMEI: { $regex: search, $options: 'i' } }]
|
||||||
{ IMEI: { $regex: search, $options: 'i' } },
|
}
|
||||||
];
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const data = await InstalledDevice.find(filter)
|
const data = await InstalledDevice.find(filter).skip(page).limit(rows).sort(sort).populate('deviceId')
|
||||||
.skip(page)
|
|
||||||
.limit(rows)
|
|
||||||
.sort(sort)
|
|
||||||
.populate('deviceId');
|
|
||||||
|
|
||||||
const total = await InstalledDevice.countDocuments(filter);
|
const total = await InstalledDevice.countDocuments(filter)
|
||||||
|
|
||||||
res.status(200).json({ data, total });
|
res.status(200).json({ data, total })
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
res.status(500).json({ message: 'An error occurred', error });
|
res.status(500).json({ message: 'An error occurred', error })
|
||||||
}
|
}
|
||||||
};
|
}
|
||||||
|
|
||||||
module.exports.getAllForAdmin = async (req, res) => {
|
module.exports.getAllForAdmin = async (req, res) => {
|
||||||
try {
|
try {
|
||||||
// const page = parseInt(req.query.page) || 1;
|
// const page = parseInt(req.query.page) || 1;
|
||||||
// const rows = parseInt(req.query.rows) || 10;
|
// const rows = parseInt(req.query.rows) || 10;
|
||||||
// const search = req.query.search || "";
|
// const search = req.query.search || "";
|
||||||
// const sortField = req.query.sortField || "status";
|
// const sortField = req.query.sortField || "status";
|
||||||
// const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
|
// const sortOrder = req.query.sortOrder === "desc" ? -1 : 1;
|
||||||
|
|
||||||
// const skip = (page - 1) * rows;
|
// const skip = (page - 1) * rows;
|
||||||
|
|
||||||
// const filter = {};
|
// const filter = {};
|
||||||
// if (search) {
|
// if (search) {
|
||||||
// filter.$or = [
|
// filter.$or = [
|
||||||
// { IMEI: new RegExp(search, 'i') },
|
// { IMEI: new RegExp(search, 'i') },
|
||||||
// { 'userId.shopName': new RegExp(search, 'i') },
|
// { 'userId.shopName': new RegExp(search, 'i') },
|
||||||
// { 'userId.national_code': new RegExp(search, 'i') },
|
// { 'userId.national_code': new RegExp(search, 'i') },
|
||||||
// ];
|
// ];
|
||||||
// }
|
// }
|
||||||
|
|
||||||
const data = await InstalledDevice.find()
|
const data = await InstalledDevice.find()
|
||||||
// .sort({ [sortField]: sortOrder })
|
// .sort({ [sortField]: sortOrder })
|
||||||
.populate('deviceId')
|
.populate('deviceId')
|
||||||
.populate('userId', 'shopName national_code first_name last_name mobile_number city_name province_name')
|
.populate('userId', 'shopName national_code first_name last_name mobile_number city_name province_name')
|
||||||
// .skip(skip)
|
// .skip(skip)
|
||||||
// .limit(rows);
|
// .limit(rows);
|
||||||
|
|
||||||
// const totalDocuments = await InstalledDevice.countDocuments(filter);
|
|
||||||
// const totalPages = Math.ceil(totalDocuments / rows);
|
|
||||||
|
|
||||||
res.status(200).json({ data });
|
|
||||||
} catch (error) {
|
|
||||||
console.error('Error:', error.message);
|
|
||||||
res.status(500).json({ message: "Server Error", error: error.message });
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
|
// const totalDocuments = await InstalledDevice.countDocuments(filter);
|
||||||
|
// const totalPages = Math.ceil(totalDocuments / rows);
|
||||||
|
|
||||||
|
res.status(200).json({ data })
|
||||||
|
} catch (error) {
|
||||||
|
console.error('Error:', error.message)
|
||||||
|
res.status(500).json({ message: 'Server Error', error: error.message })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
module.exports.updateInstalled = [
|
module.exports.updateInstalled = [
|
||||||
[
|
[
|
||||||
param('id').notEmpty().isMongoId().withMessage('لطفا ایدی را وارد یا تصحیح کنید'),
|
param('id').notEmpty().isMongoId().withMessage('لطفا ایدی را وارد یا تصحیح کنید'),
|
||||||
param('type').notEmpty().isString().withMessage('لطفا وضعیت را وارد یا تصحیح کنید'),
|
param('type').notEmpty().isString().withMessage('لطفا وضعیت را وارد یا تصحیح کنید')
|
||||||
],
|
],
|
||||||
checkValidations(validationResult),
|
checkValidations(validationResult),
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const installedDevice = await InstalledDevice.findById(req.params.id)
|
const installedDevice = await InstalledDevice.findById(req.params.id)
|
||||||
if (!installedDevice) {
|
if (!installedDevice) {
|
||||||
throw res.status(404).json({ msg: 'این ایدی وجود ندارد' })
|
throw res.status(404).json({ msg: 'این ایدی وجود ندارد' })
|
||||||
} else {
|
} else {
|
||||||
const user = await User.findById(installedDevice.userId).select('walletBalance dollarBalance score')
|
const user = await User.findById(installedDevice.userId).select('walletBalance dollarBalance score')
|
||||||
const device = await Device.findById(installedDevice.deviceId)
|
const device = await Device.findById(installedDevice.deviceId)
|
||||||
switch (req.params.type) {
|
switch (req.params.type) {
|
||||||
case "accept": {
|
case 'accept': {
|
||||||
installedDevice.status = 1;
|
installedDevice.status = 1
|
||||||
installedDevice.installationDate = new Date();
|
installedDevice.installationDate = new Date()
|
||||||
device.status = 1;
|
device.status = 1
|
||||||
|
|
||||||
user.walletBalance += device.profit
|
user.walletBalance += device.profit
|
||||||
user.dollarBalance += device.dollarProfit
|
user.dollarBalance += device.dollarProfit
|
||||||
user.score += device.score
|
user.score += device.score
|
||||||
|
|
||||||
|
await Score.create({
|
||||||
|
title: 'ثبت دستگاه',
|
||||||
|
deviceId: device.id,
|
||||||
|
score: device.score,
|
||||||
|
userId: installedDevice.userId
|
||||||
|
})
|
||||||
|
user.save()
|
||||||
|
device.save()
|
||||||
|
installedDevice.save()
|
||||||
|
notifyAdmin('newInstallDeviceRequest')
|
||||||
|
|
||||||
await Score.create({
|
res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })
|
||||||
title: "ثبت دستگاه",
|
|
||||||
deviceId: device.id,
|
|
||||||
score: device.score,
|
|
||||||
userId: installedDevice.userId
|
|
||||||
})
|
|
||||||
user.save()
|
|
||||||
device.save()
|
|
||||||
installedDevice.save()
|
|
||||||
notifyAdmin('newInstallDeviceRequest')
|
|
||||||
|
|
||||||
res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })
|
break
|
||||||
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
case "reject": {
|
|
||||||
installedDevice.status = 2;
|
|
||||||
installedDevice.save()
|
|
||||||
device.status = 0;
|
|
||||||
device.save()
|
|
||||||
notifyAdmin('newInstallDeviceRequest')
|
|
||||||
|
|
||||||
res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })
|
|
||||||
|
|
||||||
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
default: {
|
|
||||||
res.status(404).json({ msg: "وضعیت اشتباه است" })
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
case 'reject': {
|
||||||
]
|
installedDevice.status = 2
|
||||||
|
installedDevice.save()
|
||||||
|
device.status = 0
|
||||||
|
device.save()
|
||||||
|
notifyAdmin('newInstallDeviceRequest')
|
||||||
|
|
||||||
|
res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })
|
||||||
|
|
||||||
|
break
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
res.status(404).json({ msg: 'وضعیت اشتباه است' })
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|||||||
+408
-469
@@ -6,555 +6,494 @@ const User = require('../models/GPS.User')
|
|||||||
const { _sr } = require('../plugins/serverResponses')
|
const { _sr } = require('../plugins/serverResponses')
|
||||||
const { SMS } = require('../plugins/SMS_Module')
|
const { SMS } = require('../plugins/SMS_Module')
|
||||||
const {
|
const {
|
||||||
res500,
|
res500,
|
||||||
checkValidations,
|
checkValidations,
|
||||||
removeWhiteSpaces,
|
removeWhiteSpaces,
|
||||||
checkMobileNumber,
|
checkMobileNumber,
|
||||||
normalizeMobileNumber,
|
normalizeMobileNumber,
|
||||||
nameOptimizer,
|
nameOptimizer,
|
||||||
checkNationalCode,
|
checkNationalCode,
|
||||||
isPersian,
|
isPersian,
|
||||||
generateRandomDigits
|
generateRandomDigits
|
||||||
} = require('../plugins/controllersHelperFunctions')
|
} = require('../plugins/controllersHelperFunctions')
|
||||||
const _faSr = _sr.fa
|
const _faSr = _sr.fa
|
||||||
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
|
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
function sendConfirmationSMS(userId) {
|
function sendConfirmationSMS(userId) {
|
||||||
return new Promise(async (resolve, reject) => {
|
return new Promise(async (resolve, reject) => {
|
||||||
try {
|
try {
|
||||||
const user = await User.findById(userId)
|
const user = await User.findById(userId)
|
||||||
if (!user) throw new Error('invalid id')
|
if (!user) throw new Error('invalid id')
|
||||||
|
|
||||||
const mobileKey = generateRandomDigits(6)
|
const mobileKey = generateRandomDigits(6)
|
||||||
user.otp = mobileKey
|
user.otp = mobileKey
|
||||||
await user.save()
|
await user.save()
|
||||||
|
|
||||||
const smsMsg = [
|
const smsMsg = ['این شماره در وبسایت آسان سرویس ثبت گردیده.', ' کد تایید شماره همراه: ', mobileKey]
|
||||||
'این شماره در وبسایت آسان سرویس ثبت گردیده.',
|
|
||||||
' کد تایید شماره همراه: ',
|
|
||||||
mobileKey
|
|
||||||
]
|
|
||||||
|
|
||||||
await SMS([user.mobile_number], smsMsg.join(''))
|
await SMS([user.mobile_number], smsMsg.join(''))
|
||||||
|
|
||||||
resolve()
|
resolve()
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
reject(err)
|
reject(err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.register_user = [
|
module.exports.register_user = [
|
||||||
[
|
[
|
||||||
body('first_name')
|
body('first_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('last_name')
|
body('last_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('national_code')
|
body('national_code')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.national_code)
|
.withMessage(_faSr.required.national_code)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (checkNationalCode(value)) return true
|
if (checkNationalCode(value)) return true
|
||||||
else return Promise.reject(_faSr.format.national_code)
|
else return Promise.reject(_faSr.format.national_code)
|
||||||
})
|
})
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
const nationalCode = value.trim()
|
const nationalCode = value.trim()
|
||||||
return User.findOne({ national_code: nationalCode }).then(user => {
|
return User.findOne({ national_code: nationalCode }).then(user => {
|
||||||
if (user && user.national_code === nationalCode)
|
if (user && user.national_code === nationalCode)
|
||||||
return Promise.reject(new Error('کاربر با این کد ملی از قبل وجود دارد'))
|
return Promise.reject(new Error('کاربر با این کد ملی از قبل وجود دارد'))
|
||||||
else return true
|
else return true
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
||||||
|
|
||||||
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
||||||
|
|
||||||
body('shopName')
|
body('shopName').notEmpty().withMessage(_faSr.required.address),
|
||||||
.notEmpty()
|
|
||||||
.withMessage(_faSr.required.address),
|
|
||||||
|
|
||||||
|
body('mobile_number')
|
||||||
|
.notEmpty()
|
||||||
|
.withMessage(_faSr.required.phone_number)
|
||||||
|
.bail()
|
||||||
|
.custom((value, { req }) => {
|
||||||
|
const mobileNStatus = checkMobileNumber(value)
|
||||||
|
if (!mobileNStatus) return Promise.reject(_faSr.format.phone_number)
|
||||||
|
else return Promise.resolve()
|
||||||
|
})
|
||||||
|
.bail()
|
||||||
|
.custom((value, { req }) => {
|
||||||
|
const mobileNumber = value.trim()
|
||||||
|
return User.findOne({ mobile_number: mobileNumber }).then(user => {
|
||||||
|
if (user && user.mobile_number === mobileNumber)
|
||||||
|
return Promise.reject(new Error('کاربر با این شماره موبایل از قبل وجود دارد'))
|
||||||
|
else return true
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
|
||||||
body('mobile_number')
|
body('password')
|
||||||
.notEmpty()
|
.isLength({ min: 4 })
|
||||||
.withMessage(_faSr.required.phone_number)
|
.withMessage(_faSr.min_char.min4)
|
||||||
.bail()
|
.custom((value, { req }) => {
|
||||||
.custom((value, { req }) => {
|
if (value === req.body.password_confirmation) return true
|
||||||
const mobileNStatus = checkMobileNumber(value)
|
else return Promise.reject(_faSr.response.passwords_not_match)
|
||||||
if (!mobileNStatus) return Promise.reject(_faSr.format.phone_number)
|
})
|
||||||
else return Promise.resolve()
|
],
|
||||||
})
|
checkValidations(validationResult),
|
||||||
.bail()
|
async (req, res) => {
|
||||||
.custom((value, { req }) => {
|
try {
|
||||||
const mobileNumber = value.trim()
|
const provinceId = uid.v4()
|
||||||
return User.findOne({ mobile_number: mobileNumber }).then(user => {
|
const cityId = uid.v4()
|
||||||
if (user && user.mobile_number === mobileNumber)
|
|
||||||
return Promise.reject(new Error('کاربر با این شماره موبایل از قبل وجود دارد'))
|
|
||||||
else return true
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
|
|
||||||
body('password')
|
const { first_name, last_name, national_code, province_name, city_name, mobile_number, password, shopName } =
|
||||||
.isLength({ min: 4 })
|
req.body
|
||||||
.withMessage(_faSr.min_char.min4)
|
|
||||||
.custom((value, { req }) => {
|
|
||||||
if (value === req.body.password_confirmation) return true
|
|
||||||
else return Promise.reject(_faSr.response.passwords_not_match)
|
|
||||||
})
|
|
||||||
],
|
|
||||||
checkValidations(validationResult),
|
|
||||||
async (req, res) => {
|
|
||||||
try {
|
|
||||||
const provinceId = uid.v4()
|
|
||||||
const cityId = uid.v4()
|
|
||||||
|
|
||||||
const {
|
const data = {
|
||||||
first_name,
|
last_name,
|
||||||
last_name,
|
province_name: { id: provinceId, provinceName: province_name },
|
||||||
national_code,
|
city_name: { id: cityId, cityName: city_name },
|
||||||
province_name,
|
shopName
|
||||||
city_name,
|
}
|
||||||
mobile_number,
|
data.first_name = nameOptimizer(first_name)
|
||||||
password,
|
data.national_code = national_code.trim()
|
||||||
shopName
|
data.mobile_number = normalizeMobileNumber(mobile_number)
|
||||||
} = req.body
|
|
||||||
|
|
||||||
const data = {
|
// hash user password and done
|
||||||
last_name,
|
const salt = await bcrypt.genSalt(10)
|
||||||
province_name:{id:provinceId,provinceName:province_name},
|
const hash = await bcrypt.hash(password, salt)
|
||||||
city_name:{id:cityId,cityName:city_name},
|
data.password = hash
|
||||||
shopName
|
|
||||||
}
|
|
||||||
data.first_name = nameOptimizer(first_name)
|
|
||||||
data.national_code = national_code.trim()
|
|
||||||
data.mobile_number = normalizeMobileNumber(mobile_number)
|
|
||||||
|
|
||||||
|
const user = new User(data)
|
||||||
|
await user.save()
|
||||||
|
notifyAdmin('pendingUsers')
|
||||||
|
|
||||||
// hash user password and done
|
return res.json({ message: _faSr.response.success_save })
|
||||||
const salt = await bcrypt.genSalt(10)
|
} catch (err) {
|
||||||
const hash = await bcrypt.hash(password, salt)
|
const registerFailurMsg = 'مشکلی در ثبت نام پیش آمده، لطفا مجددا تلاش کنید'
|
||||||
data.password = hash
|
res500(res, registerFailurMsg)
|
||||||
|
|
||||||
const user = new User(data)
|
|
||||||
await user.save()
|
|
||||||
notifyAdmin('pendingUsers')
|
|
||||||
|
|
||||||
return res.json({ message: _faSr.response.success_save })
|
|
||||||
} catch (err) {
|
|
||||||
const registerFailurMsg = 'مشکلی در ثبت نام پیش آمده، لطفا مجددا تلاش کنید'
|
|
||||||
res500(res, registerFailurMsg)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
module.exports.update_user = [
|
module.exports.update_user = [
|
||||||
[
|
[
|
||||||
body('first_name')
|
body('first_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('last_name')
|
body('last_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
||||||
|
|
||||||
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
||||||
|
|
||||||
body('shopName')
|
body('shopName').notEmpty().withMessage(_faSr.required.field),
|
||||||
.notEmpty()
|
body('address').notEmpty().withMessage(_faSr.required.address),
|
||||||
.withMessage(_faSr.required.field),
|
|
||||||
body('address')
|
|
||||||
.notEmpty()
|
|
||||||
.withMessage(_faSr.required.address),
|
|
||||||
|
|
||||||
body('cell_number')
|
body('cell_number').notEmpty().withMessage(_faSr.required.address),
|
||||||
.notEmpty()
|
|
||||||
.withMessage(_faSr.required.address),
|
|
||||||
|
|
||||||
body('birthDate')
|
body('birthDate').notEmpty().withMessage(_faSr.required.address)
|
||||||
.notEmpty()
|
],
|
||||||
.withMessage(_faSr.required.address),
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
try {
|
||||||
async (req, res) => {
|
const { first_name, last_name, province_name, city_name, shopName, birthDate, address, cell_number } = req.body
|
||||||
try {
|
|
||||||
const {
|
|
||||||
first_name,
|
|
||||||
last_name,
|
|
||||||
province_name,
|
|
||||||
city_name,
|
|
||||||
shopName,
|
|
||||||
birthDate,
|
|
||||||
address,
|
|
||||||
cell_number
|
|
||||||
} = req.body
|
|
||||||
|
|
||||||
const data = {
|
const data = {
|
||||||
last_name,
|
last_name,
|
||||||
province_name,
|
province_name,
|
||||||
city_name,
|
city_name,
|
||||||
shopName,
|
shopName,
|
||||||
birthDate,
|
birthDate,
|
||||||
address,
|
address,
|
||||||
cell_number
|
cell_number
|
||||||
}
|
}
|
||||||
if (req.files?.image) {
|
if (req.files?.image) {
|
||||||
const image = req.files?.image
|
const image = req.files?.image
|
||||||
const fileName = 'profile' + Date.now() + '.' + image.name
|
const fileName = 'profile' + Date.now() + '.' + image.name
|
||||||
await image.mv(`./static/uploads/images/${fileName}`)
|
await image.mv(`./static/uploads/images/${fileName}`)
|
||||||
data.profilePic = `/uploads/images/${fileName}`
|
data.profilePic = `/uploads/images/${fileName}`
|
||||||
}
|
}
|
||||||
data.first_name = nameOptimizer(first_name)
|
data.first_name = nameOptimizer(first_name)
|
||||||
await User.findByIdAndUpdate(
|
await User.findByIdAndUpdate(req.params.id, data)
|
||||||
req.params.id,
|
const user = await User.findById(req.params.id)
|
||||||
data
|
return res.json({ message: _faSr.response.success_save, user })
|
||||||
)
|
} catch (err) {
|
||||||
const user = await User.findById(req.params.id)
|
const registerFailurMsg = 'مشکلی در به روز رسانی پیش آمده، لطفا مجددا تلاش کنید'
|
||||||
return res.json({ message: _faSr.response.success_save ,user })
|
throw new Error(registerFailurMsg)
|
||||||
} catch (err) {
|
|
||||||
const registerFailurMsg = 'مشکلی در به روز رسانی پیش آمده، لطفا مجددا تلاش کنید'
|
|
||||||
throw new Error(registerFailurMsg)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.update_user_password = [
|
module.exports.update_user_password = [
|
||||||
[
|
[
|
||||||
body('newPassword')
|
body('newPassword')
|
||||||
.isLength({ min: 4 })
|
.isLength({ min: 4 })
|
||||||
.withMessage(_faSr.min_char.min4)
|
.withMessage(_faSr.min_char.min4)
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (value === req.body.password_confirmation) return true
|
if (value === req.body.password_confirmation) return true
|
||||||
else return Promise.reject(_faSr.response.passwords_not_match)
|
else return Promise.reject(_faSr.response.passwords_not_match)
|
||||||
}),
|
}),
|
||||||
body('password')
|
body('password').isLength({ min: 4 }).withMessage(_faSr.min_char.min4)
|
||||||
.isLength({ min: 4 })
|
],
|
||||||
.withMessage(_faSr.min_char.min4)
|
checkValidations(validationResult),
|
||||||
],
|
async (req, res) => {
|
||||||
checkValidations(validationResult),
|
try {
|
||||||
async (req, res) => {
|
const { password, newPassword } = req.body
|
||||||
try {
|
const { user_id } = req
|
||||||
const { password, newPassword } = req.body
|
const salt = await bcrypt.genSalt(10)
|
||||||
const { user_id } = req
|
const hash = await bcrypt.hash(newPassword, salt)
|
||||||
const salt = await bcrypt.genSalt(10)
|
const user = await User.findById(user_id)
|
||||||
const hash = await bcrypt.hash(newPassword, salt)
|
if (!user) {
|
||||||
const user = await User.findById(user_id)
|
res.status(404)
|
||||||
if (!user) {
|
throw new Error(_faSr.not_found.user_id)
|
||||||
res.status(404)
|
}
|
||||||
throw new Error(_faSr.not_found.user_id)
|
const passwordMatch = await bcrypt.compare(password, user.password)
|
||||||
}
|
if (!passwordMatch) {
|
||||||
const passwordMatch = await bcrypt.compare(password, user.password)
|
res.status(401)
|
||||||
if (!passwordMatch) {
|
throw new Error('err')
|
||||||
res.status(401)
|
}
|
||||||
throw new Error('err')
|
user.password = hash
|
||||||
}
|
await user.save()
|
||||||
user.password = hash
|
return res.json({ message: _faSr.response.success_save })
|
||||||
await user.save()
|
} catch (err) {
|
||||||
return res.json({ message: _faSr.response.success_save })
|
throw new Error(err.message)
|
||||||
} catch (err) {
|
|
||||||
throw new Error(err.message)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.send_otp = [
|
module.exports.send_otp = [
|
||||||
[
|
[body('mobile_number').notEmpty().withMessage(_faSr.required.phone_number)],
|
||||||
body('mobile_number')
|
checkValidations(validationResult),
|
||||||
.notEmpty()
|
async (req, res) => {
|
||||||
.withMessage(_faSr.required.phone_number)
|
try {
|
||||||
],
|
const { mobile_number } = req.body
|
||||||
checkValidations(validationResult),
|
const user = await User.findOne({ mobile_number })
|
||||||
async (req, res) => {
|
if (!user) {
|
||||||
try {
|
res.status(404)
|
||||||
const { mobile_number } = req.body
|
throw new Error(_sr.fa.not_found.user_id)
|
||||||
const user = await User.findOne({ mobile_number })
|
}
|
||||||
if (!user) {
|
await sendConfirmationSMS(user.id)
|
||||||
res.status(404)
|
res.status(200).json({ msg: 'ok' })
|
||||||
throw new Error(_sr.fa.not_found.user_id)
|
} catch (err) {
|
||||||
}
|
throw new Error(err.message)
|
||||||
await sendConfirmationSMS(user.id)
|
|
||||||
res.status(200).json({ msg: "ok" })
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error(err.message)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.check_otp = [
|
module.exports.check_otp = [
|
||||||
[
|
[
|
||||||
body('mobile_number')
|
body('mobile_number').notEmpty().withMessage(_faSr.required.phone_number),
|
||||||
.notEmpty()
|
body('otp').notEmpty().withMessage(_faSr.required.phone_number)
|
||||||
.withMessage(_faSr.required.phone_number),
|
],
|
||||||
body('otp')
|
checkValidations(validationResult),
|
||||||
.notEmpty()
|
async (req, res) => {
|
||||||
.withMessage(_faSr.required.phone_number)
|
try {
|
||||||
],
|
const { mobile_number, otp } = req.body
|
||||||
checkValidations(validationResult),
|
const user = await User.findOne({ mobile_number })
|
||||||
async (req, res) => {
|
if (!user) throw new Error(_sr.fa.not_found.user_id)
|
||||||
try {
|
if (user.otp !== otp) throw new Error('کد اشتباه است')
|
||||||
const { mobile_number, otp } = req.body
|
if (user.otp === otp) res.status(200).json({ msg: 'ok' })
|
||||||
const user = await User.findOne({ mobile_number })
|
} catch (err) {
|
||||||
if (!user) throw new Error(_sr.fa.not_found.user_id)
|
throw new Error(err.message)
|
||||||
if (user.otp !== otp) throw new Error("کد اشتباه است")
|
|
||||||
if (user.otp === otp) res.status(200).json({ msg: "ok" })
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error(err.message)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.resetpass_otp = [
|
module.exports.resetpass_otp = [
|
||||||
[
|
[
|
||||||
body('mobile_number')
|
body('mobile_number').notEmpty().withMessage(_faSr.required.phone_number),
|
||||||
.notEmpty()
|
body('otp').notEmpty().withMessage(_faSr.required.phone_number),
|
||||||
.withMessage(_faSr.required.phone_number),
|
body('password')
|
||||||
body('otp')
|
.isLength({ min: 4 })
|
||||||
.notEmpty()
|
.withMessage(_faSr.min_char.min4)
|
||||||
.withMessage(_faSr.required.phone_number),
|
.custom((value, { req }) => {
|
||||||
body('password')
|
if (value === req.body?.password_confirmation) return true
|
||||||
.isLength({ min: 4 })
|
else return Promise.reject(_faSr.response.passwords_not_match)
|
||||||
.withMessage(_faSr.min_char.min4)
|
})
|
||||||
.custom((value, { req }) => {
|
],
|
||||||
if (value === req.body?.password_confirmation) return true
|
checkValidations(validationResult),
|
||||||
else return Promise.reject(_faSr.response.passwords_not_match)
|
async (req, res) => {
|
||||||
})
|
try {
|
||||||
],
|
const { mobile_number, otp, password } = req.body
|
||||||
checkValidations(validationResult),
|
const salt = await bcrypt.genSalt(10)
|
||||||
async (req, res) => {
|
const hash = await bcrypt.hash(password, salt)
|
||||||
try {
|
const user = await User.findOne({ mobile_number })
|
||||||
const { mobile_number, otp, password } = req.body
|
if (!user) throw new Error(_sr.fa.not_found.user_id)
|
||||||
const salt = await bcrypt.genSalt(10)
|
if (user.otp !== otp) throw new Error('کد اشتباه است')
|
||||||
const hash = await bcrypt.hash(password, salt)
|
if (user.otp === otp) {
|
||||||
const user = await User.findOne({ mobile_number })
|
user.password = hash
|
||||||
if (!user) throw new Error(_sr.fa.not_found.user_id)
|
user.otp = generateRandomDigits(6)
|
||||||
if (user.otp !== otp) throw new Error("کد اشتباه است")
|
user.save()
|
||||||
if (user.otp === otp) {
|
res.status(200).json({ msg: _sr.fa.response.success_save })
|
||||||
user.password = hash
|
}
|
||||||
user.otp = generateRandomDigits(6)
|
} catch (err) {
|
||||||
user.save()
|
throw new Error(err.message)
|
||||||
res.status(200).json({ msg: _sr.fa.response.success_save })
|
|
||||||
}
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error(err.message)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.getCurrent = async (req, res) => {
|
module.exports.getCurrent = async (req, res) => {
|
||||||
const user = await User.findById(req.user_id).select('-password -token -otp -seenByAdmin')
|
const user = await User.findById(req.user_id).select('-password -token -otp -seenByAdmin')
|
||||||
if (!user || !user.active) return res.ststus(404).json({ msg: _sr.fa.not_found.user_id })
|
if (!user || !user.active) return res.ststus(404).json({ msg: _sr.fa.not_found.user_id })
|
||||||
else return res.status(200).json({user})
|
else return res.status(200).json({ user })
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.getUsersForAdmin = async (req, res) => {
|
module.exports.getUsersForAdmin = async (req, res) => {
|
||||||
const user = await User.find({}).sort({ active: 1, created_at: -1 }).select('-password -token -otp -seenByAdmin -cardBank')
|
const user = await User.find({})
|
||||||
res.status(200).json(user)
|
.sort({ active: 1, created_at: -1 })
|
||||||
|
.select('-password -token -otp -seenByAdmin -cardBank')
|
||||||
|
res.status(200).json(user)
|
||||||
}
|
}
|
||||||
module.exports.getPendingUsersForAdmin = async (req, res) => {
|
module.exports.getPendingUsersForAdmin = async (req, res) => {
|
||||||
const user = await User.find({ active: false }).sort({ active: 1, created_at: -1 }).select('-password -token -otp -seenByAdmin -cardBank')
|
const user = await User.find({ active: false })
|
||||||
res.status(200).json(user)
|
.sort({ active: 1, created_at: -1 })
|
||||||
|
.select('-password -token -otp -seenByAdmin -cardBank')
|
||||||
|
res.status(200).json(user)
|
||||||
}
|
}
|
||||||
module.exports.getUserForAdmin = async (req, res) => {
|
module.exports.getUserForAdmin = async (req, res) => {
|
||||||
const user = await User.findById(req.params.id).select('-password -token -otp -seenByAdmin')
|
const user = await User.findById(req.params.id).select('-password -token -otp -seenByAdmin')
|
||||||
if (!user) {
|
if (!user) {
|
||||||
return res.status(404).json({ msg: _sr.fa.not_found.user_id })
|
return res.status(404).json({ msg: _sr.fa.not_found.user_id })
|
||||||
} else {
|
} else {
|
||||||
user.seenByAdmin = true
|
user.seenByAdmin = true
|
||||||
user.save()
|
user.save()
|
||||||
res.status(200).json(user)
|
res.status(200).json(user)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports.activeUser = [
|
module.exports.activeUser = [
|
||||||
[
|
[
|
||||||
param('status').notEmpty().isBoolean().withMessage('این استاتوس اشتباه است'),
|
param('status').notEmpty().isBoolean().withMessage('این استاتوس اشتباه است'),
|
||||||
param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه است')
|
param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه است')
|
||||||
],
|
],
|
||||||
checkValidations(validationResult),
|
checkValidations(validationResult),
|
||||||
async (req, res) => {
|
async (req, res) => {
|
||||||
const data = await User.findByIdAndUpdate(req.params.id,
|
const data = await User.findByIdAndUpdate(
|
||||||
{
|
req.params.id,
|
||||||
active: req.params.status
|
{
|
||||||
},
|
active: req.params.status
|
||||||
{ new: true }).select('-password -token -otp -seenByAdmin')
|
},
|
||||||
if (!data) return res.status(404).json({ msg: _sr.fa.not_found.user_id })
|
{ new: true }
|
||||||
|
).select('-password -token -otp -seenByAdmin')
|
||||||
|
if (!data) return res.status(404).json({ msg: _sr.fa.not_found.user_id })
|
||||||
|
|
||||||
notifyAdmin('pendingUsers')
|
notifyAdmin('pendingUsers')
|
||||||
|
|
||||||
res.status(200).json(data)
|
res.status(200).json(data)
|
||||||
|
}
|
||||||
}
|
|
||||||
]
|
]
|
||||||
|
|
||||||
module.exports.addUserByAdmin = [
|
module.exports.addUserByAdmin = [
|
||||||
[
|
[
|
||||||
body('first_name')
|
body('first_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('last_name')
|
body('last_name')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.first_name)
|
.withMessage(_faSr.required.first_name)
|
||||||
.bail()
|
.bail()
|
||||||
.isLength({ min: 2 })
|
.isLength({ min: 2 })
|
||||||
.withMessage(_faSr.min_char.min2)
|
.withMessage(_faSr.min_char.min2)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
|
||||||
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
|
||||||
else return true
|
else return true
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('national_code')
|
body('national_code')
|
||||||
.notEmpty()
|
.notEmpty()
|
||||||
.withMessage(_faSr.required.national_code)
|
.withMessage(_faSr.required.national_code)
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
if (checkNationalCode(value)) return true
|
if (checkNationalCode(value)) return true
|
||||||
else return Promise.reject(_faSr.format.national_code)
|
else return Promise.reject(_faSr.format.national_code)
|
||||||
})
|
})
|
||||||
.bail()
|
.bail()
|
||||||
.custom((value, { req }) => {
|
.custom((value, { req }) => {
|
||||||
const nationalCode = value.trim()
|
const nationalCode = value.trim()
|
||||||
return User.findOne({ national_code: nationalCode }).then(user => {
|
return User.findOne({ national_code: nationalCode }).then(user => {
|
||||||
if (user && user.national_code === nationalCode)
|
if (user && user.national_code === nationalCode)
|
||||||
return Promise.reject(new Error('کاربر با این کد ملی از قبل وجود دارد'))
|
return Promise.reject(new Error('کاربر با این کد ملی از قبل وجود دارد'))
|
||||||
else return true
|
else return true
|
||||||
})
|
})
|
||||||
}),
|
}),
|
||||||
|
|
||||||
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
body('province_name').notEmpty().withMessage(_faSr.required.province),
|
||||||
|
|
||||||
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
body('city_name').notEmpty().withMessage(_faSr.required.city),
|
||||||
|
|
||||||
body('shopName')
|
body('shopName').notEmpty().withMessage(_faSr.required.address),
|
||||||
.notEmpty()
|
|
||||||
.withMessage(_faSr.required.address),
|
|
||||||
|
|
||||||
|
body('mobile_number')
|
||||||
|
.notEmpty()
|
||||||
|
.withMessage(_faSr.required.phone_number)
|
||||||
|
.bail()
|
||||||
|
.custom((value, { req }) => {
|
||||||
|
const mobileNStatus = checkMobileNumber(value)
|
||||||
|
if (!mobileNStatus) return Promise.reject(_faSr.format.phone_number)
|
||||||
|
else return Promise.resolve()
|
||||||
|
})
|
||||||
|
.bail()
|
||||||
|
.custom((value, { req }) => {
|
||||||
|
const mobileNumber = value.trim()
|
||||||
|
return User.findOne({ mobile_number: mobileNumber }).then(user => {
|
||||||
|
if (user && user.mobile_number === mobileNumber)
|
||||||
|
return Promise.reject(new Error('کاربر با این شماره موبایل از قبل وجود دارد'))
|
||||||
|
else return true
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
|
||||||
body('mobile_number')
|
body('password')
|
||||||
.notEmpty()
|
.isLength({ min: 4 })
|
||||||
.withMessage(_faSr.required.phone_number)
|
.withMessage(_faSr.min_char.min4)
|
||||||
.bail()
|
.custom((value, { req }) => {
|
||||||
.custom((value, { req }) => {
|
if (value === req.body.password_confirmation) return true
|
||||||
const mobileNStatus = checkMobileNumber(value)
|
else return Promise.reject(_faSr.response.passwords_not_match)
|
||||||
if (!mobileNStatus) return Promise.reject(_faSr.format.phone_number)
|
})
|
||||||
else return Promise.resolve()
|
],
|
||||||
})
|
checkValidations(validationResult),
|
||||||
.bail()
|
async (req, res) => {
|
||||||
.custom((value, { req }) => {
|
try {
|
||||||
const mobileNumber = value.trim()
|
const provinceId = uid.v4()
|
||||||
return User.findOne({ mobile_number: mobileNumber }).then(user => {
|
const cityId = uid.v4()
|
||||||
if (user && user.mobile_number === mobileNumber)
|
|
||||||
return Promise.reject(new Error('کاربر با این شماره موبایل از قبل وجود دارد'))
|
|
||||||
else return true
|
|
||||||
})
|
|
||||||
}),
|
|
||||||
|
|
||||||
body('password')
|
const { first_name, last_name, national_code, province_name, city_name, mobile_number, password, shopName } =
|
||||||
.isLength({ min: 4 })
|
req.body
|
||||||
.withMessage(_faSr.min_char.min4)
|
|
||||||
.custom((value, { req }) => {
|
|
||||||
if (value === req.body.password_confirmation) return true
|
|
||||||
else return Promise.reject(_faSr.response.passwords_not_match)
|
|
||||||
})
|
|
||||||
],
|
|
||||||
checkValidations(validationResult),
|
|
||||||
async (req, res) => {
|
|
||||||
try {
|
|
||||||
const provinceId = uid.v4()
|
|
||||||
const cityId = uid.v4()
|
|
||||||
|
|
||||||
const {
|
const data = {
|
||||||
first_name,
|
last_name,
|
||||||
last_name,
|
province_name: { id: provinceId, provinceName: province_name },
|
||||||
national_code,
|
city_name: { id: cityId, cityName: city_name },
|
||||||
province_name,
|
shopName,
|
||||||
city_name,
|
active: true
|
||||||
mobile_number,
|
}
|
||||||
password,
|
data.first_name = nameOptimizer(first_name)
|
||||||
shopName
|
data.national_code = national_code.trim()
|
||||||
} = req.body
|
data.mobile_number = normalizeMobileNumber(mobile_number)
|
||||||
|
|
||||||
const data = {
|
// hash user password and done
|
||||||
last_name,
|
const salt = await bcrypt.genSalt(10)
|
||||||
province_name:{id:provinceId,provinceName:province_name},
|
const hash = await bcrypt.hash(password, salt)
|
||||||
city_name:{id:cityId,cityName:city_name},
|
data.password = hash
|
||||||
shopName,
|
|
||||||
active:true
|
|
||||||
}
|
|
||||||
data.first_name = nameOptimizer(first_name)
|
|
||||||
data.national_code = national_code.trim()
|
|
||||||
data.mobile_number = normalizeMobileNumber(mobile_number)
|
|
||||||
|
|
||||||
|
const user = new User(data)
|
||||||
|
await user.save()
|
||||||
|
|
||||||
// hash user password and done
|
return res.status(200).json({ message: _faSr.response.success_save })
|
||||||
const salt = await bcrypt.genSalt(10)
|
} catch (err) {
|
||||||
const hash = await bcrypt.hash(password, salt)
|
const registerFailurMsg = 'مشکلی در ثبت نام پیش آمده، لطفا مجددا تلاش کنید'
|
||||||
data.password = hash
|
res500(res, registerFailurMsg)
|
||||||
|
|
||||||
const user = new User(data)
|
|
||||||
await user.save()
|
|
||||||
|
|
||||||
|
|
||||||
return res.status(200).json({ message: _faSr.response.success_save })
|
|
||||||
} catch (err) {
|
|
||||||
const registerFailurMsg = 'مشکلی در ثبت نام پیش آمده، لطفا مجددا تلاش کنید'
|
|
||||||
res500(res, registerFailurMsg)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
}
|
||||||
]
|
]
|
||||||
@@ -24,6 +24,7 @@ module.exports._sr = {
|
|||||||
province: 'استان را وارد کنید',
|
province: 'استان را وارد کنید',
|
||||||
city: 'شهر را وارد کنید',
|
city: 'شهر را وارد کنید',
|
||||||
address: 'آدرس را وارد کنید',
|
address: 'آدرس را وارد کنید',
|
||||||
|
iban: 'شماره شبا را وارد کنید',
|
||||||
postal_code: 'کد پستی را وارد کنید',
|
postal_code: 'کد پستی را وارد کنید',
|
||||||
plaque: 'پلاک را وارد کنید',
|
plaque: 'پلاک را وارد کنید',
|
||||||
receiver_first_name: 'نام گیرنده را وارد کنید',
|
receiver_first_name: 'نام گیرنده را وارد کنید',
|
||||||
@@ -109,7 +110,7 @@ module.exports._sr = {
|
|||||||
name: 'نام تکراری است',
|
name: 'نام تکراری است',
|
||||||
title: 'عنوان تکراری است',
|
title: 'عنوان تکراری است',
|
||||||
phone_number: 'این شماره تماس از قبل وجود دارد',
|
phone_number: 'این شماره تماس از قبل وجود دارد',
|
||||||
IMEI:'این IMEI تکراری است'
|
IMEI: 'این IMEI تکراری است'
|
||||||
},
|
},
|
||||||
response: {
|
response: {
|
||||||
logged_in: 'شما وارد سیستم شدید',
|
logged_in: 'شما وارد سیستم شدید',
|
||||||
|
|||||||
@@ -17,7 +17,6 @@ router.get('/renew', renewal.findAllUser)
|
|||||||
router.get('/notif/:id', notif.setSeen)
|
router.get('/notif/:id', notif.setSeen)
|
||||||
router.get('/notif', notif.setSeenAll)
|
router.get('/notif', notif.setSeenAll)
|
||||||
|
|
||||||
|
|
||||||
/// /////////////// User
|
/// /////////////// User
|
||||||
router.get('/user/me', userGPS.getCurrent)
|
router.get('/user/me', userGPS.getCurrent)
|
||||||
router.put('/user/me/:id', userGPS.update_user)
|
router.put('/user/me/:id', userGPS.update_user)
|
||||||
@@ -28,7 +27,6 @@ router.post('/user/reset-pass', userGPS.update_user_password)
|
|||||||
router.get('/overview/main', overview.mainPage)
|
router.get('/overview/main', overview.mainPage)
|
||||||
router.get('/overview/wallet', overview.walletPage)
|
router.get('/overview/wallet', overview.walletPage)
|
||||||
|
|
||||||
|
|
||||||
/// ////////////// Award request
|
/// ////////////// Award request
|
||||||
router.post('/award-request', awardRequest.sendRequest)
|
router.post('/award-request', awardRequest.sendRequest)
|
||||||
router.get('/award-request', awardRequest.findAllUser)
|
router.get('/award-request', awardRequest.findAllUser)
|
||||||
@@ -39,6 +37,8 @@ router.get('/award', award.findAllUser)
|
|||||||
/// ///////////////// Bank card
|
/// ///////////////// Bank card
|
||||||
router.post('/bank-card', bankAccount.addCard)
|
router.post('/bank-card', bankAccount.addCard)
|
||||||
router.get('/bank-card', bankAccount.getAll)
|
router.get('/bank-card', bankAccount.getAll)
|
||||||
|
router.get('/bank-card/:id', bankAccount.getOne)
|
||||||
|
router.put('/bank-card/:id', bankAccount.updateCard)
|
||||||
router.delete('/bank-card/:id', bankAccount.deleteCard)
|
router.delete('/bank-card/:id', bankAccount.deleteCard)
|
||||||
/// ///////////////// Withdraw request
|
/// ///////////////// Withdraw request
|
||||||
router.post('/withdraw', withdraw.createRequest)
|
router.post('/withdraw', withdraw.createRequest)
|
||||||
|
|||||||
Reference in New Issue
Block a user