front/modules/auction.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 commonProduct = require('../../common/products').default

const mysqclass = require('./mysqli').default
/**
 * @class class to handle auction functions
 */
class auctionModule {
    /**
     * Search all the search auction
     * @param {object} req req object
     * @param {object} data req.body object
     * @param {number} count count for the pagination
     * @returns {object} sql response
     */
    static async searchAuctions(req, data, count) {
        const mysql = {}
        const baseTableUsed = global.configColumns.auctionlot
        const customTableUsed = global.configColumns.custom_auctionlot

        let row = ''
        let where = ''
        let having = ''
        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 ac.id asc`
        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.body.similars) {
            where += commonProduct.similarData(req)
        }
        if (req.body.filters) {
            where += commonProduct.filterData(req)
        }
        if (req.body.market_status) {
            if (Array.isArray(req.body.market_status)) {
                const values = req.body.market_status.join('","')
                where += ` AND ac.market_status in ("${values}") `
            } else if (typeof req.body.market_status === 'string') {
                where += ` AND ac.market_status = "${req.body.market_status}" `
            }
        } else {
            where += `and ac.market_status = "open" and ac.date_closed >= "${dateNow}" `
        }

        if (req.body.having) {
            having += commonProduct.havingData(req)
        }

        if (req.body.searchbar !== '' && req.body.searchbar) {
            let changed = req.body.searchbar.replace(/\\/g, '\\\\\\\\')
            changed = changed.replace(/"/g, '\\"')
            where = ` and (ac.title like "%${changed}%")${where}`
        }
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

        if (req.user && req.user.id) {
            where += ` and ( ac.selltype=1 and FIND_IN_SET("${req.user.id}", ac.selectedbuyer) or ac.selltype=0 ) `
        } else {
            where += ` and ac.selltype=0 `
        }

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch

        mysql.locationJoin = ''
        if (global.configFeatures.nellis_state_city_filter) {
            mysql.locationJoin = 'left join locations as l on l.id = p.location_id'
            if (typeof req.body.filters.currentLocation !== 'undefined') {
                where += ` and l.state = "${req.body.filters.currentLocation.state}" and l.city = "${req.body.filters.currentLocation.city}"`
            }
        }

        row = count === 1 ? 'get_all_auction_search_limit' : 'get_all_auction_search'
        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}`
        }

