front/controllers/return/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 returnModule = require('../../modules/return').default

const commonFunction = require('../../../common/function').default
const userModule = require('../../modules/user').default
const schemaModule = require('./schema').default
const { jsonResponse } = require('../logger')

const shortDescribeSCH = async (items) => {
    /**
     * Adds two numbers together.
     * @function
     */
    function changingdata(item) {
        item.avatarorg =
            item.file_name === '' || item.file_name === null
                ? `${global.s3_static_image_url}images/pics-coming.jpg`
                : `${global.s3_static_image_url}uploads/product/${item.file_name}`
        return item
    }
    const promises = items.map(changingdata)
    items = await Promise.all(promises)
    return items
}

const cartItemsCalculations = async (items) => {
    const cartValues = {
        per_total: 0,
        total_amount: 0,
        total_items: 0,
        tax_percent: 0,
        buyer_premium: 0,
        total_premium: 0,
        total_tax: 0,
        total_shipping: 0,
    }
    /**
     * Changing data .
     * @function
     */
    function changingdata(item) {
        cartValues.per_total += parseFloat(item.buynowamount)
        cartValues.total_items += 1
    }
    const promises = items.map(changingdata)
    items = await Promise.all(promises)
    cartValues.tax_percent = 10
    cartValues.buyer_premium = 15
    cartValues.total_tax = (cartValues.per_total * (cartValues.tax_percent / 100)).toFixed(2)
    cartValues.total_premium = (cartValues.per_total * (cartValues.buyer_premium / 100)).toFixed(2)
    const totalTaxPremium = commonFunction.sumFloat(cartValues.total_premium, cartValues.total_tax)
    cartValues.total_amount = commonFunction.sumFloat(
        parseFloat(cartValues.per_total).toFixed(2),
        parseFloat(totalTaxPremium).toFixed(2),
    )
    return cartValues
}

const getorCreateCartID = async (req, userDetails, locationID) => {
    let cartId = 0
    const resultcart = await Promise.all([returnModule.checkUserCartExists(req, locationID)])
    if (resultcart[0].length > 0) {
        cartId = resultcart[0][0].id
    } else {
        const results = await Promise.all([
            returnModule.addNewCartEntry(req, userDetails, locationID),
        ])
        cartId = results[0].insertId
    }
    return cartId
}

/**
 * Relist Product
 *
 * @memberOf frontend.return
 * @param {returnModule.allCartItems} modules
 * @param {returnModule.getCartDetails} modules
 * @param {returnModule.cartLocationDetails} modules
 */
const getSingleCartDetails = async (req, cartID) => {
    req.body.cart_id = cartID
    let [cartItems, cartValues, cartLocation] = await Promise.all([
        returnModule.allCartItems(req, req.body, 1),
        returnModule.getCartDetails(req.body.cart_id),
        returnModule.cartLocationDetails(req.body.cart_id),
    ])
    cartItems = await shortDescribeSCH(cartItems)
    const responseData = { cartItems, cartValues: cartValues[0], cartLocation: cartLocation[0] }
    return responseData
}

/**
 * Relist Product
 *
 * @memberOf frontend.return
 * @param {returnModule.checkUserProductExists} modules
 * @param {userModule.userDetails} modules
 * @param {returnModule.changeCartStatus} modules
 * @param {returnModule.updateCartData} modules
 */
const checkAndAddtoCart = async (req) => {
    let success = false
    const resultuser = await Promise.all([
        returnModule.checkUserProductExists(req, req.body.id),
        userModule.userDetails(req.user.id),
    ])
    const userDetails = resultuser[1][0]
    if (resultuser[0].length > 0) {
        req.body.cart_id = await getorCreateCartID(req, userDetails, resultuser[0][0].location_id)
        const cartChange = req.body.cart === 1 ? req.body.cart_id : 0
        await Promise.all([returnModule.changeCartStatus(req, cartChange, req.body.id)])
        const [cartItems] = await Promise.all([returnModule.allCartItems(req, req.body, 1)])
        const cartValues = await cartItemsCalculations(cartItems)
        await Promise.all([returnModule.updateCartData(cartValues, req.body.cart_id)])
        success = true
    } else {
        success = false
    }
    const responseData = { success }
    return responseData
}

