admin/modules/employee.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  # ||
|| # ---------------------------------------------------------------------- # ||
|| ########################################################################## ||
\* ============================================================================ */

const dateFormat = require('dateformat')
const md5 = require('md5')
const _ = require('underscore')
const moment = require('moment')
const commonSQL = require('../../common/sql').default
const mysqclass = require('./mysqli').default
const commonProduct = require('../../common/products').default

/**
 * @class class to handle communication functions
 */
class adminEmployeeModule {
    /**
     * Fetch all employees
     * @param {object} req request data
     * @param {string} count count for the pagination
     * @returns {object} sql response
     */
    static async fetchEmployeesAll(req, count) {
        const mysql = {}

        const baseTableUsed = global.configColumns.employees
        const customTableUsed = global.configColumns.custom_employees

        let row = ''
        let where = ''
        let limitf = ''
        let order = ''

        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        if (typeof req.body.limit === 'undefined') {
            req.body.limit = global.configurations.variables.search_limit || 25
        }
        if (typeof req.body.page === 'undefined') {
            req.body.page = 1
        }

        order = `order by e.id desc`
        if (req.body.orderby || req.body.order) {
            const sortReturn = commonProduct.sortOrderData(req, where)
            if (sortReturn.order) {
                order = sortReturn.order
            }
            if (sortReturn.where) {
                where += sortReturn.where
            }
        }

        if (req.user.emp_type === 'employee') {
            mysql.where += ` and emp_type = "employee" and id != ${req.user.id}`
        } else if (req.user.emp_type === 'admin') {
            mysql.where += ` and emp_type = "employee" and id != ${req.user.id}`
        } else if (req.user.emp_type === 'super_admin') {
            mysql.where += ` and ( emp_type = "employee" or emp_type = "admin" or emp_type = "super_admin" )`
        } else {
            mysql.where += ` and id = 0`
        }

        if (req.body.similars) {
            where += commonProduct.similarData(req)
        }
        if (req.body.filters) {
            where += commonProduct.filterData(req)
        }

        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.mainTableJoin = generatedData.mainTableJoin

        mysql.columns = generatedData.rowstoFetch

        const limitrg = req.body.limit
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }

        const escapeData = []
        if (count === 1) {
            let pagen = (req.body.page - 1) * limitrg
            if (parseInt(pagen, 10) < 0) {
                pagen = 0
            }
            limitf = ` limit ${pagen},${limitrg}`
        }

        if (count === 1) {
            row = 'get_all_employees_limit'
        } else {
            row = 'get_all_employees'
        }

        mysql.order = order
        mysql.where = where
        mysql.limitf = limitf
        mysql.dateNow = dateNow

        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Fetch single employee details
     * @param {number} pid Employee ID which details has to be fetched
     * @returns {object} sql response
     */
    static async fetchUsersbyID(pid) {
        const mysql = {}
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'get_single_user_employee')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Check email existing for the employee
     * @param {string} nameID Employee email which has to be checked
     * @returns {object} sql response
     */
    static async checkEmailExisting(nameID) {
        const mysql = {}
        const escapeData = [nameID]
        const strQuery = await mysqclass.mysqli(mysql, 'check_emp_email_exists')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }

