front/controllers/auction/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 jwt = require('jsonwebtoken')
const auctionModule = require('../../modules/auction').default
const productModule = require('../../modules/product').default
const productController = require('../product/index')
const commonFunction = require('../../../common/function').default

const schemaModule = require('./schema').default
const { jsonResponse } = require('../logger')

/**
 * Get Dynamic contects for the pagination for auction
 *
 * @memberOf frontend.auction
 * @param {object} req req data with images which has to be uploaded
 * @param {number} responseData response Data which has to be retrieved
 */
const getdynamicinnercontents = async (req, responseData) => {
    const returnResponse = responseData
    returnResponse.totalRecords = returnResponse.totalRecords[0]
        ? returnResponse.totalRecords[0].totallength
        : 0
    let disp = (parseInt(req.body.page, 10) - 1) * req.body.limit + 1
    const afifen = (parseInt(req.body.page, 10) - 1) * req.body.limit + parseInt(req.body.limit, 10)
    const orgifen = afifen > returnResponse.totalRecords ? returnResponse.totalRecords : afifen
    disp = returnResponse.totalRecords === 0 ? 0 : disp
    returnResponse.setDisp = `${disp}-${orgifen}`
    return returnResponse
}

/**
 * Add image link to the data
 *
 * @memberOf frontend.auction
 * @param {array} items Items array in which image url is added to the name
 */
