add pagination and fix bug

This commit is contained in:
Mr Swift
2024-08-07 15:42:53 +03:30
parent 13f991eab2
commit db6c8d6681
13 changed files with 322 additions and 156 deletions
+10 -10
View File
@@ -13,22 +13,22 @@ module.exports.addCard = [
async (req, res) => { async (req, res) => {
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, holderName,
PAN, PAN,
IBAN IBAN
}]; }];
userData.save() userData.save()
res.status(201).json({msg: 'با موفقیت ثبت شد '}) res.status(201).json({ msg: 'با موفقیت ثبت شد ' })
} }
} }
] ]
@@ -50,8 +50,8 @@ module.exports.deleteCard = [
async (req, res) => { async (req, res) => {
const userData = await User.findOneAndUpdate( const userData = await User.findOneAndUpdate(
{ {
_id:req.user_id, _id: req.user_id,
"cardBank._id":req.params.id "cardBank._id": req.params.id
}, },
{ {
$pull: { $pull: {
@@ -59,6 +59,6 @@ module.exports.deleteCard = [
} }
} }
).select('id cardBank') ).select('id cardBank')
res.status(200).json({msg: "با موفقیت حذف شد ", data:userData}) res.status(200).json({ msg: "با موفقیت حذف شد ", data: userData })
} }
] ]
+44 -27
View File
@@ -38,8 +38,8 @@ module.exports.importExel = async (req, res) => {
const file = req.files.file const file = req.files.file
const exelFile = await readXlsxFile(Buffer.from(file.data)); const exelFile = await readXlsxFile(Buffer.from(file.data));
const data = await creator(exelFile) const data = await creator(exelFile)
res.status(201).json({ msg: _sr.fa.response.success_save, data }) res.status(201).json({ msg: _sr.fa.response.success_save, data })
} catch (error) { } catch (error) {
@@ -51,8 +51,25 @@ module.exports.importExel = async (req, res) => {
module.exports.getAll = [ module.exports.getAll = [
async (req, res) => { async (req, res) => {
const data = await Device.find().sort({ created_at: -1 }) let page;
res.status(200).json(data) 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 Device.find().sort({ created_at: -1 }).skip(page).limit(rows);
const total = Math.ceil((await Device.estimatedDocumentCount()))
res.status(200).json({ data, total })
} }
] ]
@@ -107,31 +124,31 @@ module.exports.updateDevice = [
] ]
const creator = (exel)=>{ const creator = (exel) => {
return new Promise (async(resolve, reject)=>{ return new Promise(async (resolve, reject) => {
for (const row of exel) { for (const row of exel) {
// eslint-disable-next-line no-constant-condition // eslint-disable-next-line no-constant-condition
if (validator.isIMEI(row[0].toString().trim() )|| true) { if (validator.isIMEI(row[0].toString().trim()) || true) {
const device = await Device.findOne({ IMEI: row[0] }) const device = await Device.findOne({ IMEI: row[0] })
if (device) { if (device) {
console.warn("Repeated IMEI ", row[0]) console.warn("Repeated IMEI ", row[0])
} else {
await Device.create(
{
IMEI: row[0],
model: row[1],
tomanPrice: row[2],
dollarProfit: row[3] || 1,
profit: row[4] || 1,
score: row[5] || 1,
renewalProfit: row[6] || 1
}
)
}
} else { } else {
await Device.create( console.warn("Wrong IMEI ", row[0])
{
IMEI: row[0],
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")
resolve("end")
}) })
} }
+60 -18
View File
@@ -4,6 +4,7 @@ const { checkValidations } = require('../plugins/controllersHelperFunctions');
const User = require('../models/User'); const User = require('../models/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');
module.exports.deviceRegistration = [ module.exports.deviceRegistration = [
[ [
@@ -11,38 +12,74 @@ module.exports.deviceRegistration = [
], ],
checkValidations(validationResult), checkValidations(validationResult),
async (req, res) => { async (req, res) => {
const device = await Device.find({IMEI:req.body.IMEI}); const device = await Device.find({ IMEI: req.body.IMEI });
if(!device){ if (!device) {
throw res.status(404).json({msg:'این IMEI وجود ندارد'}) throw res.status(404).json({ msg: 'این IMEI وجود ندارد' })
// eslint-disable-next-line eqeqeq // eslint-disable-next-line eqeqeq
}else if(device.status == 1){ } else if (device.status == 1) {
throw res.status(404).json({msg:'این IMEI قبلا ثبت شده'}) throw res.status(404).json({ msg: 'این IMEI قبلا ثبت شده' })
}else{ } else {
const data = { const data = {
deviceId: device.id, deviceId: device.id,
status:0, status: 0,
registerDate:new Date(), registerDate: new Date(),
userId:req.user_id userId: req.user_id
} }
const newRequest = await InstalledDevice.create(data); const newRequest = await InstalledDevice.create(data);
device.status = 1; device.status = 1;
device.save() device.save()
res.status(201).json({msg:_sr.fa.response.success_save, data:newRequest}) res.status(201).json({ msg: _sr.fa.response.success_save, data: newRequest })
} }
} }
] ]
module.exports.getAllForUser = async(req, res)=>{ module.exports.getAllForUser = async (req, res) => {
const data = await InstalledDevice.find({userId:req.user_id}).sort({created_at: -1}).populate('deviceId') let page;
res.status(200).json(data) 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 InstalledDevice.find({ userId: req.user_id }).sort({ created_at: -1 }).populate('deviceId').skip(page).limit(rows);
const total = Math.ceil((await InstalledDevice.countDocuments({ userId: req.user_id })))
res.status(200).json({ data, total })
} }
module.exports.getAllForAdmin = async(req, res)=>{ module.exports.getAllForAdmin = async (req, res) => {
const data = await InstalledDevice.find({}).sort({status: 1}).populate('deviceId').populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic') let page;
res.status(200).json(data) 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 InstalledDevice.find({}).sort({ status: 1 }).skip(page).limit(rows)
.populate('deviceId')
.populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic')
const total = Math.ceil((await InstalledDevice.estimatedDocumentCount()))
res.status(200).json({ data, total })
} }
@@ -56,7 +93,7 @@ module.exports.updateInstalled = [
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) const user = await User.findById(installedDevice.userID)
const device = await Device.findById(installedDevice.deviceId) const device = await Device.findById(installedDevice.deviceId)
@@ -71,6 +108,11 @@ module.exports.updateInstalled = [
user.dollarBalance += device.dollarProfit user.dollarBalance += device.dollarProfit
user.score += device.score user.score += device.score
user.save() user.save()
await Score.create({
deviceId: device.id,
score: device.score,
userId: installedDevice.userID
})
res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice }) res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice })
break; break;
} }
+20 -2
View File
@@ -35,8 +35,26 @@ module.exports.gpsRequest = [
module.exports.getAllRequest = [ module.exports.getAllRequest = [
async (req, res) => { async (req, res) => {
const data = await RequestGPS.find({}).sort({ status: 1 }).populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic') let page;
res.status(200).json(data) 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 })
} }
] ]
+32
View File
@@ -0,0 +1,32 @@
// const { body, param, validationResult } = require('express-validator')
// const { _sr } = require('../plugins/serverResponses')
// const { checkValidations } = require('../plugins/controllersHelperFunctions')
const Score = require('../models/GPS.Score')
const User = require('../models/User')
module.exports.getAll = 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 score = await Score.find({ userId: req.user_id }).skip(page).limit(rows);
const total = Math.ceil((await score.estimatedDocumentCount()))
const user = await User.findById(req.user_id).select('score')
res.status(200).json({ data: score, score: user.score, total })
}
+39 -8
View File
@@ -30,17 +30,48 @@ module.exports.createRequest = [
module.exports.getAllForUser = async (req, res) => { module.exports.getAllForUser = async (req, res) => {
let page;
const requests = await Withdraw.find({ userId: req.user_id }).sort({ created_at: -1 }) let rows;
if (!req.query?.rows) {
res.status(201).json(requests) 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 Withdraw.find({ userId: req.user_id }).sort({ created_at: -1 }).skip(page).limit(rows);
const total = Math.ceil((await Withdraw.countDocuments({ userId: req.user_id })))
res.status(201).json({ data, total })
} }
module.exports.getAllForAdmin = async (req, res) => { module.exports.getAllForAdmin = async (req, res) => {
let page;
const requests = await Withdraw.find().sort({ status: 1 }).populate('userId', 'shopName shopNumber shopAddress birthDate score first_name last_name profilePic') let rows;
if (!req.query?.rows) {
res.status(201).json(requests) 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 Withdraw.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 Withdraw.estimatedDocumentCount()))
res.status(201).json({ data, total })
} }
+26 -26
View File
@@ -1,41 +1,41 @@
const mongoose = require('mongoose') const mongoose = require('mongoose')
const deviceSchema = mongoose.Schema({ const deviceSchema = mongoose.Schema({
model:String, model: String,
IMEI:{ IMEI: {
type:String, type: String,
unique:[true,"این ایدی در سامانه موجود است"] unique: [true, "این ایدی در سامانه موجود است"]
}, },
tomanPrice:{ tomanPrice: {
type:Number, type: Number,
min:0, min: 0,
default:0 default: 0
}, },
dollarProfit:{ dollarProfit: {
type:Number, type: Number,
min:0, min: 0,
default:0 default: 0
}, },
profit:{ profit: {
type:Number, type: Number,
min:0, min: 0,
default:0 default: 0
}, },
score:{ score: {
type:Number, type: Number,
min:0 min: 0
}, },
renewalProfit:{ renewalProfit: {
type:Number, type: Number,
min:0 min: 0
}, },
status:{ status: {
type:Number, type: Number,
enum:[ enum: [
0, // not installed 0, // not installed
1 // installed 1 // installed
], ],
default:0 default: 0
} }
}) })
+12 -12
View File
@@ -1,24 +1,24 @@
const mongoose = require('mongoose') const mongoose = require('mongoose')
const InstalledDeviceSchema = mongoose.Schema({ const InstalledDeviceSchema = mongoose.Schema({
deviceId:{ deviceId: {
type:String, type: String,
ref:"Device" ref: "Device"
}, },
status:{ status: {
type:Number, type: Number,
enum:[ enum: [
0, // Pending 0, // Pending
1, // Accepted 1, // Accepted
2, // Rejected 2, // Rejected
], ],
default:0 default: 0
}, },
registerDate:Date, registerDate: Date,
installationDate:Date, installationDate: Date,
userId:{ userId: {
type:String, type: String,
ref:'User' ref: 'User'
}, },
}) })
+22 -18
View File
@@ -1,28 +1,32 @@
const mongoose = require('mongoose') const mongoose = require('mongoose')
const RenewalSchema = mongoose.Schema({ const RenewalSchema = mongoose.Schema({
deviceId:{ deviceId: {
type:String, type: String,
ref:'Device' ref: 'Device'
}, },
renewDate:Date, renewDate: Date,
renewType:{ renewType: {
type:String, type: String,
}, },
price:{ price: {
type:Number, type: Number,
min:0 min: 0
}, },
profit:{ profit: {
type:Number, type: Number,
min:0, min: 0,
unique:true, unique: true,
default:0, default: 0,
required:true required: true
}, },
dollarProfit:{ dollarProfit: {
type:Number, type: Number,
min:0 min: 0
},
userId: {
type: String,
ref: 'User'
}, },
}) })
+11 -11
View File
@@ -1,22 +1,22 @@
const mongoose = require('mongoose') const mongoose = require('mongoose')
const RequestSchema = mongoose.Schema({ const RequestSchema = mongoose.Schema({
userId:{ userId: {
type:String, type: String,
ref:'User' ref: 'User'
}, },
shopName:String, shopName: String,
shopNumber:String, shopNumber: String,
shopAddress:String, shopAddress: String,
birthDate:String, birthDate: String,
status:{ status: {
type:Number, type: Number,
enum:[ enum: [
0, // Pending 0, // Pending
1, // Accepted 1, // Accepted
2 // Rejected 2 // Rejected
], ],
default:0 default: 0
} }
}) })
+18
View File
@@ -0,0 +1,18 @@
const mongoose = require('mongoose')
const ScoreSchema = mongoose.Schema({
deviceId: {
type: String,
ref: 'Device'
},
score: {
type: Number,
min: 0
},
userId: {
type: String,
ref: 'User'
},
})
module.exports = mongoose.model('Score', ScoreSchema)
+21 -21
View File
@@ -2,40 +2,40 @@ const mongoose = require('mongoose')
const BankSchema = mongoose.Schema({ const BankSchema = mongoose.Schema({
holderName:String, holderName: String,
PAN:{ PAN: {
type:Number, type: Number,
}, },
IBAN:{ IBAN: {
type:Number, type: Number,
} }
}) })
/// ///////////////////////////////////////////////////// /// /////////////////////////////////////////////////////
const WithdrawSchema = mongoose.Schema({ const WithdrawSchema = mongoose.Schema({
card:BankSchema, card: BankSchema,
amount:{ amount: {
type:Number, type: Number,
min:0 min: 0
}, },
dollarAmount:{ dollarAmount: {
type:Number, type: Number,
min:0 min: 0
}, },
userId:{ userId: {
type:String, type: String,
ref:'User' ref: 'User'
}, },
status:{ status: {
type:Number, type: Number,
enum:[ enum: [
0, // Pending 0, // Pending
1, // Accepted 1, // Accepted
2, // deposited 2, // deposited
] ]
}, },
depositDate:Date, depositDate: Date,
trackingNumber:String trackingNumber: String
}) })
module.exports = mongoose.model('Withdraw', WithdrawSchema) module.exports = mongoose.model('Withdraw', WithdrawSchema)
+4
View File
@@ -3,6 +3,7 @@ const router = Router()
const bankAccount = require('../controllers/GPS.BankAccount') const bankAccount = require('../controllers/GPS.BankAccount')
const withdraw = require('../controllers/GPS.Withdraw') const withdraw = require('../controllers/GPS.Withdraw')
const installedDevice = require('../controllers/GPS.InstalledDevice') const installedDevice = require('../controllers/GPS.InstalledDevice')
const score = require('../controllers/GPS.Score')
/// ///////////////// Bank card /// ///////////////// Bank card
router.post('/bank-card', bankAccount.addCard) router.post('/bank-card', bankAccount.addCard)
@@ -16,4 +17,7 @@ router.get('/withdraw', withdraw.getAllForUser)
router.post('/register-device', installedDevice.deviceRegistration) router.post('/register-device', installedDevice.deviceRegistration)
router.get('/register-device', installedDevice.getAllForUser) router.get('/register-device', installedDevice.getAllForUser)
/// ///////////////// Score
router.get('/score', score.getAll)
module.exports = router module.exports = router