admin/controllers/report/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 */
/* eslint-disable consistent-return */
const jwt = require('jsonwebtoken')
const _ = require('underscore')

const adminReportModule = require('../../modules/report').default
const schemaModule = require('./schema').default
const commonFunction = require('../../../common/function').default

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

const getdynamicinnercontents = async (req, sortValues, 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
}

/**
 * Get the reports data
 *
 * @memberOf adminside.report
 * @param {adminReportModule.userRelatedReport} modules
 * @param {adminReportModule.productRelatedReport} modules
 * @param {adminReportModule.allVehicleListUser} modules
 * @param {adminReportModule.employeeRelatedExport} modules
 */
const getRelatedBodyDetails = async (req, typeExport) => {
    let replaceObjects = {}
    let topheading = ''
    let records = []
    let totalRecords = []
    let type = req.body.report
    console.log('type', type)
    try {
        if (typeExport === 'report') {
            if (type.indexOf('user_management') !== -1) {
                type = type.split('_user_management')[0]
                console.log('type', type)
                switch (type) {
                    case 'deactivate':
                        topheading = 'DEACTIVE USERS'
                        break
                    case 'active':
                        topheading = 'ACTIVE USERS'
                        break
                    default:
                        topheading = 'ALL USERS'
                        break
                }
                replaceObjects = {
                    id: { name: 'User ID', field: 'id', type: '' },
                    user_fullname: { name: 'User Name', field: 'user_fullname', type: '' },
                    email: { name: ' User Email', field: 'email', type: '' },
                    phone: { name: 'Phone Number', field: 'phone', type: '' },
                    created_username: { name: 'Created By', field: 'created_username', type: '' },
                    created_at: { name: ' Created Date', field: 'created_at', type: 'datetime' },
                    last_login: { name: 'Last Login', field: 'last_login', type: 'datetime' },
                    status: { name: 'Status', field: 'status', type: 'capitalize' },
                }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.userRelatedReport(req, type, 0),
                        adminReportModule.userRelatedReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.userRelatedReport(req, type, 2),
                    ])
                }
            } else if (type === 'buyerhistory') {
                topheading = type === 'buyerhistory' ? 'Dealer History' : ''
                replaceObjects = {
                    bhbuyer_name: { name: 'Dealer Email', field: 'buyeremail', type: '' },
                    bhup_id: { name: 'Vehicle ID', field: 'id', type: '' },
                    bhupc_name: { name: 'Vehicle Name', field: 'title', type: '' },
                    bhpbid_amt: { name: 'Bid Amount', field: 'amount', type: 'price' },
                    bhbid_count: { name: 'No. of Bidders', field: 'totalbids', type: 'bids' },
                    bhp_status: { name: 'Status', field: 'paid', type: '' },
                    bhsold_date: { name: 'Sold Date', field: 'buy_sold_date', type: 'date' },
                }
                const [reportData] = await Promise.all([adminReportModule.userRelatedReport(req)])
                records = reportData
            } else if (type.indexOf('_product_management') !== -1) {
                type = type.split('_product_management')[0]
                switch (type) {
                    case 'active':
                        topheading = 'ACTIVE PROJECTS'
                        break
                    case 'closed':
                        topheading = 'CLOSED PROJECTS'
                        break
                    case 'draft':
                        topheading = 'DRAFT PROJECTS'
                        break
                    case 'sold':
                        topheading = 'SOLD PROJECTS'
                        break
                    case 'ending':
                        topheading = 'ENDING PROJECTS'
                        break
                    default:
                        topheading = 'ALL PROJECTS'
                        break
                }
                replaceObjects = {
                    id: { name: 'ID', field: 'id', type: '' },
                    title: { name: 'Title', field: 'title', type: '' },
                    date_added: { name: 'Starting Date', field: 'date_added', type: 'datetime' },
                    date_closed: { name: 'End Date', field: 'date_closed', type: 'datetime' },
                    sprice: { name: 'Starting Price', field: 'sprice', type: 'price' },
                    rprice: { name: 'Reserve Price', field: 'rprice', type: 'price' },
                    buynowamount: { name: 'Sold Price', field: 'buynowamount', type: 'price' },
                    wprice: { name: 'Current Price', field: 'wprice', type: 'price' },
                    buynowemail: { name: 'Buyer Email', field: 'buynowemail', type: '' },
                    winemail: { name: 'Winner Email', field: 'winemail', type: '' },
                    market_status: { name: 'Status', field: 'market_status', type: 'capitalize' },
                    paid_date: { name: 'Paid Date', field: 'paid_date', type: 'datetime' },
                    common_invoice: { name: 'Invoice ID', field: 'common_invoice', type: '' },
                    totalbids: { name: 'No. of Bids', field: 'totalbids', type: '' },
                    winnerName: { name: 'Buyer Name', field: 'winnerName', type: '' },
                    numDiffBidders: {
                        name: 'No. of Different Bidders',
                        field: 'numDiffBidders',
                        type: 'bidders',
                    },
                    bidderInfo: { name: 'Bidder Information', field: 'bidderInfo', type: '' },
                }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.productRelatedReport(req, type, 0),
                        adminReportModule.productRelatedReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.productRelatedReport(req, type, 2),
                    ])
                }
            }
        } else if (typeExport === 'export') {
            if (
                type === 'livevehiclesuser' ||
                type === 'allvehiclesuser' ||
                type === 'futurevehiclesuser'
            ) {
                replaceObjects = [
                    { name: 'ID', field: 'id', type: '' },
                    { name: 'Name', field: 'title', type: '' },
                    { name: 'VIN', field: 'gi_vin', type: '' },
                    { name: 'Year', field: 'gi_year', type: '' },
                    { name: 'Mileage', field: 'gi_mileage', type: '' },
                    { name: 'Make', field: 'gi_make', type: '' },
                    { name: 'Model', field: 'gi_model', type: '' },
                    { name: 'Start Date', field: 'date_added', type: 'date' },
                    { name: 'Close Date', field: 'date_closed', type: 'date' },
                ]
                if (type === 'livevehiclesuser') {
                    const [reportData] = await Promise.all([
                        adminReportModule.allVehicleListUser(req, 'live'),
                    ])
                    records = reportData
                } else if (type === 'allvehiclesuser') {
                    const [reportData] = await Promise.all([
                        adminReportModule.allVehicleListUser(req, 'all'),
                    ])
                    records = reportData
                } else {
                    const [reportData] = await Promise.all([
                        adminReportModule.allVehicleListUser(req, 'future'),
                    ])
                    records = reportData
                }
            } else if (type === 'alllogsemail') {
                replaceObjects = [
                    { name: 'ID', field: 'id', type: '' },
                    { name: 'Email', field: 'email', type: '' },
                    { name: 'Subject', field: 'subject', type: '' },
                    { name: 'Date', field: 'date_sent', type: 'date' },
                ]
                const [reportData] = await Promise.all([adminReportModule.allEmailLogsAdmin()])
                records = reportData
            } else if (type === 'alltemplatessms' || type === 'alltemplatesemail') {
                replaceObjects = [
                    { name: 'ID', field: 'id', type: '' },
                    { name: 'Title', field: 'title', type: '' },
                    { name: 'English Subject', field: 'for_english_subject', type: '' },
                    { name: 'English Template', field: 'for_english_template', type: 'html' },
                    { name: 'Spanish Subject', field: 'for_spanish_subject', type: '' },
                    { name: 'Spanish Template', field: 'for_spanish_template', type: 'html' },
                    { name: 'Method', field: 'method', type: '' },
                ]
                if (type === 'alltemplatessms') {
                    const [reportData] = await Promise.all([
                        adminReportModule.allTemplatesAdmin('sms'),
                    ])
                    records = reportData
                } else {
                    const [reportData] = await Promise.all([
                        adminReportModule.allTemplatesAdmin('email'),
                    ])
                    records = reportData
                }
            } else if (
                type === 'usersactive' ||
                type === 'usersdisapprove' ||
                type === 'usersall' ||
                type === 'employeeall'
            ) {
                replaceObjects = [
                    { name: 'User ID', field: 'id', type: '' },
                    { name: 'User Name', field: 'user_fullname', type: '' },
                    { name: ' User Email', field: 'email', type: '' },
                    { name: 'Phone Number', field: 'phone', type: '' },
                    { name: 'User Role', field: 'user_type', type: 'role' },
                    { name: 'Created By', field: 'created_username', type: '' },
                    { name: ' Created Date', field: 'created_at', type: 'date' },
                    { name: 'Last Login', field: 'last_login', type: 'date' },
                    { name: 'Status', field: 'status', type: '' },
                ]
                if (type === 'usersdisapprove') {
                    const [reportData] = await Promise.all([
                        adminReportModule.userRelatedExport('deactivate'),
                    ])
                    records = reportData
                } else if (type === 'usersactive') {
                    const [reportData] = await Promise.all([
                        adminReportModule.userRelatedExport('active'),
                    ])
                    records = reportData
                } else if (type === 'usersall') {
                    const [reportData] = await Promise.all([
                        adminReportModule.userRelatedExport('all'),
                    ])
                    records = reportData
                } else if (type === 'employeeall') {
                    const [reportData] = await Promise.all([
                        adminReportModule.employeeRelatedExport('all'),
                    ])
                    records = reportData
                }
            }
        }
        return [replaceObjects, records, totalRecords, topheading]
    } catch (e) {
        console.error(e)
    }
}
/**
 * Get the reports headers
 *
 * @memberOf adminside.report
 * @param {object} body all data
 * @param {object} headers all header values
 */
