front/modules/cart.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 cart functions
 */
class cartModule {
    /**
     * All cart items fetch
     * @param {object} req req object
     * @param {number} data req.body object
     * @param {number} count count for the pagination
     * @returns {object} sql response
     */
    static async allCartItems(req, data, count) {
        const baseTableUsed = global.configColumns.projects
        const customTableUsed = global.configColumns.custom_projects

        const mysql = {}
        let row = ''
        let where = ''
        const order = 'p.date_closed asc'
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        where += count === 1 ? `and b.cart_id = ${req.body.cart_id}` : ' and b.cart_id = 0'

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

        row = 'cart_all_item'
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc]
        const ordergor = order === '' ? '' : `order by ${order}`

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        mysql.where = where
        mysql.order = ordergor
        mysql.dateNow = dateNow
        mysql.userid = uidc

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

    /**
     * All cart items fetch
     * @param {object} req req object
     * @param {number} data req.body object
     * @param {number} count count for the pagination
     * @returns {object} sql response
     */
    static async getAllCarts(req) {
        let mysql = ''
        let row = ''
        let where = ''
        const order = 'pc.id asc'
        where += ``
        row = 'cart_all_cartid'
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc]
        const ordergor = order === '' ? '' : `order by ${order}`
        mysql = {
            where,
            order: ordergor,
            userid: uidc,
        }

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

    /**
     * Get all available appointments
     * @param {object} req req object
     * @returns {object} sql response
     */
    static async getAllAvailableAppointments(req) {
        let mysql = ''
        let row = ''
        let where = ''
        const order = 'a.id asc'
        where += ``
        row = 'get_all_available_appointments'
        let uidc = 0
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        let betweenDate = new Date(new Date().getTime() + 3 * 24 * 60 * 60 * 1000)
        betweenDate = dateFormat(betweenDate, 'yyyy-mm-dd HH:MM:ss')
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [dateNow, betweenDate, uidc]
        const ordergor = order === '' ? '' : `order by ${order}`
        mysql = {
            where,
            order: ordergor,
            userid: uidc,
        }

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

    /**
     * Get all sort and filtered values
     * @param {object} req req object
     * @param {object} data req.body object
     * @returns {object} sql response
     */
    static async getSearchSortCategories(req, data) {
        const mysql = {}
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        mysql.where = ''
        mysql.where += ` and p.market_status = "open" and p.date_closed >= "${dateNow}" `

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

    /**
     * Check Product exists for the users
     * @param {object} req req object
     * @param {object} id project id to check
     * @returns {object} sql response
     */
    static async checkUserProductExists(req, id) {
        const mysql = {}
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc, id]
        const strQuery = await mysqclass.mysqli(mysql, 'check_cart_user')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Check Product exists for the users
     * @param {object} req req object
     * @param {object} id project id to check
     * @returns {object} sql response
     */
    static async checkUserCartExists(req, locationID) {
        const mysql = {}
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc, locationID]
        const strQuery = await mysqclass.mysqli(mysql, 'check_cart_user_exists')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Check User has un paid items exists
     * @param {object} req req object
     * @returns {object} sql response
     */
    static async checkUserUnPaidExists(req) {
        const mysql = {}
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc]
        const strQuery = await mysqclass.mysqli(mysql, 'check_cart_user_exists')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Get all cart details
     * @param {number} cartID cart ID the details to be fetched
     * @returns {object} sql response
     */
    static async getCartDetails(cartID) {
        const mysql = {}
        const escapeData = [cartID]
        const strQuery = await mysqclass.mysqli(mysql, 'get_cart_all_data')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * cart Location Details
     * @param {number} cartID cart ID the location details to be fetched
     * @returns {object} sql response
     */
    static async cartLocationDetails(cartID) {
        const mysql = {}
        const escapeData = [cartID]
        const strQuery = await mysqclass.mysqli(mysql, 'get_cart_location_data')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * change cart status
     * @param {number} req req object
     * @param {number} cartChange cart change details
     * @param {number} id cart ID which status has to be changed
     * @returns {object} sql response
     */
    static async changeCartStatus(req, cartChange, id) {
        const mysql = {}
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [cartChange, uidc, id]
        const strQuery = await mysqclass.mysqli(mysql, 'add_cart_to_user')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * add New Cart Entry
     * @param {object} req req object
     * @param {object} userDetails user details object
     * @param {number} locationID location ID which has to be added
     * @returns {object} sql response
     */
    static async addNewCartEntry(req, userDetails, locationID) {
        const mysql = {}
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        const escapeData = [
            req.user.id,
            userDetails.first_name,
            userDetails.last_name,
            userDetails.address1,
            userDetails.address2,
            userDetails.city,
            userDetails.state,
            userDetails.zip,
            locationID,
            dateNow,
        ]
        const strQuery = await mysqclass.mysqli(mysql, 'insert_new_cart_user')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Update Cart Entry
     * @param {object} data req.body object
     * @param {number} id cart ID which has to be updated
     * @returns {object} sql response
     */
    static async updateCartData(data, id) {
        let postData = data
        const mysqli = {}
        if (postData.total_amount) {
            postData.balance_amount = postData.total_amount
        } else {
            postData.balance_amount = 0.0
        }
        const acceptedObjects = [
            'per_total',
            'total_items',
            'tax_percent',
            'total_tax',
            'buyer_premium',
            'total_premium',
            'total_shipping',
            'total_amount',
            'balance_amount',
            'bill_first_name',
            'bill_last_name',
            'bill_address1',
            'bill_address2',
            'bill_city',
            'bill_state',
            'bill_zipcode',
            'cart_paid',
        ]
        postData = _.omit(postData, (value, key) => {
            if (
                _.isNull(value) ||
                _.isUndefined(value) ||
                value === '' ||
                !_.contains(acceptedObjects, key)
            ) {
                return true
            }
            return false
        })
        let escapeData = []
        const defaultKeys = ['updated_at']
        const defaultValues = [dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')]
        const keyswithescape = defaultKeys.concat(_.keys(postData))
        escapeData = defaultValues.concat(_.values(postData))
        mysqli.keys = _.map(keyswithescape, (val) => {
            return `${val} = ?`
        })
        mysqli.cart_id = id
        const strQuery = await mysqclass.mysqli(mysqli, 'update_cart_details')
        const dataPromise = await global.mysql.query(strQuery, escapeData)
        return dataPromise
    }

    /**
     * get All Pending Cart ID
     * @param {object} req req object
     * @returns {object} sql response
     */
    static async getAllPendingCartID(req) {
        const mysql = {}
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        const escapeData = [uidc]
        const strQuery = await mysqclass.mysqli(mysql, 'get_all_pending_carts')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * get All Pending Cart Items
     * @param {object} req req object
     * @param {number} cartID cart ID which items has to be fetched
     * @returns {object} sql response
     */
    static async getAllPendingCartItems(req, cartID) {
        const mysql = {}
        let uidc = 0
        let arrayCartID = []
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }
        if (cartID instanceof Array) {
            arrayCartID = cartID
        } else if (cartID) {
            arrayCartID = cartID.split(',')
        } else {
            arrayCartID = [0]
        }
        const escapeData = [uidc, arrayCartID]

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

module.exports.default = cartModule