admin/modules/product.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 mysqclass = require('./mysqli').default
const commonProduct = require('../../common/products').default
/**
 * @class class to handle product functions
 */
class adminProductModule {
    /**
     * Get all products
     * @param {object} req request data
     * @param {string} count count for the pagination
     * @returns {object} sql response
     */
    static async fetchProductsAll(req, count) {
        const mysql = {}
        const { action } = req.body

        const baseTableUsed = global.configColumns.projects
        const customTableUsed = global.configColumns.custom_projects

        let row = ''
        let where = ''
        let limitf = ''
        let order = ''
        let groupby = ''
        let subQuery = ''

        if (action) {
            if (action === 'unsold') {
                where += ' and (p.market_status = "unsold" or p.market_status = "closed") '
            } else if (action !== 'sold') {
                where += ` and p.market_status = "${action}"`
            } else if (action === 'sold') {
                where += ` and p.market_status = "sold"`
            }
        }

        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 (action) {
            if (action !== 'relisted') {
                where += ' and p.is_relist = 0 '
            }
        }

        order = `order by p.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.groupby) {
            groupby += `GROUP BY ${req.body.groupby}`
        }

        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 additionalTable = global.configColumns.buynow
        const customAdditionalTable = { enabled: 0 }

        const additionalGeneratedData = commonProduct.additionalTableJoin(
            additionalTable,
            customAdditionalTable,
            baseTableUsed,
            action === 'sold' ? 'inner join' : 'left join',
            'project_id',
            'id',
        )

        const additionalTable2 = global.configColumns.employees
        const customAdditionalTable2 = { enabled: 0 }

        const additionalGeneratedData2 = commonProduct.additionalTableJoin(
            additionalTable2,
            customAdditionalTable2,
            baseTableUsed,
            'left join',
            'id',
            'user_id',
        )

        mysql.customTableJoin = `${mysql.customTableJoin} ${additionalGeneratedData.customTableJoin} ${additionalGeneratedData2.customTableJoin} `
        mysql.columns = mysql.columns.concat(additionalGeneratedData.rowstoFetch)
        mysql.columns = mysql.columns.concat(additionalGeneratedData2.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) {
            limitf = ` `
        } else {
            let pagen = (req.body.page - 1) * limitrg
            if (parseInt(pagen, 10) < 0) {
                pagen = 0
            }
            limitf = ` limit ${pagen},${limitrg}`
        }

        if (
            req.body.filters &&
            req.body.filters.auctiontype &&
            req.body.filters.auctiontype.value === 'ttw'
        ) {
            subQuery += ` ,(select id from ${customTableUsed.ext_name} where ttw_offer_project_id = p.id limit 1 ) isAlreadyOffered `
            subQuery += ` ,(select count(bb.user_id) as bidscount from ttwbids as bb where bb.project_id = p.id) as ttwbidscount`
        }

        if (action) {
            if (action === 'sold') {
                if (count === 1) {
                    row = 'get_sold_products_limit'
                } else {
                    row = 'get_sold_products'
                }
            } else if (count === 1) {
                row = 'get_all_products_limit'
            } else {
                row = 'get_all_products'
            }
        } else if (count === 1) {
            row = 'get_all_products_limit'
        } else {
            row = 'get_all_products'
        }

        mysql.order = order
        mysql.where = where
        mysql.limitf = limitf
        mysql.dateNow = dateNow
        mysql.groupby = groupby
        mysql.subQuery = subQuery
        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * fetch Deposit Data
     * @param {object} req request data
     * @returns {object} sql response
     */
    static async fetchDepositsData(req) {
        const data = req.body
        const mysql = {}
        let row = ''
        let order = ''
        const sortorder = data.orderby
        let where = ''

        if (sortorder === 1) {
            order = 'order by bdt.date_closed asc'
        } else if (sortorder === 2) {
            order = 'order by bdt.id desc '
        }

        const baseTableUsed = global.configColumns.bid_deposit
        const customTableUsed = { enabled: 0 }
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

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

        console.log('generatedData', generatedData)
        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        mysql.mainTable = generatedData.mainTableJoin

        row = 'get_all_bid_deposit_data'

        const escapeData = []

        mysql.where = where
        mysql.order = order

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

    /**
     * Get all active Auctions
     * @returns {object} sql response
     */
    static async fetchActiveAuctions(req) {
        const mysql = {}
        if (req.body.auctionlot > 0) {
            mysql.where = ` and id = "${req.body.auctionlot}" `
        } else {
            mysql.where = ''
        }
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        const escapeData = [dateNow, dateNow]
        const strQuery = await mysqclass.mysqli(mysql, 'get_all_auct_active')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    static async fetchActiveAuctionsUsers(buyerID) {
        const mysql = {}
        mysql.where = ''
        const baseTableUsed = global.configColumns.users
        const customTableUsed = global.configColumns.custom_users
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])
        if (buyerID) {
            mysql.where = ` and u.id in (${buyerID.toString().split(',')})`
        }
        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        const escapeData = []
        const strQuery = await mysqclass.mysqli(mysql, 'get_auction_buyers')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Update Project status
     * @param {string} status Status which has to be updated
     * @param {number} pid Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async marketStatusUpdate(status, pid) {
        const mysql = { closeDate: '' }
        if (global.configurations.variables.project_close_date) {
            const extHours = global.configurations.variables.project_close_date
            const minutesaddition = parseInt(extHours, 10) * 3600000 // *60000; from minutes to milli seconds
            let dateClose = new Date(new Date().getTime() + minutesaddition)
            dateClose = dateFormat(dateClose, 'yyyy-mm-dd HH:MM:ss')
            mysql.closeDate = `, date_closed = "${dateClose}"`
        }

        const escapeData = [status, pid]
        const strQuery = await mysqclass.mysqli(mysql, 'prod_change_market_status')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        console.log('dataReturn', strQuery, escapeData)
        return dataReturn
    }
    /**
     * add attachement for project
     * @param {object} data data
     * @param {number} proid Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async addattachement(data, proid) {
        const mysqli = {}
        const escapeData = [
            proid,
            data.file_name,
            1,
            data.user_id,
            data.orderby,
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        ]
        mysqli.keys = 'project_id,file_name,type,user_id,orderby,created_at'
        mysqli.values = '?,?,?,?,?,?'
        mysqli.tables = ' attachments '
        const strQuery = await mysqclass.mysqli(mysqli, 'insert_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * add audio attachment
     * @param {object} data data
     * @param {number} projectId Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async addAudioAttachment(data, projectId) {
        const mysqli = {}
        const escapeData = [
            projectId,
            data.file_name,
            4,
            data.user_id,
            data.orderby,
            dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss'),
        ]
        mysqli.keys = 'project_id,file_name,type,user_id,orderby,created_at'
        mysqli.values = '?,?,?,?,?,?'
        mysqli.tables = ' attachments '
        const strQuery = await mysqclass.mysqli(mysqli, 'insert_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * add attachement to product
     * @param {object} data data
     * @param {number} projectId Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async addattachementtoproduct(data, proid) {
        const mysqli = {}
        const escapeData = [data, proid]
        mysqli.keys = ' avatar=?'
        mysqli.values = ' id=?'
        mysqli.tables = ' projects '
        const strQuery = await mysqclass.mysqli(mysqli, 'update_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * delete attachement to product
     * @param {number} proid Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async deleteAttachmentProject(proid) {
        const mysqli = {}
        const escapeData = [proid]
        mysqli.values = ' project_id=?'
        mysqli.tables = ' attachments '
        const strQuery = await mysqclass.mysqli(mysqli, 'delete_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    // static async deleteItemPropsProject(proid) {
    //     const mysqli = {}
    //     const escapeData = [proid]
    //     mysqli.values = ' project_id=?'
    //     mysqli.tables = ' item_props_array '
    //     const strQuery = await mysqclass.mysqli(mysqli, 'delete_tables')
    //     const dataReturn = await global.mysql.query(strQuery, escapeData)
    //     return dataReturn
    // }
    /**
     * delete items props project
     * @param {number} proid Project ID which status has to be updated
     * @returns {object} sql response
     */
    static async deleteItemPropsProject(proid) {
        const mysqli = {}
        const escapeData = [proid]
        mysqli.keys = ' is_deleted=1'
        mysqli.values = ' project_id=?'
        mysqli.tables = ' item_props_array '
        const strQuery = await mysqclass.mysqli(mysqli, 'update_tables')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * fetch one Project By ID
     * @param {object} pid auction ID to which the data is to be fetched
     * @returns {object} sql response
     */
    static async fetchProjectbyID(pid, baseTableUsed, customTableUsed) {
        const mysql = {}
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])
        mysql.baseTableName = baseTableUsed.ext_name
        mysql.baseTableShort = baseTableUsed.short_name
        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'get_single_project')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }
    /**
     * fetch all attachments By Project ID
     * @param {object} pid auction ID to which the data is to be fetched
     * @returns {object} sql response
     */
    static async fetchAllAttachments(pid) {
        const mysql = {}
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'get_all_attachments')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * fetch all attachments By Project ID
     * @param {object} pid auction ID to which the data is to be fetched
     * @returns {object} sql response
     */
    static async bidHistoryViewPage(req, count) {
        const mysql = {}

        const projectID = req.body.filters.project_id.value

        const baseTableUsed = global.configColumns.bids
        const customTableUsed = { enabled: 0 }

        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 b.common_invoice 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)
        }

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

        if (req.body.get_proxy) {
            row = count === 1 ? 'get_all_proxy_bid_history_limit' : 'get_all_proxy_bid_history'
        } else {
            row = count === 1 ? 'get_all_bid_history_limit' : 'get_all_bid_history'
        }

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

        const escapeData = [projectID, projectID]
        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.limitf = limitf

        mysql.customTableJoin = generatedData.customTableJoin
        if (req.body.get_proxy) {
            mysql.columns = []
        } else {
            mysql.columns = generatedData.rowstoFetch
        }
        mysql.mainTable = generatedData.mainTableJoin

        const additionalTable = global.configColumns.users
        const customAdditionalTable = global.configColumns.custom_users

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

        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * ttw Bid history
     * @param {object} req request data
     * @param {Number} count data
     * @returns {object} sql response
     */
    static async ttwBidHistory(req, count) {
        const mysql = {}
        mysql.where = ''
        if (req.body.ttwOffers) mysql.where += ' and b.awarded =1 '
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        mysql.order = ''
        let row = ''
        const pagen = (req.body.page - 1) * req.body.limit
        const limitf = ` limit ${pagen},${req.body.limit}`
        mysql.limit = limitf
        mysql.dateNow = dateNow
        const escapeData = [req.body.id]
        if (count === 1) {
            row = 'get_all_ttwbid_history_limit'
        } else {
            row = 'get_all_ttwbid_history'
        }
        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * ttw Bid history update
     * @param {object} data ttw update data
     * @returns {object} sql response
     */
    static async ttwBidHistoryUpdate(data) {
        const mysql = {}
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        const escapeData = [dateNow, data.proposed_amount, data.id]
        const strQuery = await mysqclass.mysqli(mysql, 'ttwbid_history_update')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * item props array
     * @param {number} pid projet ids
     * @param {string} baseTableUsed base table name
     * @param {Object} customTableUsed custom table  by default { enabled: 0 }
     * @returns {object} sql response
     */
    static async itemPropsArray(pid, baseTableUsed, customTableUsed = { enabled: 0 }) {
        const mysql = {}
        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])
        mysql.baseTableName = baseTableUsed.ext_name
        mysql.baseTableShort = baseTableUsed.short_name
        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'itemPropsArray')
        const data = await global.mysql.query(strQuery, escapeData)
        return data
    }
}

module.exports.default = adminProductModule