const getHeaderValues = async (body, headers) => {
    const headerstoshow = []
    const fieldstoshow = []
    const fieldstochange = []
    console.log('body', body)
    headers = _.omit(headers, (value, key, object) => {
        if (!_.contains(body, key)) {
            return true
        }
    })

    _.each(headers, function (val) {
        headerstoshow.push(val.name)
        fieldstoshow.push(val.field)
        fieldstochange.push({
            field: val.field,
            type: val.type,
        })
    })
    return [headerstoshow, fieldstoshow, fieldstochange]
}

module.exports = {
    /**
     * Download Report
     *
     * @memberOf adminside.report
     * @param {adminside.report.getRelatedBodyDetails} modules
     * @param {adminside.report.getHeaderValues} modules
     */
    downloadReport: async (req, res) => {
        try {
            let reportRequired
            let data
            let head
            let field
            let totalRecords
            let topheading
            let fieldchange
            const page = req.body.page ? 1 : req.body.page
            const perpage = req.body.perpage ? 10 : req.body.perpage

            try {
                ;[reportRequired, data, totalRecords, topheading] = await getRelatedBodyDetails(
                    req,
                    'report',
                )
                ;[head, field, fieldchange] = await getHeaderValues(req.body.fields, reportRequired)
                console.log('fieldchange', fieldchange)
                console.log('head', head)
                console.log('field', field)

                data = _.map(data, (val) => {
                    val = _.omit(val, (value, key) => {
                        if (!_.contains(field, key)) {
                            return true
                        }
                        return false
                    })

                    val = _.map(fieldchange, function (valhead) {
                        if (val[valhead.field]) {
                            if (valhead.type === 'date') {
                                return `"${commonFunction.dateFormatFunction(val[valhead.field])}"`
                            }
                            if (valhead.type === 'datetime') {
                                return `"${commonFunction.dateTimeFormatFunction(
                                    val[valhead.field],
                                )}"`
                            }
                            if (valhead.type === 'capitalize') {
                                return `"${commonFunction.capitalize(val[valhead.field])}"`
                            }
                            if (valhead.type === 'price') {
                                return `"${commonFunction.currencyFormat(val[valhead.field])}"`
                            }
                            return `"${val[valhead.field]}"`
                        }
                        return '-'
                    })
                    return val.join(',')
                })
            } finally {
                const lbreak = '\n'
                let csvContent = head.join(',')
                csvContent += lbreak
                csvContent += data.join(lbreak)
                topheading = topheading.replace(/ /g, '_').toLowerCase()
                const responseData = {
                    filename: `${topheading}.csv`,
                    records: csvContent,
                }
                jsonResponse(res, 'success', {
                    responseType: 1,
                    message: 'Details successfully retrieved!',
                    responseData,
                })
                // res.setHeader('Content-disposition', 'attachment; filename=sellerreports.csv')
                // res.set('Content-Type', 'application/octet-stream')
                // res.send(csvContent)
            }
        } catch (e) {
            console.error(e)
            jsonResponse(res, 'error', {
                responseType: 3,
                message: 'Internal Server error!',
            })
        }
    },
    /**
     * Display Report
     *
     * @memberOf adminside.report
     * @param {adminside.report.getRelatedBodyDetails} modules
     * @param {adminside.report.getHeaderValues} modules
     */
    displayReport: async (req, res) => {
        try {
            let reportRequired
            let records
            let totalRecords
            let head
            let field
            let topheading
            let fieldchange
            const page = req.body.page ? 1 : req.body.page
            const perpage = req.body.perpage ? 10 : req.body.perpage
            console.log(req.body)
            try {
                ;[reportRequired, records, totalRecords, topheading] = await getRelatedBodyDetails(
                    req,
                    'report',
                )
                ;[head, field, fieldchange] = await getHeaderValues(req.body.fields, reportRequired)
                console.log('DATA: ', records)
                console.log('fieldchange', fieldchange)
                console.log('head', head)
                console.log('field', field)
            } finally {
                console.log('data', records)
                let responseData = {
                    topheading,
                    heading: head,
                    records,
                    totalRecords,
                    requests: req.body,
                    reportRequired: _.keys(reportRequired),
                }
                console.log('totalRecords', totalRecords)
                responseData = await getdynamicinnercontents(req, null, 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!',
            })
        }
    },
}