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 commonModule = require('../../../common/modules/tables').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.avatar === '' || item.avatar === null
                ? `${global.s3_static_image_url}images/pics-coming.jpg`
                : `${global.s3_static_image_url}uploads/auction/${item.avatar}`
        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} items auction details
 * @param {adminAuctionModule.getAuctionProjectID} modules
 * @param {commonFunction.asyncForEach} modules
 * @returns {Object} all related projects
 */
const getAssociatedProjects = async (items) => {
    const itemsChanged = []
    const getProjectID = async (item) => {
        const [projectID] = await Promise.all([adminAuctionModule.getAuctionProjectID(item.id)])
        item.auction_lots = projectID[0].auction_lots
        itemsChanged.push(item)
        return true
    }
    await commonFunction.asyncForEach(items, async (element) => {
        await getProjectID(element)
    })
    return itemsChanged
}

/**
 * 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 (req, auctionLotId, updateProject) => {
    const [auctionLot] = await Promise.all([adminAuctionModule.fetchAuctionbyID(auctionLotId)])
    await Promise.all([
        adminAuctionModule.updateAllCloseDates(
            auctionLot[0].date_added,
            auctionLot[0].date_closed,
            auctionLotId,
        ),
    ])
    const [subLots] = await Promise.all([adminAuctionModule.getAllSubLots(auctionLotId)])

    let updatelotcnt = 0
    let updatelottime = auctionLot[0].ending_mins
    let list = 1
    let belowFiveIncrement = new Date()

    if (updateProject) {
        delete req.body.market_status
        delete req.body.date_closed
        delete req.body.date_added
        delete req.body.ending_enable
        delete req.body.ending_items
        delete req.body.ending_mins
        delete req.body.ending_enable
        delete req.body.description
        delete req.body.title
        delete req.body.avatar
    }

    const processAllItems = async (items) => {
        if (auctionLot[0].ending_enable === 1) {
            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)
            }

            await 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
                }
            }
        }

        if (updateProject) {
            if (req.body.project_status) {
                req.body.market_status = req.body.project_status
            }
            req.body.id = items.id
            const baseTableUsed = global.configColumns.projects
            const customTableUsed = global.configColumns.custom_projects
            const [results] = await Promise.all([
                commonFunction.tableFunction(req, baseTableUsed, customTableUsed),
            ])
        }
        return true
    }

    await commonFunction.asyncForEach(subLots, async (element) => {
        await processAllItems(element)
    })
    return true
}

module.exports = {
    reConfigureEndTime,
    /**
     * 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),
            ])
            totalRecords = [{ totallength: totalRecords.length }]
            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 {
            req.body.id = commonFunction.getValidID(req.body.id)
            const baseTableUsed = global.configColumns.auctionlot
            const customTableUsed = global.configColumns.custom_auctionlot

            if (req.body.date_added) {
                req.body.date_added = commonFunction.dateTimeFormatConvert(req.body.date_added)
            }
            if (req.body.date_closed) {
                req.body.date_closed = commonFunction.dateTimeFormatConvert(req.body.date_closed)
            }

            if (req.body.id) {
                req.body.updated_at = commonFunction.dateTimeFormatConvert(new Date())
            } else {
                req.body.user_id = req.user.admin_id
                req.body.created_at = commonFunction.dateTimeFormatConvert(new Date())
            }

            if (req.body.project_status === 'draft') {
                req.body.market_status = 'draft'
            } else if (req.body.project_status === 'open') {
                req.body.market_status = 'open'
            }

            const [results] = await Promise.all([
                commonFunction.tableFunction(req, baseTableUsed, customTableUsed),
            ])
            if (req.body.id) {
                req.body.auction_id = req.body.id
            } else {
                req.body.auction_id = results[0].insertId
            }
            if (req.body.market_status === 'open') {
                if (typeof global.configFeatures.private_auction_email !== 'undefined') {
                    if (
                        parseInt(global.configFeatures.private_auction_email.enabled, 10) === 1 &&
                        req.body.selltype
                    ) {
                        req.body.refer_id = req.body.auction_id
                        req.body.refer_field = global.configFeatures.private_auction_email.cat_name
                        req.body.type = 'private_auction_email'

                        const [notificationResponse] = await Promise.all([
                            commonFunction.notifycheck(req),
                        ])
                        if (notificationResponse.length === 0) {
                            await Promise.all([commonFunction.notifyinsert(req)])
                        }
                    }
                }
            }

            await Promise.all([adminAuctionModule.emptyOutAuctionID(req.body.auction_id)])
            if (
                req.body.project_id &&
                ((Array.isArray(req.body.project_id) && req.body.project_id.length > 0) ||
                    (!Array.isArray(req.body.project_id) && req.body.project_id !== ''))
            ) {
                await Promise.all([adminAuctionModule.auctionProjectUpdateexist(req)])
            }
            await reConfigureEndTime(req, req.body.auction_id, true)
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        } finally {
            const responseData = {
                auction_id: req.body.auction_id,
            }
            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
            req.body.id = commonFunction.getValidID(req.body.id)

            req.body.filters = req.body.filters ? req.body.filters : {}
            req.body.filters.id = { value: id, field: 'ac.id', type: 'in' }

            let [records] = await Promise.all([adminAuctionModule.fetchAuctionsAll(req, 0)])

            records = await shortDescribeSCH(records)
            records = await getAssociatedProjects(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(req, auctionId, true)
                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)])
                    if (typeof global.configFeatures.auction_removed_notification !== 'undefined') {
                        if (
                            parseInt(
                                global.configFeatures.auction_removed_notification.enabled,
                                10,
                            ) === 1
                        ) {
                            req.body.refer_id = req.body.auction_id
                            req.body.refer_field =
                                global.configFeatures.auction_removed_notification.cat_name
                            req.body.type = 'auction_removed_notification'
                            req.body.isCommon = 1
                            req.body.notification_id = 0
                            await Promise.all([commonFunction.notifyinsert(req)])
                        }
                    }
                }
                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', '')
    //     }
    // },
}