const getNonCartItems = async (req) => {
    let [nonCartItems] = await Promise.all([returnModule.allCartItems(req, req.body, 0)])
    nonCartItems = await shortDescribeSCH(nonCartItems)
    const responseData = nonCartItems
    return responseData
}

/**
 * Relist Product
 *
 * @memberOf frontend.return
 * @param {returnModule.updateReturned} modules
 * @param {returnModule.IMrelistall} modules
 * @param {returnModule.updateRelisted} modules
 * @param {returnModule.IMrelistallAttach} modules
 */
const relistProduct = async (prodID, status) => {
    if (status === 'returned') {
        await Promise.all([returnModule.updateReturned(prodID, status)])
    } else if (status === 'relisted') {
        const [newProd, updateRelist] = await Promise.all([
            returnModule.IMrelistall(prodID),
            returnModule.updateRelisted(prodID, status),
        ])
        await Promise.all([returnModule.IMrelistallAttach(prodID, newProd.insertId)])
    }
    const responseData = {}
    return responseData
}

module.exports = {
    relistProduct,
    getSingleCartDetails,
    checkAndAddtoCart,
    /**
     * Single Cart Usage
     *
     * @memberOf frontend.return
     * @param {frontend.return.getSingleCartDetails} modules
     */
    singleCart: async (req, res) => {
        try {
            await schemaModule.search().validateSync(req.body)
            const [responseData] = await Promise.all([getSingleCartDetails(req, req.body.cart_id)])
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Single Cart Usage
     *
     * @memberOf frontend.return
     * @param {returnModule.getAllAvailableAppointments} modules
     */
    checkAppointments: async (req, res) => {
        try {
            const [records] = await Promise.all([returnModule.getAllAvailableAppointments(req)])
            const responseData = {
                records,
            }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Get all return products for the user
     *
     * @memberOf frontend.return
     * @param {frontend.return.getSingleCartDetails} modules
     * @param {returnModule.getAllCarts} modules
     */
    search: async (req, res) => {
        try {
            await schemaModule.search().validateSync(req.body)
            const allCarts = []
            const getallCartsFunction = async (cartID) => {
                const [responseData] = await Promise.all([getSingleCartDetails(req, cartID)])
                allCarts.push(responseData)
            }

            const [allCartsUsers, nonCartItems] = await Promise.all([
                returnModule.getAllCarts(req),
                getNonCartItems(req),
            ])

            await commonFunction.asyncForEach(allCartsUsers, async (carts) => {
                await getallCartsFunction(carts.id)
            })

            const responseData = {
                nonCartItems,
                cartItems: allCarts,
            }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Change one status of the return cart item
     *
     * @memberOf frontend.return
     * @param {frontend.return.checkAndAddtoCart} modules
     */
    changeStatus: async (req, res) => {
        try {
            await schemaModule.changeStatus().validateSync(req.body)
            const [response] = await Promise.all([checkAndAddtoCart(req)])
            if (response.success) {
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message:
                        req.body.cart === 1
                            ? 'Successfully added to cart!'
                            : 'Successfully removed from cart!',
                })
            } else {
                jsonResponse(res, 'error', {
                    responseType: 2,
                    message: 'Cart action failed!',
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Save return cart billing address
     *
     * @memberOf frontend.return
     * @param {returnModule.updateCartData} modules
     */
    saveAddress: async (req, res) => {
        try {
            await schemaModule.saveAddress().validateSync(req.body)
            await Promise.all([returnModule.updateCartData(req.body, req.body.cart_id)])
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Billing Address Updated!',
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
}