    /**
     * Employee Action
     * @param {object} req request data
     * @returns {object} sql response
     */
    static async userOperation(req) {
        const mysql = {}
        const postData = req.body
        const acceptedObjects = [
            'emp_firstname',
            'emp_lastname',
            'emp_address1',
            'emp_status',
            'emp_email',
            'emp_type',
            'emp_permissions',
            'password_hash',
            'password_salt',
            'emp_phone',
            'emp_city',
            'emp_state',
            'emp_zip',
        ]
        let escapeData = []
        let row = ''
        if (req.body.id) {
            const defaultKeys = ['updated_at']
            const defaultValues = [dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')]
            const valueInsert = commonSQL.updateSQLFunction(
                postData,
                acceptedObjects,
                defaultKeys,
                defaultValues,
            )
            mysql.keys = valueInsert.keys
            escapeData = valueInsert.escapeData
            row = 'update_on_employee'
            mysql.user_id = req.body.id
        } else {
            req.body.password_salt = '12345'
            req.body.password_hash = md5(md5(req.body.password) + req.body.password_salt)
            const defaultKeys = ['created_at']
            const defaultValues = [dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')]
            const valueInsert = commonSQL.InsertSQLFunction(
                postData,
                acceptedObjects,
                defaultKeys,
                defaultValues,
            )
            mysql.keys = valueInsert.keys
            mysql.values = valueInsert.values
            escapeData = valueInsert.escapeData
            row = 'insert_into_employee'
        }
        const strQuery = await mysqclass.mysqli(mysql, row)
        const data = await global.mysql.query(strQuery, escapeData)

        return data
    }

    /**
     * Update status of the employee
     * @param {string} status status which has to be changed for the employee
     * @param {number} pid employee id which has to be updated
     * @returns {object} sql response
     */
    static async userStatusUpdate(status, pid) {
        const mysql = {}
        const escapeData = [status, pid]
        const strQuery = await mysqclass.mysqli(mysql, 'employee_change_status')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        console.log('dataReturn', strQuery, escapeData)
        return dataReturn
    }

    /**
     * Create a employee insert query
     * @param {object} req request data
     * @param {object} data request.body data
     * @param {string} baseTableUsed baseTable which the query has to be generated
     * @returns {object} sql response
     */
    static async createuserlist(req, data, baseTableUsed) {
        const mysqli = {}
        let escapeData = []
        const postData = data
        const acceptedObjects = baseTableUsed.array_columns
        const defaultKeys = ['created_at', 'updated_at']
        const defaultValues = [
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        ]
        const valueInsert = commonSQL.InsertSQLFunction(
            postData,
            acceptedObjects,
            defaultKeys,
            defaultValues,
        )
        mysqli.keys = valueInsert.keys
        escapeData = valueInsert.escapeData
        mysqli.values = valueInsert.values
        mysqli.tables = baseTableUsed.ext_name
        const strQuery = await mysqclass.mysqli(mysqli, 'insert_tables')
        const dataPromise = await global.mysql.query(strQuery, escapeData)
        return dataPromise
    }

    /**
     * Update query for the employees
     * @param {object} req request data
     * @param {object} data request.body data
     * @param {string} baseTableUsed baseTable which the query has to be generated
     * @returns {object} sql response
     */
    static async updatealltypeofuser(req, data, proid, typeoffield, baseTableUsed) {
        const mysqli = {}
        let escapeData = []
        const postData = data
        const postID = proid
        const fieldType = typeoffield
        const acceptedObjects = baseTableUsed.array_columns
        const defaultKeys = ['updated_at']
        const defaultValues = [dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')]
        const valueInsert = commonSQL.updateSQLFunction(
            postData,
            acceptedObjects,
            defaultKeys,
            defaultValues,
        )
        mysqli.keys = valueInsert.keys
        escapeData = valueInsert.escapeData
        mysqli.values = ` ${fieldType}=${postID}`
        mysqli.tables = baseTableUsed.ext_name
        const strQuery = await mysqclass.mysqli(mysqli, 'update_tables')
        const dataPromise = await global.mysql.query(strQuery, escapeData)
        return dataPromise
    }

    /**
     * Select query to fetch all employees
     * @param {object} data request.body data
     * @param {string} baseTableUsed baseTable which the query has to be generated
     * @returns {object} sql response
     */
    static async commonselectparenttable(data, proid, baseTableUsed, baseid) {
        const mysqli = {}
        const proId = proid.split(',')
        const escapeData = [proId]
        mysqli.keys = data
        mysqli.values = `${baseid} IN (?)`
        mysqli.tables = baseTableUsed.ext_name
        mysqli.group_by = ''
        mysqli.order_by = ''
        mysqli.limit_by = ''
        const strQuery = await mysqclass.mysqli(mysqli, 'select_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
}

module.exports.default = adminEmployeeModule