const shortDescribeSCHOnlyAvatar = async (items) => {
    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/auction/${item.file_name}`
        return item
    }
    const promises = items.map(changingdata)
    items = await Promise.all(promises)
    return items
}
/**
 * get lot details
 *
 * @memberOf frontend.auction
 * @param {array} items Items array
 * @param {object} req req object
 */
const getLotDetails = async (items, req) => {
    const itemsChanged = []

    const getProjectID = async (item) => {
        req.body.filters = {}
        req.body.filters = {
            project: {
                value: item.id,
                type: 'in',
                field: 'p.auctionid',
            },
        }
        // const [projectID] = await Promise.all([auctionModule.getAuctionProjectDetails(item.id, req)])
        const [projectID] = await Promise.all([productModule.searchProducts(req, req.body, 1)])
        item.all_projects = projectID
        if (
            global.configFeatures.load_bidding_details &&
            global.configFeatures.load_bidding_details.enabled
        ) {
            await productController.biddingDetails(req, item.all_projects)
        }
        itemsChanged.push(item)
        return true
    }
    await commonFunction.asyncForEach(items, async (element) => {
        await getProjectID(element)
    })
    return itemsChanged
}
/**
 * auction watch list
 *
 * @memberOf frontend.auction
 * @param {array} items Items array
 * @param {number} userID user id
 */
const auctionWatchList = async (items, userID) => {
    const itemsChanged = []
    const getProjectID = async (item) => {
        const [projectID] = await Promise.all([
            auctionModule.getAuctionWatchListDetails(item.id, userID),
        ])
        item.following_auction =
            typeof projectID[0] !== 'undefined' ? projectID[0].following_auction : 0
        itemsChanged.push(item)
        return true
    }
    await commonFunction.asyncForEach(items, async (element) => {
        await getProjectID(element)
    })
    return itemsChanged
}
/**
 * Get bidding lot deatils
 *
 * @memberOf frontend.auction
 * @param {array} items Items array
 * @param {number} userID user id
 */
const getBiddingLotDetails = async (req, items) => {
    const dashboardData = {
        body: {},
    }
    dashboardData.body.limit = 1000
    dashboardData.body.page = 1
    dashboardData.body.action = 'all'
    dashboardData.user = req.user
    const itemsChanged = []
    const getProjectID = async (item) => {
        dashboardData.body.filters = {}
        dashboardData.body.filters = {
            project: {
                value: item.id,
                type: 'in',
                field: 'p.auctionid',
            },
        }
        const [responseData] = await Promise.all([
            productController.dashboardFunction(dashboardData),
        ])
        item.all_projects = responseData
        itemsChanged.push(item)
        return true
    }
    await commonFunction.asyncForEach(items, async (element) => {
        await getProjectID(element)
    })
    return itemsChanged
}

module.exports = {
    /**
     * Search Auction Items
     *
     * @memberOf frontend.auction
     * @param {auctionModule.searchAuctions} modules
     * @param {frontend.auction.shortDescribeSCHOnlyAvatar} modules
     * @param {frontend.auction.getdynamicinnercontents} modules
     */
    search: async (req, res) => {
        try {
            await schemaModule.search().validateSync(req.body)
            let [records, totalRecords] = await Promise.all([
                auctionModule.searchAuctions(req, req.body, 1),
                auctionModule.searchAuctions(req, req.body, 0),
            ])
            totalRecords = [{ totallength: totalRecords.length }]
            let responseData = { records, totalRecords }
            records = await shortDescribeSCHOnlyAvatar(records)
            if (
                global.configFeatures.lot_details_in_auction &&
                global.configFeatures.lot_details_in_auction.enabled
            ) {
                records = await getLotDetails(records, req)
            }
            if (
                global.configFeatures.auction_watch_list &&
                global.configFeatures.auction_watch_list.enabled
            ) {
                const userID = typeof req.user !== 'undefined' ? req.user.id : 0
                records = await auctionWatchList(records, userID)
            }
            responseData = await getdynamicinnercontents(req, responseData)
            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 perticular user bids
     *
     * @memberOf frontend.getMyBids
     * @param {auctionModule.getMyBids} modules
     * @param {frontend.auction.getBiddingLotDetails} modules
     */
    getMyBids: async (req, res) => {
        try {
            await schemaModule.search().validateSync(req.body)
            let [records, totalRecords] = await Promise.all([
                auctionModule.getMyBids(req, req.body, 1),
                auctionModule.getMyBids(req, req.body, 0),
            ])
            totalRecords = [{ totallength: totalRecords.length }]
            records = await getBiddingLotDetails(req, records)
            const responseData = { records, totalRecords }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },

    /**
     * Add to watchlist
     *
     * @memberOf frontend.auction
     * @param {auctionModule.auctionIsInWatchlist} modules
     * @param {auctionModule.updateWatchlist} modules
     * @param {auctionModule.addAuctionToWatchList} modules
     */
    addAuctionToWatchList: async (req, res) => {
        try {
            const auctionID = req.body.auction_id
            const [watchexist] = await Promise.all([
                auctionModule.auctionIsInWatchlist(req, auctionID),
            ])
            if (watchexist.length > 0) {
                await Promise.all([auctionModule.updateAuctionWatchlist(req, auctionID)])
            } else {
                await Promise.all([auctionModule.addAuctionWatchlist(req, auctionID)])
            }
            const responseData = { auction_id: auctionID, status: 'added' }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Successfully added to watchlist!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },

    /**
     * Remove from watchlist
     *
     * @memberOf frontend.auction
     * @param {auctionModule.removeAuctionToWatchList} modules
     */
    removeAuctionFromWatchList: async (req, res) => {
        try {
            const auctionID = req.body.auction_id
            await Promise.all([auctionModule.removeAuctionWatchlist(req, auctionID)])
            const responseData = { auction_id: auctionID, status: 'removed' }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Successfully removed from watchlist!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * get user auction watch list
     *
     * @memberOf frontend.auction
     * @param {auctionModule.getAuctionWatchList} modules
     */
    getAuctionWatchList: async (req, res) => {
        try {
            let [records, totalRecords] = await Promise.all([
                auctionModule.getAuctionWatchList(req, req.body, 1),
                auctionModule.getAuctionWatchList(req, req.body, 0),
            ])
            if (
                global.configFeatures.lot_details_in_auction &&
                global.configFeatures.lot_details_in_auction.enabled
            ) {
                records = await getLotDetails(records, req)
            }
            let responseData = { records, totalRecords }
            responseData = await getdynamicinnercontents(req, responseData)
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
}

module.exports.auctionWatchList = auctionWatchList