diff --git a/pages/account/guarantee/index.vue b/pages/account/guarantee/index.vue
index dc6a3b7..522580d 100644
--- a/pages/account/guarantee/index.vue
+++ b/pages/account/guarantee/index.vue
@@ -46,7 +46,7 @@
{{ $jDate(item.ItemReceptionTransDate) }}
- {{ item.deliveryCode || '-' }}
+ {{ item }}
|
نظر ثبت شده
diff --git a/server/WebSocket/controllers/admin_EventsController.js b/server/WebSocket/controllers/admin_EventsController.js
index da300e8..fdf4647 100644
--- a/server/WebSocket/controllers/admin_EventsController.js
+++ b/server/WebSocket/controllers/admin_EventsController.js
@@ -8,7 +8,7 @@ const BufferRequest = require('../../models/BufferRequest')
const GuaranteeReport = require('../../models/GuaranteeReport')
const Complaint = require('../../models/Complaint')
const Withdraw = require('../../models/GPS.Withdraw');
-const RequestGPS = require('../../models/GPS.Request')
+const UserGPS = require('../../models/GPS.User')
const AwardRequest = require('../../models/GPS.AwardRequest');
const InstalledDevice = require('../../models/GPS.InstalledDevice');
@@ -46,7 +46,7 @@ module.exports.getAllNotifs = async socket => {
Withdraw.countDocuments({ status: 0 }),
// unread GPS request
- RequestGPS.countDocuments({ status: 0 }),
+ UserGPS.countDocuments({ active: false }),
// unread award request
AwardRequest.countDocuments({ status: 0 }),
diff --git a/server/authentication.js b/server/authentication.js
index 1289045..cea3acc 100644
--- a/server/authentication.js
+++ b/server/authentication.js
@@ -1,5 +1,6 @@
const jwt = require('jsonwebtoken')
const User = require('./models/User')
+const UserGPS = require('./models/GPS.User')
function res401(res, message) {
return res.status(401).json({ message })
@@ -48,13 +49,13 @@ const authentication = {
const decoded = jwt.verify(token.replace(/^Bearer\s/, ''), authentication.secretKey)
if (!decoded) throw new Error('err2')
- const user = await User.findById(decoded._id)
- if (!user || !user.scope.includes('gps')) throw new Error('err3')
+ const user = await UserGPS.findById(decoded._id)
+ if (!user || !user.active) throw new Error('err3')
req.user_id = decoded._id
return next()
} catch (err) {
- return res401(res, 'unauthorized')
+ return res401(res, 'unauthorized'+ err.message)
}
},
// check if user logged in (middleware)
diff --git a/server/controllers/GPS.Auth.js b/server/controllers/GPS.Auth.js
index 16b1e3b..c8bbf0b 100644
--- a/server/controllers/GPS.Auth.js
+++ b/server/controllers/GPS.Auth.js
@@ -4,61 +4,101 @@ const { body, validationResult } = require('express-validator')
const { secretKey } = require('../authentication')
const { _sr } = require('../plugins/serverResponses')
const { checkValidations } = require('../plugins/controllersHelperFunctions')
-const User = require('../models/User')
+const UserGPS = require('../models/GPS.User')
+const { generateRandomDigits
+} = require('../plugins/controllersHelperFunctions')
+module.exports.login_with_pass = [
+ [
+ body('username')
+ .isLength({ min: 4 })
+ .withMessage(_sr.fa.min_char.min4)
+ .bail()
+ .if((value, { req }) => {
+ return req.body.password && req.body.password.length >= 4
+ })
+ .custom((value, { req }) => {
+ return UserGPS.findOne({
+ $or: [{ national_code: value }, { mobile_number: value }]
+ }).then(user => {
+ if (!user) return Promise.reject(_sr.fa.not_found.password)
+ else return true
+ })
+ }),
+ body('password')
+ .notEmpty()
+ .withMessage(_sr.fa.required.password)
+ .bail()
+ .isLength({ min: 4 })
+ .withMessage(_sr.fa.min_char.min4),
+ body('remember_me')
+ .exists()
+ .withMessage(_sr.fa.required.remember_me)
+ .bail()
+ .isBoolean()
+ .withMessage(_sr.fa.format.boolean)
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const { username, password } = req.body
+ const user = await UserGPS.findOne({
+ $or: [{ national_code: username }, { mobile_number: username }]
+ })
+ if (!user) throw new Error(_sr.fa.not_found.password)
+ const passwordMatch = await bcrypt.compare(password, user.password)
+ if (!passwordMatch) throw new Error(_sr.fa.not_found.password)
+ if (!user.active) {
+ throw new Error('حساب شما هنوز تاییده نشده است')
+ }
+ const token = await jwt.sign({ _id: user._id }, secretKey, {
+ expiresIn: req.body.remember_me ? '30d' : '7d'
+ })
+ user.token = token
+ await user.save()
+ return res.status(200).json({ token })
+ } catch (err) {
+ return res.status(422).json({
+ validation: { username: { msg: err.message } }
+ })
+ }
+ }
+]
-module.exports.login = [
- [
- body('username')
- .isLength({ min: 4 })
- .withMessage(_sr.fa.min_char.min4)
- .bail()
- .if((value, { req }) => {
- return req.body.password && req.body.password.length >= 4
- })
- .custom((value, { req }) => {
- return User.findOne({
- $or: [{ email: value.toLowerCase().trim() }, { national_code: value }, { username: value }]
- }).then(user => {
- if (!user) return Promise.reject(_sr.fa.not_found.password)
- else return true
- })
- }),
- body('password')
- .notEmpty()
- .withMessage(_sr.fa.required.password)
- .bail()
- .isLength({ min: 4 })
- .withMessage(_sr.fa.min_char.min4),
- body('remember_me')
- .exists()
- .withMessage(_sr.fa.required.remember_me)
- .bail()
- .isBoolean()
- .withMessage(_sr.fa.format.boolean)
- ],
- checkValidations(validationResult),
- async (req, res) => {
- try {
- const { username, password } = req.body
- const user = await User.findOne({
- $or: [{ email: username.toLowerCase().trim() }, { national_code: username }, { username }]
- })
- if (!user) throw new Error(_sr.fa.not_found.password)
- const passwordMatch = await bcrypt.compare(password, user.password)
- if (!passwordMatch) throw new Error(_sr.fa.not_found.password)
+
+module.exports.login_with_otp = [
+ [
+ body('mobile_number')
+ .notEmpty()
+ .withMessage(_sr.fa.required.phone_number),
+ body('otp')
+ .notEmpty()
+ .withMessage(_sr.fa.required.phone_number)
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const { mobile_number, otp } = req.body
+ const user = await UserGPS.findOne({ mobile_number })
+ if (!user) throw new Error(_sr.fa.not_found.user_id)
+ if (user.otp !== otp) throw new Error("کد اشتباه است")
+ if (user.otp === otp) {
+ if (!user.active) {
+ throw new Error('حساب شما هنوز تاییده نشده است')
+ }
const token = await jwt.sign({ _id: user._id }, secretKey, {
expiresIn: req.body.remember_me ? '30d' : '7d'
})
- if(!user.scope.includes('gps')){
- throw new Error('شما به این بخش دسترسی ندارید')
- }
- user.token = token
- await user.save()
+ user.otp = generateRandomDigits(6)
+ user.save()
return res.status(200).json({ token })
- } catch (err) {
- return res.status(422).json({
- validation: { username: { msg: err.message } }
- })
+
}
+ } catch (err) {
+ return res.status(422).json({
+ validation: { otp: { msg: err.message } }
+ })
+
}
- ]
\ No newline at end of file
+
+ }
+]
\ No newline at end of file
diff --git a/server/controllers/GPS.Overview.js b/server/controllers/GPS.Overview.js
index 225c675..5155355 100644
--- a/server/controllers/GPS.Overview.js
+++ b/server/controllers/GPS.Overview.js
@@ -1,4 +1,4 @@
-const User = require('../models/User');
+const User = require('../models/GPS.User');
const InstalledDevice = require('../models/GPS.InstalledDevice');
const Withdraw = require('../models/GPS.Withdraw');
diff --git a/server/controllers/GPS.Request.js b/server/controllers/GPS.Request.js
deleted file mode 100644
index 8c53463..0000000
--- a/server/controllers/GPS.Request.js
+++ /dev/null
@@ -1,147 +0,0 @@
-const { body, param, validationResult } = require('express-validator')
-const { _sr } = require('../plugins/serverResponses')
-const { checkValidations, res400 } = require('../plugins/controllersHelperFunctions')
-const User = require('../models/User')
-const RequestGPS = require('../models/GPS.Request')
-
-module.exports.gpsRequest = [
- [
- body('shopName').notEmpty().isString().withMessage(_sr.fa.required.name),
- body('shopNumber').notEmpty().isString().withMessage(_sr.fa.required.store_number),
- body('shopAddress').notEmpty().isString().withMessage(_sr.fa.required.address),
- body('birthDate').notEmpty().isString().withMessage(_sr.fa.required.date),
- ],
- checkValidations(validationResult),
- async (req, res) => {
- const { shopName, shopNumber, shopAddress, birthDate, profilePic } = req.body;
- const repeated = await RequestGPS.findOne({ userId: req.user_id })
- if (repeated) {
- res400(res, "شما قبلا درخواست ثبت کرده اید")
- } else {
- const request = await RequestGPS.create({
- shopName,
- shopNumber,
- shopAddress,
- birthDate,
- profilePic,
- userId: req.user_id,
- })
- // res.status(201).json({ msg: 'درخواست شما با موفقیت ثبت شد', date: request })
- res.status(201).json(request)
-
- }
-
- }
-]
-
-
-module.exports.getAllRequest = [
- async (req, res) => {
- let page;
- let rows;
- if (!req.query?.rows) {
- rows = 10
- } else {
- rows = req.query.rows
- }
- if (!req.query?.page) {
- page = 0
- // eslint-disable-next-line eqeqeq
- } else if (!req.query.page == 1) {
- page = 0
- } else {
- page = req.query.page
- page = page * rows - rows
- }
- const data = await RequestGPS.find({}).sort({ status: 1 }).skip(page).limit(rows)
- .populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic')
- const total = Math.ceil((await RequestGPS.estimatedDocumentCount()))
- res.status(200).json({ data, total })
- }
-]
-
-module.exports.getOneRequest = [
- [
- param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه است')
- ],
- checkValidations(validationResult),
- async (req, res) => {
- const data = await RequestGPS.findById(req.params.id).populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic')
- res.status(200).json(data)
- }
-]
-
-
-module.exports.changeStatus = [
- [
- param('status').notEmpty().isString().withMessage('این استاتوس اشتباه است'),
- param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه است')
- ],
- checkValidations(validationResult),
- async (req, res) => {
- switch (req.params.status) {
- case "accept": {
- const data = await RequestGPS.findByIdAndUpdate(req.params.id,
- {
- status: 1
- },
- { new: true })
- const userPreData = await User.findById(data.userId).select('walletBalance dollarBalance score scope')
- if(userPreData.scope.includes('gps')){
- const userData = await User.findByIdAndUpdate(
- data.userId,
- {
- shopName: data.shopName,
- shopNumber: data.shopNumber,
- shopAddress: data.shopAddress,
- birthDate: data.birthDate,
- walletBalance: userPreData?.walletBalance | 0,
- dollarBalance: userPreData?.dollarBalance | 0,
- score: userPreData?.score | 0,
- $push:{scope:'gps'}
- },
- { new: true }
- ).select('first_name last_name')
- // res.status(200).json({ msg: 'با موفقیت به روز شد', data: userData })
- res.status(200).json(userData)
-
-
- }else{
- const userData = await User.findByIdAndUpdate(
- data.userId,
- {
- shopName: data.shopName,
- shopNumber: data.shopNumber,
- shopAddress: data.shopAddress,
- birthDate: data.birthDate,
- walletBalance: userPreData?.walletBalance | 0,
- dollarBalance: userPreData?.dollarBalance | 0,
- score: userPreData?.score | 0,
- },
- { new: true }
- ).select('first_name last_name')
- // res.status(200).json({ msg: 'با موفقیت به روز شد', data: userData })
- res.status(200).json(userData)
-
-
- }
- break;
- }
- case "reject": {
- const data = await RequestGPS.findByIdAndUpdate(req.params.id,
- {
- status: 2
- },
- { new: true })
-
- // res.status(200).json({ msg: 'با موفقیت به روز شد', data })
- res.status(200).json(data)
-
- break;
- }
- default:
- res.status(400).json({ msg: 'این استاتوس اشتباه است' })
- break;
- }
- }
-]
diff --git a/server/controllers/GPS.User.js b/server/controllers/GPS.User.js
new file mode 100644
index 0000000..4570e2e
--- /dev/null
+++ b/server/controllers/GPS.User.js
@@ -0,0 +1,405 @@
+/* eslint-disable no-unused-vars */
+const bcrypt = require('bcryptjs')
+const { body, validationResult, param } = require('express-validator')
+const User = require('../models/GPS.User')
+const { _sr } = require('../plugins/serverResponses')
+const { SMS } = require('../plugins/SMS_Module')
+const {
+ res500,
+ checkValidations,
+ removeWhiteSpaces,
+ checkMobileNumber,
+ normalizeMobileNumber,
+ nameOptimizer,
+ checkNationalCode,
+ isPersian,
+ generateRandomDigits
+} = require('../plugins/controllersHelperFunctions')
+const _faSr = _sr.fa
+
+
+
+function sendConfirmationSMS(userId) {
+ return new Promise(async (resolve, reject) => {
+ try {
+ const user = await User.findById(userId)
+ if (!user) throw new Error('invalid id')
+
+ const mobileKey = generateRandomDigits(6)
+ user.otp = mobileKey
+ await user.save()
+
+ const smsMsg = [
+ 'این شماره در وبسایت آسان سرویس ثبت گردیده.',
+ ' کد تایید شماره همراه: ',
+ mobileKey
+ ]
+
+ await SMS([user.mobile_number], smsMsg.join(''))
+
+ resolve()
+ } catch (err) {
+ reject(err)
+ }
+ })
+}
+
+module.exports.register_user = [
+ [
+ body('first_name')
+ .notEmpty()
+ .withMessage(_faSr.required.first_name)
+ .bail()
+ .isLength({ min: 2 })
+ .withMessage(_faSr.min_char.min2)
+ .bail()
+ .custom((value, { req }) => {
+ if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
+ if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
+ else return true
+ }),
+
+ body('last_name')
+ .notEmpty()
+ .withMessage(_faSr.required.first_name)
+ .bail()
+ .isLength({ min: 2 })
+ .withMessage(_faSr.min_char.min2)
+ .bail()
+ .custom((value, { req }) => {
+ if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
+ if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
+ else return true
+ }),
+
+ body('national_code')
+ .notEmpty()
+ .withMessage(_faSr.required.national_code)
+ .bail()
+ .custom((value, { req }) => {
+ if (checkNationalCode(value)) return true
+ else return Promise.reject(_faSr.format.national_code)
+ })
+ .bail()
+ .custom((value, { req }) => {
+ const nationalCode = value.trim()
+ return User.findOne({ national_code: nationalCode }).then(user => {
+ if (user && user.national_code === nationalCode)
+ return Promise.reject(new Error('کاربر با این کد ملی از قبل وجود دارد'))
+ else return true
+ })
+ }),
+
+ body('province_name').notEmpty().withMessage(_faSr.required.province),
+
+ body('city_name').notEmpty().withMessage(_faSr.required.city),
+
+ body('shopName')
+ .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('password')
+ .isLength({ min: 4 })
+ .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 {
+ first_name,
+ last_name,
+ national_code,
+ province_name,
+ city_name,
+ mobile_number,
+ password,
+ shopName
+ } = req.body
+
+ const data = {
+ last_name,
+ province_name,
+ city_name,
+ shopName
+ }
+ data.first_name = nameOptimizer(first_name)
+ data.national_code = national_code.trim()
+ data.mobile_number = normalizeMobileNumber(mobile_number)
+
+
+ // hash user password and done
+ const salt = await bcrypt.genSalt(10)
+ const hash = await bcrypt.hash(password, salt)
+ data.password = hash
+
+ const user = new User(data)
+ await user.save()
+ return res.json({ message: _faSr.response.success_save })
+ } catch (err) {
+ const registerFailurMsg = 'مشکلی در ثبت نام پیش آمده، لطفا مجددا تلاش کنید'
+ res500(res, registerFailurMsg)
+ }
+ }
+]
+
+
+module.exports.update_user = [
+ [
+ body('first_name')
+ .notEmpty()
+ .withMessage(_faSr.required.first_name)
+ .bail()
+ .isLength({ min: 2 })
+ .withMessage(_faSr.min_char.min2)
+ .bail()
+ .custom((value, { req }) => {
+ if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
+ if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
+ else return true
+ }),
+
+ body('last_name')
+ .notEmpty()
+ .withMessage(_faSr.required.first_name)
+ .bail()
+ .isLength({ min: 2 })
+ .withMessage(_faSr.min_char.min2)
+ .bail()
+ .custom((value, { req }) => {
+ if (removeWhiteSpaces(value).length < 2) return Promise.reject(_faSr.min_char.min2)
+ if (!isPersian(value)) return Promise.reject(new Error('لطفا با حروف فارسی تایپ کنید'))
+ else return true
+ }),
+ body('province_name').notEmpty().withMessage(_faSr.required.province),
+
+ body('city_name').notEmpty().withMessage(_faSr.required.city),
+
+ body('shopName')
+ .notEmpty()
+ .withMessage(_faSr.required.field),
+ body('address')
+ .notEmpty()
+ .withMessage(_faSr.required.address),
+
+ body('cell_number')
+ .notEmpty()
+ .withMessage(_faSr.required.address),
+
+ body('birthDate')
+ .notEmpty()
+ .withMessage(_faSr.required.address),
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const {
+ first_name,
+ last_name,
+ province_name,
+ city_name,
+ shopName,
+ birthDate,
+ address,
+ cell_number
+ } = req.body
+
+ const data = {
+ last_name,
+ province_name,
+ city_name,
+ shopName,
+ birthDate,
+ address,
+ cell_number
+ }
+ data.first_name = nameOptimizer(first_name)
+ await User.findByIdAndUpdate(
+ req.params.id,
+ data
+ )
+ return res.json({ message: _faSr.response.success_save })
+ } catch (err) {
+ const registerFailurMsg = 'مشکلی در به روز رسانی پیش آمده، لطفا مجددا تلاش کنید'
+ res500(res, registerFailurMsg)
+ }
+ }
+]
+
+module.exports.update_user_password = [
+ [
+ body('newPassword')
+ .isLength({ min: 4 })
+ .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)
+ }),
+ body('password')
+ .isLength({ min: 4 })
+ .withMessage(_faSr.min_char.min4)
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const { password, newPassword } = req.body
+ const { user_id } = req
+ const salt = await bcrypt.genSalt(10)
+ const hash = await bcrypt.hash(newPassword, salt)
+ const user = await User.findById(user_id)
+ if (!user) throw new Error(_faSr.not_found.user_id)
+ const passwordMatch = await bcrypt.compare(password, user.password)
+ if (!passwordMatch) throw new Error('err')
+ user.password = hash
+ await user.save()
+ return res.json({ message: _faSr.response.success_save })
+ } catch (err) {
+ if (err) return res500(res, err)
+ }
+ }
+]
+
+module.exports.send_otp = [
+ [
+ body('mobile_number')
+ .notEmpty()
+ .withMessage(_faSr.required.phone_number)
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const { mobile_number } = req.body
+ const user = await User.findOne({ mobile_number })
+ if (!user) throw new Error(_sr.fa.not_found.user_id)
+ await sendConfirmationSMS(user.id)
+ res.status(200).json({msg:"ok"})
+ } catch (err) {
+ if (err) return res500(res, err)
+ }
+ }
+]
+
+module.exports.check_otp = [
+ [
+ body('mobile_number')
+ .notEmpty()
+ .withMessage(_faSr.required.phone_number),
+ body('otp')
+ .notEmpty()
+ .withMessage(_faSr.required.phone_number)
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ try {
+ const { mobile_number, otp } = req.body
+ const user = await User.findOne({ mobile_number })
+ if (!user) throw new Error(_sr.fa.not_found.user_id)
+ if (user.otp !== otp) throw new Error("کد اشتباه است")
+ if (user.otp === otp) res.status(200).json({ msg: "ok" })
+ } catch (err) {
+ if (err) return res500(res, err.message)
+ }
+ }
+]
+
+module.exports.resetpass_otp = [
+ [
+ body('mobile_number')
+ .notEmpty()
+ .withMessage(_faSr.required.phone_number),
+ body('otp')
+ .notEmpty()
+ .withMessage(_faSr.required.phone_number),
+ body('password')
+ .isLength({ min: 4 })
+ .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 { mobile_number, otp, password } = req.body
+ const salt = await bcrypt.genSalt(10)
+ const hash = await bcrypt.hash(password, salt)
+ const user = await User.findOne({ mobile_number })
+ if (!user) throw new Error(_sr.fa.not_found.user_id)
+ if (user.otp !== otp) throw new Error("کد اشتباه است")
+ if (user.otp === otp) {
+ user.password = hash
+ user.otp = generateRandomDigits(6)
+ user.save()
+ res.status(200).json({ msg: _sr.fa.response.success_save })
+ }
+ } catch (err) {
+ if (err) return res500(res, err.message)
+ }
+ }
+]
+
+module.exports.getCurrent = async (req, res) => {
+ 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 })
+ else return res.status(200).json(user)
+}
+
+module.exports.getUsersForAdmin = async (req, res) => {
+ const user = await User.find({}).sort({ active: 1, created_at: -1 }).select('-password -token -otp -seenByAdmin')
+ res.status(200).json(user)
+}
+
+module.exports.getUserForAdmin = async (req, res) => {
+ const user = await User.findById(req.params.id).select('-password -token -otp -seenByAdmin')
+ if (!user) {
+ return res.status(404).json({ msg: _sr.fa.not_found.user_id })
+ }else {
+ user.seenByAdmin = true
+ user.save()
+ res.status(200).json(user)
+ }
+}
+
+module.exports.activeUser = [
+ [
+ param('status').notEmpty().isBoolean().withMessage('این استاتوس اشتباه است'),
+ param('id').notEmpty().isMongoId().withMessage('این ایدی اشتباه است')
+ ],
+ checkValidations(validationResult),
+ async (req, res) => {
+ const data = await User.findByIdAndUpdate(req.params.id,
+ {
+ 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 })
+
+
+ res.status(200).json(data)
+
+ }
+]
\ No newline at end of file
diff --git a/server/controllers/serialsExelController.js b/server/controllers/serialsExelController.js
index 740b586..3cdefb9 100644
--- a/server/controllers/serialsExelController.js
+++ b/server/controllers/serialsExelController.js
@@ -101,18 +101,16 @@ module.exports.checkSerial = [
try {
const { serial, type, g } = req.body
const serialStatus = await serialChecker(serial, type, g)
+console.log("s");
- console.log(serialStatus)
let okMsg
if (type === 'guaranteeSerial') okMsg = serialStatus
else okMsg = serialStatus
-
let errMsg
if (type === 'guaranteeSerial') errMsg = 'شماره سریال گارانتی معتبر نیست.'
else errMsg = 'شماره سریال کالا معتبر نیست.'
-
if (serialStatus) return res.json({ message: okMsg })
else return res404(res, errMsg)
} catch (e) {
diff --git a/server/database.js b/server/database.js
index 0f6c099..d59a6d9 100644
--- a/server/database.js
+++ b/server/database.js
@@ -5,7 +5,7 @@ const inHostUrl = 'mongodb://root:KPTt76tImNBBMm4Kor8QA9gB@asan-service:27017/as
const outHostUrl = 'mongodb://root:KPTt76tImNBBMm4Kor8QA9gB@hotaka.liara.cloud:33794/asanserv_database?authSource=admin'
const init = ()=>{
try {
- mongoose.connect(inHostUrl, {
+ mongoose.connect(outHostUrl, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
diff --git a/server/models/GPS.AwardRequest.js b/server/models/GPS.AwardRequest.js
index 4689cfc..b2ff3e1 100644
--- a/server/models/GPS.AwardRequest.js
+++ b/server/models/GPS.AwardRequest.js
@@ -7,7 +7,7 @@ const AwardRequestSchema = mongoose.Schema({
},
userId:{
type:String,
- ref:'User'
+ ref:'UserGPS'
},
desc:String,
metaData:Object,
diff --git a/server/models/GPS.InstalledDevice.js b/server/models/GPS.InstalledDevice.js
index 583964b..38f3f80 100644
--- a/server/models/GPS.InstalledDevice.js
+++ b/server/models/GPS.InstalledDevice.js
@@ -19,7 +19,7 @@ const InstalledDeviceSchema = mongoose.Schema({
installationDate: Date,
userId: {
type: String,
- ref: 'User'
+ ref: 'UserGPS'
},
})
diff --git a/server/models/GPS.Renewal.js b/server/models/GPS.Renewal.js
index a181274..9298bc8 100644
--- a/server/models/GPS.Renewal.js
+++ b/server/models/GPS.Renewal.js
@@ -26,7 +26,7 @@ const RenewalSchema = mongoose.Schema({
},
userId: {
type: String,
- ref: 'User'
+ ref: 'UserGPS'
},
})
diff --git a/server/models/GPS.Request.js b/server/models/GPS.Request.js
deleted file mode 100644
index d755842..0000000
--- a/server/models/GPS.Request.js
+++ /dev/null
@@ -1,23 +0,0 @@
-const mongoose = require('mongoose')
-
-const RequestSchema = mongoose.Schema({
- userId: {
- type: String,
- ref: 'User'
- },
- shopName: String,
- shopNumber: String,
- shopAddress: String,
- birthDate: String,
- status: {
- type: Number,
- enum: [
- 0, // Pending
- 1, // Accepted
- 2 // Rejected
- ],
- default: 0
- }
-})
-
-module.exports = mongoose.model('RequestGPS', RequestSchema)
diff --git a/server/models/GPS.Score.js b/server/models/GPS.Score.js
index 5e40807..b941a27 100644
--- a/server/models/GPS.Score.js
+++ b/server/models/GPS.Score.js
@@ -12,7 +12,7 @@ const ScoreSchema = mongoose.Schema({
},
userId: {
type: String,
- ref: 'User'
+ ref: 'UserGPS'
},
})
diff --git a/server/models/GPS.User.js b/server/models/GPS.User.js
new file mode 100644
index 0000000..8e0c743
--- /dev/null
+++ b/server/models/GPS.User.js
@@ -0,0 +1,57 @@
+const mongoose = require('mongoose')
+
+const BankSchema = mongoose.Schema({
+ holderName: String,
+ PAN: {
+ type: Number,
+ },
+ IBAN: {
+ type: String,
+ }
+})
+
+
+const UserSchema = mongoose.Schema({
+ first_name: String,
+ last_name: String,
+ national_code: String,
+ province_name: String,
+ city_name: String,
+ address: String,
+ mobile_number: String,
+ cell_number:String,
+ password: String,
+ profilePic: {
+ type: String,
+ default: "noPic"
+ },
+ shopName: String,
+ birthDate: String,
+ walletBalance: {
+ type: Number,
+ min: 0,
+ default: 0
+ },
+ dollarBalance: {
+ type: Number,
+ min: 0,
+ default: 0
+ },
+ score: {
+ type: Number,
+ min: 0,
+ default: 0
+ },
+ cardBank: [BankSchema],
+ active:{ type: Boolean, default: false },
+
+
+ /// //////////////////////////////// user confirmations
+ seenByAdmin: { type: Boolean, default: false },
+
+ /// /////////////
+ token: String,
+ otp:String
+})
+
+module.exports = mongoose.model('UserGPS', UserSchema)
diff --git a/server/models/GPS.Withdraw.js b/server/models/GPS.Withdraw.js
index 3c13415..3b02048 100644
--- a/server/models/GPS.Withdraw.js
+++ b/server/models/GPS.Withdraw.js
@@ -24,7 +24,7 @@ const WithdrawSchema = mongoose.Schema({
},
userId: {
type: String,
- ref: 'User'
+ ref: 'UserGPS'
},
status: {
type: Number,
diff --git a/server/models/User.js b/server/models/User.js
index a398b0a..486eddb 100644
--- a/server/models/User.js
+++ b/server/models/User.js
@@ -1,15 +1,5 @@
const mongoose = require('mongoose')
-const BankSchema = mongoose.Schema({
- holderName:String,
- PAN:{
- type:Number,
- },
- IBAN:{
- type:String,
- }
-})
-
const UserSchema = mongoose.Schema({
// for admins
@@ -54,31 +44,6 @@ const UserSchema = mongoose.Schema({
last_name: String,
password: String,
- // for GPS
- profilePic:{
- type:String,
- default:"noPic"
- },
- shopName:String,
- shopNumber:String,
- shopAddress:String,
- birthDate:String,
- walletBalance:{
- type:Number,
- min:0,
- default:0
- },
- dollarBalance:{
- type:Number,
- min:0,
- default:0
- },
- score:{
- type:Number,
- min:0,
- default:0
- },
- cardBank:[BankSchema],
/// //////////////////////////////// user confirmations
diff --git a/server/plugins/asanServiceSerialChecker.js b/server/plugins/asanServiceSerialChecker.js
index 0ba4f73..396fcbd 100644
--- a/server/plugins/asanServiceSerialChecker.js
+++ b/server/plugins/asanServiceSerialChecker.js
@@ -9,13 +9,10 @@ const serialChecker = (serial, type = 'guaranteeSerial', g = 1) => {
if (type === 'guaranteeSerial') exelsPath = guaranteeSerialsPath + `/${g}`;
if (type === 'orginality') exelsPath = productSerialsPath + `/${g}`;
- const newTxt = serial.toLowerCase().split("-")
- let lowerSerial = ""
- for(const item of newTxt){
-
- lowerSerial += item
-
- }
+console.log("s");
+
+ const lowerSerial = serial.toString().toLowerCase().trim().replace("-","")
+
try {
const serialFiles = await fs.readdirSync(exelsPath);
if ((serialFiles?.length) <= 0) {
@@ -23,20 +20,24 @@ const serialChecker = (serial, type = 'guaranteeSerial', g = 1) => {
reject("این کد در سامانه موجود نیست")
}
serialFiles.forEach(async (file, i) => {
- const exelFile = await readXlsxFile(`${exelsPath}/${file}`);
+ if(file.split('.').some(item => ['xlsx', 'xltx', 'xlsm', 'xlsb'].includes(item))){
+ const exelFile = await readXlsxFile(`${exelsPath}/${file}`);
+console.log(file);
- for (const row of exelFile) {
-
- // eslint-disable-next-line eqeqeq
- if ((row[1].toString()).toLowerCase() == lowerSerial) {
- resolve(row[2]);
- return; // Serial found, exit loop
- }
-
- }
- if ((serialFiles.length - 1) <= i) {
- // eslint-disable-next-line prefer-promise-reject-errors
- reject("این کد در سامانه موجود نیست")
+ for (const row of exelFile) {
+ console.log(row);
+
+ // eslint-disable-next-line eqeqeq
+ if ((row[1].toString()).toLowerCase().trim() == lowerSerial) {
+ resolve(row[2]);
+ return; // Serial found, exit loop
+ }
+
+ }
+ if ((serialFiles.length - 1) <= i) {
+ // eslint-disable-next-line prefer-promise-reject-errors
+ reject("این کد در سامانه موجود نیست")
+ }
}
})
diff --git a/server/routes/admin.js b/server/routes/admin.js
index 0ae205b..ebed870 100644
--- a/server/routes/admin.js
+++ b/server/routes/admin.js
@@ -26,12 +26,12 @@ const smsBroadcastController = require('../controllers/smsBroadcastController')
const surveyController = require('../controllers/surveyController')
const complaintController = require('../controllers/complaintController')
const brandController = require('../controllers/brandController')
-const requestController = require('../controllers/GPS.Request')
const withdraw = require('../controllers/GPS.Withdraw')
const installedDevice = require('../controllers/GPS.InstalledDevice')
const device = require('../controllers/GPS.Device')
const award = require('../controllers/GPS.Award')
const awardRequest = require('../controllers/GPS.AwardRequest')
+const userGPS = require('../controllers/GPS.User')
/// //////////////////////////////////////////////////////// routes
@@ -39,6 +39,15 @@ const awardRequest = require('../controllers/GPS.AwardRequest')
/// ///////////////////////////// GPS
+/// /////////////// User
+
+router.get('/gps/users',hasPermission('gps'), userGPS.getUsersForAdmin)
+router.get('/gps/users/:id',hasPermission('gps'), userGPS.getUserForAdmin)
+
+router.patch('/gps/users/:id/:status',hasPermission('gps'), userGPS.activeUser)
+
+
+
/// ////////////// Award
router.post('/gps/award',hasPermission('gps'), award.createAward)
router.get('/gps/award',hasPermission('gps'), award.findAllAdmin)
@@ -50,11 +59,6 @@ router.get('/gps/award-request',hasPermission('gps'), awardRequest.findAllAdmin)
router.get('/gps/award-request/:id',hasPermission('gps'), awardRequest.findOne)
router.put('/gps/award-request/:id',hasPermission('gps'), awardRequest.update)
-/// ////////////// request for access to gps
-router.get('/gps/request',hasPermission('gps'), requestController.getAllRequest)
-router.get('/gps/request/:id',hasPermission('gps'), requestController.getOneRequest)
-router.patch('/gps/request/:id/:status',hasPermission('gps'), requestController.changeStatus)
-
/// ////////////// Withdraw
router.get('/gps/withdraw',hasPermission('gps'), withdraw.getAllForAdmin)
router.patch('/gps/withdraw/:id/:type',hasPermission('gps'), withdraw.updateReq)
diff --git a/server/routes/auth.js b/server/routes/auth.js
index 83c1eb5..4c2c221 100644
--- a/server/routes/auth.js
+++ b/server/routes/auth.js
@@ -1,16 +1,21 @@
const { Router } = require('express')
const router = Router()
const userController = require('../controllers/userController')
-const gpsAuthController = require('../controllers/GPS.Auth')
+const userAuthGPS = require('../controllers/GPS.Auth')
+const userGPS = require('../controllers/GPS.User')
+/// //////////////////GPS section
+router.post('/gps/register', userGPS.register_user)
-/// /////////////////// gps routes
-router.post('/gps/login', gpsAuthController.login)
+router.post('/gps/login/pass', userAuthGPS.login_with_pass)
+router.post('/gps/login/otp', userAuthGPS.login_with_otp)
+router.post('/gps/otp/send', userGPS.send_otp)
+router.post('/gps/otp/check', userGPS.check_otp)
-/// ///////////////////
-// router.post('/register/admin', userController.register_admin)
+router.post('/gps/otp/reset-pass', userGPS.resetpass_otp)
+
+/// ////////////////////////
router.post('/register/user', userController.register_user)
-// router.post('/activation/:key', userController.activation)
router.post('/reset-pass-token', userController.generate_reset_user_password_link)
router.post('/set-new-pass', userController.reset_password_using_token)
diff --git a/server/routes/gps.js b/server/routes/gps.js
index 47dbe98..62dcf76 100644
--- a/server/routes/gps.js
+++ b/server/routes/gps.js
@@ -7,6 +7,13 @@ const score = require('../controllers/GPS.Score')
const award = require('../controllers/GPS.Award')
const awardRequest = require('../controllers/GPS.AwardRequest')
const overview = require('../controllers/GPS.Overview')
+const userGPS = require('../controllers/GPS.User')
+
+/// /////////////// User
+router.get('/user/me', userGPS.getCurrent)
+router.put('/user/me', userGPS.update_user)
+
+router.post('/user/reset-pass', userGPS.update_user_password)
/// /////////////// Overview page
router.get('/overview/main', overview.mainPage)
diff --git a/server/routes/user.js b/server/routes/user.js
index 663ee7c..54fed88 100644
--- a/server/routes/user.js
+++ b/server/routes/user.js
@@ -6,10 +6,8 @@ const representationController = require('../controllers/representationControlle
const transactionDraftsController = require('../controllers/transactionDraftsController')
const transactionController = require('../controllers/transactionController')
const surveyController = require('../controllers/surveyController')
-const requestController = require('../controllers/GPS.Request')
-/// // GPS
-router.post('/gps/request', requestController.gpsRequest)
+
/// // profile
router.put('/update_profile', userController.update_user)
|