291 lines
8.6 KiB
JavaScript
291 lines
8.6 KiB
JavaScript
const { body, param, validationResult } = require('express-validator')
|
|
const { _sr } = require('../plugins/serverResponses')
|
|
const { checkValidations } = require('../plugins/controllersHelperFunctions')
|
|
const User = require('../models/GPS.User')
|
|
const Withdraw = require('../models/GPS.Withdraw')
|
|
const { notifyAdmin } = require('../WebSocket/controllers/admin_EventsController')
|
|
|
|
module.exports.createRequest = [
|
|
[
|
|
body('card').notEmpty().isObject().withMessage('گارت ورودی خود را انتخاب کنید'),
|
|
body('amount').notEmpty().isNumeric().withMessage('مقدار را وارد کنید')
|
|
],
|
|
checkValidations(validationResult),
|
|
async (req, res) => {
|
|
try {
|
|
const withdraw = await Withdraw.findOne({ userId: req.user_id, status: 0 })
|
|
if (withdraw) {
|
|
res.status(400).json({ msg: 'شما درخواست درحال بررسی دارید' })
|
|
} else {
|
|
const user = await User.findById(req.user_id)
|
|
if (!user) {
|
|
return res.status(400).json({ msg: 'کاربر یافت نشد' })
|
|
}
|
|
if (req.body.amount > user.walletBalance) {
|
|
return res.status(400).json({ msg: 'موجودی شما کافی نیست' })
|
|
}
|
|
if (user.walletBalance >= 50000) {
|
|
const data = {
|
|
card: req.body.card,
|
|
userId: req.user_id,
|
|
amount: req.body.amount,
|
|
// dollarAmount: user.dollarBalance,
|
|
status: 0
|
|
}
|
|
|
|
const request = await Withdraw.create(data)
|
|
// user.dollarBalance = 0
|
|
user.walletBalance -= req.body.amount
|
|
user.save()
|
|
// res.status(201).json({ msg: _sr.fa.response.success_save, data: request })
|
|
notifyAdmin('newWithdrawRequest')
|
|
res.status(201).json(request)
|
|
} else {
|
|
res.status(400).json({ msg: 'حداقل موجودی باید 50 هزار تومان باشد' })
|
|
}
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ msg: error })
|
|
}
|
|
}
|
|
]
|
|
|
|
module.exports.cancellRequest = async (req, res) => {
|
|
try {
|
|
// Find the latest request with status 0 for the current user
|
|
const withdraw = await Withdraw.findOne({ userId: req.user_id, status: 0 })
|
|
.sort({ _id: -1 }) // Get the latest one
|
|
|
|
if (!withdraw) {
|
|
return res.status(404).json({ msg: 'درخواست در حال بررسی یافت نشد' })
|
|
}
|
|
|
|
// Restore the wallet balance
|
|
const user = await User.findById(req.user_id)
|
|
if (user) {
|
|
user.walletBalance += withdraw.amount
|
|
await user.save()
|
|
}
|
|
|
|
// Delete the request
|
|
await Withdraw.findByIdAndDelete(withdraw._id)
|
|
|
|
res.status(200).json({ msg: 'درخواست با موفقیت لغو شد' })
|
|
} catch (error) {
|
|
res.status(500).json({ msg: error.message || error })
|
|
}
|
|
}
|
|
|
|
module.exports.getAllForUser = async (req, res) => {
|
|
const rows = !req.query?.rows || req.query?.rows <= 5 ? 10 : parseInt(req.query.rows)
|
|
|
|
let page = 0
|
|
if (req.query?.page && req.query.page > 1) {
|
|
page = (req.query.page - 1) * rows
|
|
}
|
|
|
|
const search = req.query?.search || null
|
|
|
|
let sort = {}
|
|
|
|
if (req.query?.created_at) {
|
|
sort.created_at = parseInt(req.query.created_at)
|
|
}
|
|
|
|
if (req.query?.updated_at) {
|
|
sort.updated_at = parseInt(req.query.updated_at)
|
|
}
|
|
|
|
if (req.query?.amount) {
|
|
sort.amount = parseInt(req.query.amount)
|
|
}
|
|
|
|
if (req.query?.status) {
|
|
sort.status = parseInt(req.query.status)
|
|
}
|
|
|
|
if (Object.keys(sort).length === 0) {
|
|
sort = { created_at: 1 }
|
|
}
|
|
|
|
const filter = {
|
|
userId: req.user_id
|
|
}
|
|
|
|
if (search) {
|
|
filter.$or = [{ amount: search }, { trackingNumber: { $regex: search, $options: 'i' } }]
|
|
}
|
|
|
|
try {
|
|
const data = await Withdraw.find(filter).skip(page).limit(rows).sort(sort)
|
|
const total = await Withdraw.countDocuments(filter)
|
|
|
|
res.status(200).json({ data, total })
|
|
} catch (error) {
|
|
res.status(500).json({ message: 'خطای سرور', error })
|
|
}
|
|
}
|
|
|
|
module.exports.getAllForAdmin = async (req, res) => {
|
|
try {
|
|
const page = parseInt(req.query.page) || 1
|
|
const rows = parseInt(req.query.rows) || 10
|
|
const search = req.query.search || ''
|
|
const status = req.query.status !== undefined ? parseInt(req.query.status) : undefined
|
|
const sortField = req.query.sortField || 'status'
|
|
const sortOrder = req.query.sortOrder === 'desc' ? -1 : 1
|
|
const skip = (page - 1) * rows
|
|
|
|
// If search is provided, use aggregation to search in user fields
|
|
if (search) {
|
|
const matchStage = {}
|
|
|
|
if (status !== undefined) {
|
|
matchStage.status = status
|
|
}
|
|
|
|
// Build search conditions
|
|
const searchConditions = [
|
|
{ 'userId.mobile_number': new RegExp(search, 'i') },
|
|
{ 'userId.national_code': new RegExp(search, 'i') },
|
|
{ 'userId.first_name': new RegExp(search, 'i') },
|
|
{ 'userId.last_name': new RegExp(search, 'i') },
|
|
{ 'userId.shopName': new RegExp(search, 'i') },
|
|
{ trackingNumber: new RegExp(search, 'i') }
|
|
]
|
|
|
|
// Add amount search if search is a number
|
|
if (!isNaN(search) && search.trim() !== '') {
|
|
searchConditions.push({ amount: parseInt(search) })
|
|
}
|
|
|
|
const aggregationPipeline = [
|
|
{ $match: matchStage },
|
|
{
|
|
$lookup: {
|
|
from: 'usergps',
|
|
let: { userIdStr: '$userId' },
|
|
pipeline: [
|
|
{
|
|
$match: {
|
|
$expr: {
|
|
$eq: ['$_id', { $toObjectId: '$$userIdStr' }]
|
|
}
|
|
}
|
|
}
|
|
],
|
|
as: 'userId'
|
|
}
|
|
},
|
|
{ $unwind: { path: '$userId', preserveNullAndEmptyArrays: false } },
|
|
{
|
|
$match: {
|
|
$or: searchConditions
|
|
}
|
|
},
|
|
{ $sort: { [sortField]: sortOrder } },
|
|
{ $skip: skip },
|
|
{ $limit: rows }
|
|
]
|
|
|
|
const countPipeline = [
|
|
{ $match: matchStage },
|
|
{
|
|
$lookup: {
|
|
from: 'usergps',
|
|
let: { userIdStr: '$userId' },
|
|
pipeline: [
|
|
{
|
|
$match: {
|
|
$expr: {
|
|
$eq: ['$_id', { $toObjectId: '$$userIdStr' }]
|
|
}
|
|
}
|
|
}
|
|
],
|
|
as: 'userId'
|
|
}
|
|
},
|
|
{ $unwind: { path: '$userId', preserveNullAndEmptyArrays: false } },
|
|
{
|
|
$match: {
|
|
$or: searchConditions
|
|
}
|
|
},
|
|
{ $count: 'total' }
|
|
]
|
|
|
|
const [data, countResult] = await Promise.all([
|
|
Withdraw.aggregate(aggregationPipeline),
|
|
Withdraw.aggregate(countPipeline)
|
|
])
|
|
|
|
const totalDocuments = countResult[0]?.total || 0
|
|
const totalPages = Math.ceil(totalDocuments / rows)
|
|
|
|
res.status(200).json({ data, totalDocuments, totalPages })
|
|
} else {
|
|
// No search - use simple find with populate
|
|
const matchStage = {}
|
|
|
|
if (status !== undefined) {
|
|
matchStage.status = status
|
|
}
|
|
|
|
const data = await Withdraw.find(matchStage)
|
|
.sort({ [sortField]: sortOrder })
|
|
.skip(skip)
|
|
.limit(rows)
|
|
.populate('userId')
|
|
|
|
const totalDocuments = await Withdraw.countDocuments(matchStage)
|
|
const totalPages = Math.ceil(totalDocuments / rows)
|
|
|
|
res.status(200).json({ data, totalDocuments, totalPages })
|
|
}
|
|
} catch (error) {
|
|
res.status(500).json({ message: 'An error occurred, please try again.', error: error.message })
|
|
}
|
|
}
|
|
|
|
module.exports.updateReq = [
|
|
[
|
|
param('id').notEmpty().isMongoId().withMessage('ایدی را باید وارد کنید'),
|
|
param('type').notEmpty().isString().withMessage('وضعیت را باید وارد کنید')
|
|
],
|
|
checkValidations(validationResult),
|
|
async (req, res) => {
|
|
const request = await Withdraw.findById(req.params.id)
|
|
if (!request) {
|
|
res.status(404).json({ msg: _sr.fa.not_found.item_id })
|
|
} else {
|
|
switch (req.params.type) {
|
|
case 'accept': {
|
|
request.status = 1
|
|
request.save()
|
|
notifyAdmin('newWithdrawRequest')
|
|
|
|
res.status(201).json({ msg: _sr.fa.response.success_save, data: request })
|
|
|
|
break
|
|
}
|
|
case 'deposit': {
|
|
request.status = 2
|
|
request.depositDate = new Date()
|
|
request.trackingNumber = req.body.trackingNumber || 0
|
|
request.save()
|
|
notifyAdmin('newWithdrawRequest')
|
|
|
|
res.status(201).json({ msg: _sr.fa.response.success_save, data: request })
|
|
|
|
break
|
|
}
|
|
default: {
|
|
res.status(404).json({ msg: 'استاتوس اشتباه است' })
|
|
break
|
|
}
|
|
}
|
|
}
|
|
}
|
|
]
|