admin/controllers/user/index.js

/* ============================================================================ *\
|| ########################################################################## ||
|| # Auction Software Marketplace          Release: 0.6   Build 0.7         # ||
|| # ---------------------------------------------------------------------- # ||
|| # License # 35YAHCNR9344X6O666C123AB                                     # ||
|| # ---------------------------------------------------------------------- # ||
|| # Copyright ©2014–2021 Develop Scripts LLC. All Rights Reserved          # ||
|| # This file may not be redistributed in whole or significant part.       # ||
|| # ------------- AUCTION SOFTWARE IS NOT FREE SOFTWARE ------------------ # ||
|| # http://www.auctionsoftwaremarketplace.com|support@auctionsoftware.com  # ||
|| # ---------------------------------------------------------------------- # ||
|| ########################################################################## ||
\* ============================================================================ */

/* eslint-disable prefer-destructuring */
/* eslint-disable no-param-reassign */
const jwt = require('jsonwebtoken')
const adminUserModule = require('../../modules/user').default
const schemaModule = require('./schema').default
const commonFunction = require('../../../common/function').default

const { jsonResponse, errorResponse } = require('../logger')

module.exports = {
    /**
     * Get All Users
     *
     * @memberOf adminside.user
     * @param {adminUserModule.fetchBuyersAll} modules
     */
    allbuyers: async (req, res) => {
        req.body.action = typeof req.body.action === 'undefined' ? 'open' : req.body.action
        let records = []
        let totalRecords = []
        let activelots = []
        try {
            ;[records, totalRecords, activelots] = await Promise.all([
                adminUserModule.fetchBuyersAll(req, 0),
                adminUserModule.fetchBuyersAll(req, 1),
            ])
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            let responseData = { records, totalRecords, activelots }
            responseData = await commonFunction.getdynamicinnercontents(req, responseData)
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        }
    },
    /**
     * Get Singer User
     *
     * @memberOf adminside.user
     * @param {adminUserModule.fetchUsersbyID} modules
     */
    getSingleUser: async (req, res) => {
        let record = {}
        try {
            const id = typeof req.body.id === 'undefined' ? '' : req.body.id
            const [records] = await Promise.all([adminUserModule.fetchUsersbyID(id)])
            record = records[0]
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = { record }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        }
    },
    /**
     * User Action
     *
     * @memberOf adminside.user
     * @param {adminUserModule.checkEmailExisting} modules
     * @param {adminUserModule.userOperation} modules
     * @param {adminUserModule.manualInsertUsernotify} modules
     */
    userAction: async (req, res) => {
        try {
            req.body.id =
                typeof req.body.id === 'undefined' || req.body.id === 0 || req.body.id === ''
                    ? null
                    : req.body.id
            req.body.email = req.body.email.toLowerCase()
            req.body.emailexists = false
            if (req.body.id) {
                const resultuser = await Promise.all([
                    adminUserModule.checkEmailExisting(req.body.email),
                ])
                if (resultuser[0].length > 0) {
                    if (
                        resultuser[0][0].id === req.body.id &&
                        resultuser[0][0].email === req.body.email
                    ) {
                        await Promise.all([adminUserModule.userOperation(req)])
                    } else {
                        req.body.emailexists = true
                    }
                } else {
                    await Promise.all([adminUserModule.userOperation(req)])
                }
            } else {
                const resultuser = await Promise.all([
                    adminUserModule.checkEmailExisting(req.body.email),
                ])
                if (resultuser[0].length > 0) {
                    req.body.emailexists = true
                } else {
                    req.body.password = Math.random().toString(36).slice(2)
                    const usermail = req.body.email.toLowerCase()
                    const firstname = req.body.first_name
                    const lastname = req.body.last_name

                    const results = await Promise.all([
                        adminUserModule.userOperation(req),
                        commonFunction.mailtemps('buyer_register_admin'),
                    ])
                    await Promise.all([adminUserModule.manualInsertUsernotify(results[0].insertId)])
                    if (results[1].length > 0) {
                        let template = results[1][0].template
                        const subjectMessage = results[1][0].subject
                        template = template.replace(/{{event.siteurl}}/g, global.url)
                        template = template.replace(/{{event.sitename}}/g, 'www.GM.com')
                        template = template.replace('{{event.user}}', firstname)
                        template = template.replace('{{event.logoimgsrc}}', global.url)
                        template = template.replace('{{event.password}}', req.body.password)
                        // sendgrid.sendEmail(subjectMessage, usermail, template, 1);
                    }
                }
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            if (req.body.emailexists) {
                jsonResponse(res, 'error', {
                    responseType: 2,
                    message: 'Registration Failed! Email Already Exists.',
                })
            } else {
                const responseData = {}
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: req.body.id ? 'Successfully updated!' : 'Successfully registered!',
                    responseData,
                })
            }
        }
    },
    /**
     * Change status of the User
     *
     * @memberOf adminside.user
     * @param {adminUserModule.userStatusUpdate} modules
     */
    changeStatus: async (req, res) => {
        try {
            if (req.body.action && req.body.user_id.length > 0) {
                await adminUserModule.userStatusUpdate(req.body.action, req.body.user_id)
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = {}
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Status successfully changed',
                responseData,
            })
        }
    },
    /**
     * Add User
     *
     * @memberOf adminside.user
     * @param {adminUserModule.createuserlist} modules
     */
    userAdd: async (req, res) => {
        try {
            const userlist = await Promise.all([
                adminUserModule.createuserlist(req, req.body, global.configColumns.users),
            ])
            if (global.configColumns.custom_users.enabled) {
                req.body.user_id = userlist[0].insertId
                await Promise.all([
                    adminUserModule.createuserlist(
                        req,
                        req.body,
                        global.configColumns.custom_users,
                    ),
                ])
            }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
            })
        } catch (e) {
            errorResponse(e, res)
        }
    },
    /**
     * Add Update
     *
     * @memberOf adminside.user
     * @param {adminUserModule.updatealltypeofproduct} modules
     * @param {adminUserModule.updatealltypeofuser} modules
     */
    userUpdate: async (req, res) => {
        try {
            await Promise.all([
                adminUserModule.updatealltypeofproduct(
                    req,
                    req.body,
                    req.body.id,
                    'id',
                    global.configColumns.users,
                ),
            ])

            if (global.configColumns.custom_users.enabled) {
                await Promise.all([
                    adminUserModule.updatealltypeofuser(
                        req,
                        req.body,
                        req.body.id,
                        'user_id',
                        global.configColumns.custom_users,
                    ),
                ])
            }

            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
            })
        } catch (e) {
            errorResponse(e, res)
        }
    },
    /**
     * List all Users
     *
     * @memberOf adminside.user
     * @param {adminUserModule.commonselectparenttable} modules
     */
    userListing: async (req, res) => {
        try {
            const usersobj = {}
            const [baseuserlist] = await Promise.all([
                adminUserModule.commonselectparenttable(
                    '*',
                    'id',
                    req.body.id,
                    global.configColumns.users,
                ),
            ])
            usersobj.user_list = baseuserlist
            if (global.configColumns.custom_users.enabled) {
                const [baseuserlistcus] = await Promise.all([
                    adminUserModule.commonselectparenttable(
                        '*',
                        'user_id',
                        req.body.id,
                        global.configColumns.custom_users,
                    ),
                ])
                usersobj.usercus_list = baseuserlistcus
            }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                usersobj,
            })
        } catch (e) {
            errorResponse(e, res)
        }
    },
}