admin/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 adminAuctionModule = require('../../modules/auction').default
const schemaModule = require('./schema').default
const commonFunction = require('../../../common/function').default

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

const shortDescribeSCH = 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
}
/**
 * Re configure the end time for the auction projects
 *
 * @memberOf adminside.auction
 * @param {string} auctionLotId auctionID for which the configuration end time has to be changed
 * @param {adminAuctionModule.fetchAuctionbyID} modules
 * @param {adminAuctionModule.updateAllCloseDates} modules
 * @param {adminAuctionModule.getAllSubLots} modules
 * @param {adminAuctionModule.updatelofdetails} modules
 */
const reConfigureEndTime = async (auctionLotId) => {
    const [auctionLot] = await Promise.all([adminAuctionModule.fetchAuctionbyID(auctionLotId)])
    await Promise.all([
        adminAuctionModule.updateAllCloseDates(
            auctionLot[0].date_added,
            auctionLot[0].date_closed,
            auctionLotId,
        ),
    ])
    if (auctionLot[0].ending_enable === 1) {
        const [subLots] = await Promise.all([adminAuctionModule.getAllSubLots(auctionLotId)])

        let updatelotcnt = 0
        let updatelottime = auctionLot[0].ending_mins
        let list = 1
        let belowFiveIncrement = new Date()
        const processAllItems = async (items) => {
            const newdt = new Date(auctionLot[0].date_closed)
            updatelotcnt += 1
            if (auctionLot[0].ending_mins === updatelottime && list === 1) {
                belowFiveIncrement = new Date(auctionLot[0].date_closed)
            } else {
                const minutesaddition = parseInt(updatelottime, 10) * 60000
                belowFiveIncrement = new Date(newdt.getTime() + minutesaddition)
            }
            adminAuctionModule.updatelofdetails(items.id, belowFiveIncrement)
            if (auctionLot[0].ending_items === updatelotcnt) {
                updatelotcnt = 0
                if (auctionLot[0].ending_mins === updatelottime && list === 1) {
                    list = 0
                } else {
                    updatelottime += auctionLot[0].ending_mins
                }
                return true
            }
            return true
        }

        const resultloop = []
        subLots.forEach(async (element) => {
            const looptoformat = await processAllItems(element)
            resultloop.push(looptoformat)
        })
        await Promise.all(resultloop)
    }
    return true
}