        mysql.userid = uidc
        mysql.order = order
        mysql.where = where
        mysql.having = having
        mysql.limitf = limitf
        mysql.dateNow = dateNow

        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * get auction project details
     * @param {number} pid project id
     * @param {object} req request object
     * @returns {object} sql response
     */
    static async getAuctionProjectDetails(pid, req) {
        const mysql = {}
        mysql.where = ``
        if (req.body.market_status) {
            if (Array.isArray(req.body.market_status)) {
                const values = req.body.market_status.join('","')
                mysql.where = ` AND market_status in ("${values}") `
            } else if (typeof req.body.market_status === 'string') {
                mysql.where = ` AND market_status = "${req.body.market_status}" `
            } else {
                mysql.where = ` AND market_status = "open" `
            }
        } else {
            mysql.where = ` AND market_status = "open" `
        }
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'get_project_auctions_details')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * get Auction Watch list details
     * @param {number} uid user id
     * @param {number} pid project id
     * @returns {object} sql response
     */
    static async getAuctionWatchListDetails(aid, uid) {
        const mysql = {}
        const escapeData = [aid, uid]
        const strQuery = await mysqclass.mysqli(mysql, 'get_auctions_watch_list')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     *
     * @param {object} req request data
     * @param {object} data data
     * @param {number} count count
     * @returns {object} sql query
     */
    static async getMyBids(req, data, count) {
        const actionValue = data.auction_action
        const mysql = {}
        let row = ''
        let where = ''
        let having = ''
        let limitf = ''
        let order = ''
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')

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

        order = `order by ac.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.body.similars) {
            where += commonProduct.similarData(req)
        }
        if (req.body.filters) {
            where += commonProduct.filterData(req)
        }
        if (req.body.having) {
            having += commonProduct.havingData(req)
        }

        if (actionValue !== '') {
            if (
                actionValue === 'auction' ||
                actionValue === 'all' ||
                actionValue === 'winning' ||
                actionValue === 'outbid'
            ) {
                row = count === 1 ? 'my_bidding_items' : 'my_bidding_items_count'

                if (actionValue === 'winning') {
                    where += ` and p.market_status = "open"`
                    where += ` and p.date_closed >= "${dateNow}" `
                    where += `and (select IFNULL(bb.user_id,0) as latestbiduser_id from bids AS bb where bb.project_id = p.id and bb.proposal != "tie_bid" order by bb.proposed_amount desc limit 1) = "${uidc}"`
                } else if (actionValue === 'outbid') {
                    where += ` and p.market_status = "open"`
                    where += ` and p.date_closed >= "${dateNow}" `
                    where += `and (select IFNULL(bb.user_id,0) as latestbiduser_id from bids AS bb where bb.project_id = p.id and bb.proposal != "tie_bid" order by bb.proposed_amount desc limit 1) != "${uidc}"`
                } else {
                    where += ` and (p.market_status = "open" or p.market_status = "sold")`
                }
            } else if (actionValue === 'watchlist') {
                if (!req.body.is_custom_check)
                    where += ` and p.market_status = "open" and p.date_closed >= "${dateNow}" `
                row = count === 1 ? 'dash_watchlist_item' : 'dash_watchlist_item_count'
            }
        }

        const baseTableUsed = global.configColumns.auctionlot
        const customTableUsed = global.configColumns.custom_auctionlot
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.mainTableJoin = generatedData.mainTableJoin
        mysql.columns = generatedData.rowstoFetch
        const additionalTable = global.configColumns.projects
        const customAdditionalTable = { enabled: 0 }

        const additionalGeneratedData = commonProduct.additionalTableJoin(
            additionalTable,
            customAdditionalTable,
            baseTableUsed,
            'inner join',
            'auctionid',
            'id',
        )
        mysql.customTableJoin = `${mysql.customTableJoin} ${additionalGeneratedData.customTableJoin}`
        mysql.columns = mysql.columns.concat(additionalGeneratedData.rowstoFetch)

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

        mysql.order = order
        mysql.where = where
        mysql.having = having
        mysql.limitf = limitf
        mysql.dateNow = dateNow
        mysql.userid = uidc

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

    /**
     * check if the project is in watch list table for the user
     * @param {object} req request data
     * @param {string} auctionID data is the req.body
     * @returns {object} sql response
     */
    static async auctionIsInWatchlist(req, auctionID) {
        const mysql = {}
        const uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        const escapeData = [uidc, auctionID]
        const strQuery = await mysqclass.mysqli(mysql, 'check_auction_watchlist_exist')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }

    /**
     * update watchlist to the user and project
     * @param {object} req request data
     * @param {string} auctionID auction_id to which user requested for watchlist
     * @returns {object} sql response
     */
    static async updateAuctionWatchlist(req, auctionID) {
        const mysql = {}
        const uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        const escapeData = [auctionID, uidc]
        const strQuery = await mysqclass.mysqli(mysql, 'update_existing_auction_watchlist')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }

    /**
     * add to watchlist for the user and project
     * @param {object} req request data
     * @param {string} auctionID auctionlot_id to which user requested for watchlist
     * @returns {object} sql response
     */
    static async addAuctionWatchlist(req, auctionID) {
        const mysql = {}
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        const uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        const escapeData = [auctionID, uidc, dateNow]
        const strQuery = await mysqclass.mysqli(mysql, 'insert_new_auction_watchlist')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }

    /**
     * remove watchlist for the user and project
     * @param {object} req request data
     * @param {string} auctionID auction_id to which user requested for watchlist
     * @returns {object} sql response
     */
    static async removeAuctionWatchlist(req, auctionID) {
        const mysql = {}
        const uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        const escapeData = [auctionID, uidc]
        const strQuery = await mysqclass.mysqli(mysql, 'delete_from_auction_watchlist')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }

    static async x(req, data, count) {
        let mysql = ''
        let having = ''
        let row = ''
        let order = 'ac.id desc'
        const sortorder = data.orderby
        let where = ''
        let limitf = ''

        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
        }
        if (sortorder === 1) {
            order = 'order by ac.date_closed asc'
        } else if (sortorder === 2) {
            order = 'order by ac.id desc '
        }
        where += ` and ac.market_status = "open" and ac.date_closed >= "${dateNow}" `

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

        const baseTableUsed = global.configColumns.auctionlot
        const customTableUsed = global.configColumns.custom_auctionlot
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

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

        let escapeData = []
        if (count === 0) {
            let pagen = (req.body.page - 1) * limitrg
            if (parseInt(pagen, 10) < 0) {
                pagen = 0
            }
            limitf = ` limit ${pagen},${limitrg}`
            escapeData = [uidc]
        } else {
            escapeData = [uidc]
        }
        mysql = {
            where,
            having,
            order,
            limitf,
            dateNow,
            customTableJoin: generatedData.customTableJoin,
            columns: generatedData.rowstoFetch,
        }

        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        console.log('Auction WishList', count, strQuery, escapeData)
        console.log(dataReturn)
        return dataReturn
    }
    /**
     * remove watchlist for the user and project
     * @param {object} req request data
     * @param {string} data data
     * @param {number} count data
     * @returns {object} sql response
     */
    static async getAuctionWatchList(req, data, count) {
        let mysql = ''
        let row = ''
        let order = ''
        const sortorder = data.orderby
        let where = ''
        let having = ''
        let limitf = ''

        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 ac.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
            }
        }
        // where += ` and ac.market_status = "open" and ac.date_closed >= "${dateNow}" `

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

        if (req.body.searchbar !== '' && req.body.searchbar) {
            let changed = req.body.searchbar.replace(/\\/g, '\\\\\\\\')
            changed = changed.replace(/"/g, '\\"')
            where = ` and (ac.title like "%${changed}%")${where}`
        }

        const baseTableUsed = global.configColumns.auctionlot
        const customTableUsed = global.configColumns.custom_auctionlot
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

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

        let escapeData = []
        if (count === 1) {
            let pagen = (req.body.page - 1) * limitrg
            if (parseInt(pagen, 10) < 0) {
                pagen = 0
            }
            limitf = ` limit ${pagen},${limitrg}`
            escapeData = [uidc]
        } else {
            escapeData = [uidc]
        }
        mysql = {
            where,
            having,
            order,
            userid: uidc,
            limitf,
            dateNow,
            customTableJoin: generatedData.customTableJoin,
            columns: generatedData.rowstoFetch,
        }

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

module.exports.default = auctionModule