const { body, param, validationResult } = require('express-validator'); const { _sr } = require('../plugins/serverResponses'); const { checkValidations } = require('../plugins/controllersHelperFunctions'); const User = require('../models/User'); const InstalledDevice = require('../models/GPS.InstalledDevice'); const Device = require('../models/GPS.Device'); /** * get all installed device for user * get all installed device for admin * patch a installed device by id and type */ module.exports.deviceRegistration = [ [ body('IMEI').notEmpty().isString().withMessage('لطفا IMEI را وارد یا تصحیح کنید') ], checkValidations(validationResult), async (req, res) => { const device = await Device.find({IMEI:req.body.IMEI}); if(!device){ throw res.status(404).json({msg:'این IMEI وجود ندارد'}) // eslint-disable-next-line eqeqeq }else if(device.status == 1){ throw res.status(404).json({msg:'این IMEI قبلا ثبت شده'}) }else{ const data = { deviceId: device.id, status:0, registerDate:new Date(), userId:req.user_id } const newRequest = await InstalledDevice.create(data); device.status = 1; device.save() res.status(201).json({msg:_sr.fa.response.success_save, data:newRequest}) } } ] module.exports.getAllForUser = async(req, res)=>{ const data = await InstalledDevice.find({userId:req.user_id}).sort({created_at: -1}).populate('deviceId') res.status(200).json(data) } 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') res.status(200).json(data) } module.exports.updateInstalled = [ [ param('id').notEmpty().isMongoId().withMessage('لطفا ایدی را وارد یا تصحیح کنید'), param('type').notEmpty().isString().withMessage('لطفا وضعیت را وارد یا تصحیح کنید'), ], checkValidations(validationResult), async (req, res) => { const installedDevice = await InstalledDevice.findById(req.params.id) if (!installedDevice) { throw res.status(404).json({msg:'این ایدی وجود ندارد'}) } else { const user = await User.findById(installedDevice.userID) const device = await Device.findById(installedDevice.deviceId) switch (req.params.type) { case "accept": { installedDevice.status = 1; installedDevice.installationDate = new Date(); installedDevice.save() device.status = 1; device.save() user.walletBalance += device.profit user.dollarBalance += device.dollarPrice user.score += device.score user.save() res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice }) break; } case "reject": { installedDevice.status = 2; installedDevice.save() device.status = 0; device.save() res.status(201).json({ msg: _sr.fa.response.success_save, data: installedDevice }) break; } default: { res.status(404).json({ msg: "استاتوس اشتباه است" }) break; } } } } ]