module.exports = {
    /**
     * Get Auction Lots
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.fetchAuctionsAll} modules
     */
    auctionlots: async (req, res) => {
        req.body.action = typeof req.body.action === 'undefined' ? 'open' : req.body.action
        let records = []
        let totalRecords = []
        try {
            ;[records, totalRecords] = await Promise.all([
                adminAuctionModule.fetchAuctionsAll(req, 0),
                adminAuctionModule.fetchAuctionsAll(req, 1),
            ])
            records = await shortDescribeSCH(records)
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            let responseData = { records, totalRecords }
            responseData = await commonFunction.getdynamicinnercontents(req, responseData)
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        }
    },
    /**
     * Auction Actions
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.auctionOperation} modules
     * @param {adminAuctionModule.emptyOutAuctionID} modules
     * @param {adminAuctionModule.auctionProjectUpdateexist} modules
     */
    auctionAction: async (req, res) => {
        try {
            if (typeof req.file !== 'undefined') {
                req.body.avatar = req.file.filename
            }

            req.body.ending_enable = !!(req.body.ending_enable && req.body.ending_enable === 'true')
            req.body.id =
                typeof req.body.id === 'undefined' ||
                req.body.id === 0 ||
                req.body.id === '0' ||
                req.body.id === ''
                    ? null
                    : req.body.id

            const results = await Promise.all([adminAuctionModule.auctionOperation(req)])
            if (req.body.id) {
                req.body.auction_id = req.body.id
            } else {
                req.body.auction_id = results[0].insertId
            }

            await Promise.all([adminAuctionModule.emptyOutAuctionID(req.body.auction_id)])
            await Promise.all([adminAuctionModule.auctionProjectUpdateexist(req)])
            await reConfigureEndTime(req.body.auction_id)
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = {}
            jsonResponse(res, 'success', {
                responseType: 1,
                message: req.body.id ? 'Successfully updated!' : 'Successfully added!',
                responseData,
            })
        }
    },
    /**
     * Get Single Auction Details
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.fetchAuctionbyID} modules
     */
    getSingleAuction: async (req, res) => {
        let record = {}
        try {
            const id = typeof req.body.id === 'undefined' ? '' : req.body.id
            let [records] = await Promise.all([adminAuctionModule.fetchAuctionbyID(id)])
            records = await shortDescribeSCH(records)
            record = records[0]
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = { record }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        }
    },
    /**
     * Add Project to Auctions
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.auctionProjectUpdateexist} modules
     * @param {adminside.auction.reConfigureEndTime} modules
     */
    addtoAuction: async (req, res) => {
        try {
            const responseData = {}
            const auctionId = typeof req.body.auction_id === 'undefined' ? '' : req.body.auction_id
            if (auctionId) {
                await Promise.all([adminAuctionModule.auctionProjectUpdateexist(req)])
                await reConfigureEndTime(auctionId)
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Successfully added!',
                    responseData,
                })
            } else {
                jsonResponse(res, 'error', {
                    responseType: 1,
                    message: 'No Auction selected!',
                    responseData,
                })
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Get All projects for the auction
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.getAllAssociatedAuctions} modules
     */
    getAllProjectsAssociated: async (req, res) => {
        let records = []
        try {
            const id = typeof req.body.id === 'undefined' ? '' : req.body.id
            ;[records] = await Promise.all([adminAuctionModule.getAllAssociatedAuctions(id)])
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = { records }
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Details successfully retrieved!',
                responseData,
            })
        }
    },
    /**
     * Change Status of the Auction
     *
     * @memberOf adminside.auction
     * @param {adminAuctionModule.emptyOutAuctionID} modules
     * @param {adminAuctionModule.auctionStatusUpdate} modules
     */
    changeStatus: async (req, res) => {
        try {
            if (req.body.action && req.body.auction_id.length > 0) {
                if (req.body.action === 'removed') {
                    await Promise.all([adminAuctionModule.emptyOutAuctionID(req.body.auction_id)])
                }
                await adminAuctionModule.auctionStatusUpdate(req.body.action, req.body.auction_id)
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = {}
            jsonResponse(res, 'success', {
                responseType: 1,
                message: 'Status successfully changed',
                responseData,
            })
        }
    },

    // deleteauction: async (req, res) => {
    //     const auctionid = typeof req.body.auctionid === 'undefined' ? '' : req.body.auctionid
    //     if (auctionid && auctionid !== '') {
    //         await Promise.all([admin.delete_auction(auctionid)])
    //         jsonResponse(res, 'success', '')
    //     } else {
    //         jsonResponse(res, 'failed', '')
    //     }
    // },

    // deletelot: async (req, res) => {
    //     const lotid = typeof req.body.lotid === 'undefined' ? '' : req.body.lotid
    //     if (lotid && lotid !== '') {
    //         await Promise.all([admin.delete_auction(lotid), admin.delete_project_auct(lotid)])
    //         jsonResponse(res, 'success', '')
    //     } else {
    //         jsonResponse(res, 'failed', '')
    //     }
    // },

    // deleteVehicle: async (req, res) => {
    //     const vehicleid = typeof req.body.vehicleid === 'undefined' ? '' : req.body.vehicleid
    //     if (vehicleid && vehicleid !== '') {
    //         await Promise.all([admin.delete_products(vehicleid)])
    //         console.log('auction lot id: ', req.body.auct_id)
    //         await reConfigureEndTime(req.body.auct_id) // reconfigure the start / end time for each sub lots after updated the auction lot information
    //         jsonResponse(res, 'success', '')
    //     } else {
    //         jsonResponse(res, 'failed', '')
    //     }
    // },
}