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 commonCustomFunction = require('../../../../../custom/common/function').default
const commonFunction = require('../../../common/function').default

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

const getdynamicinnercontents = async (req, sortValues, responseData) => {
    const returnResponse = responseData
    returnResponse.totalRecords = returnResponse.totalRecords.length
        ? 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)
    req.body.fields = req.body.fields ? req.body.fields : []
    try {
        replaceObjects = {}

        await commonFunction.asyncForEach(req.body.fields, (field) => {
            if (typeof field === 'object' && field !== null) {
                replaceObjects[field] = {
                    name:
                        field.name ||
                        field.field
                            .split('_')
                            .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                            .join(' '),
                    field: field.field,
                    type: field.type || '',
                    table: field.table || null,
                }
            } else {
                replaceObjects[field] = {
                    name: field
                        .split('_')
                        .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
                        .join(' '),
                    field,
                    type: '',
                }
            }
        })

        if (typeExport === 'report' || typeExport === 'export') {
            if (type.indexOf('user_management') !== -1) {
                type = type.split('_user_management')[0]
                switch (type) {
                    case 'deactivate':
                        topheading = 'DEACTIVE USERS'
                        break
                    case 'active':
                        topheading = 'ACTIVE USERS'
                        break
                    case 'unverified':
                        topheading = 'UNVERIFIED USERS'
                        break
                    default:
                        topheading = 'ALL USERS'
                        break
                }

                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              ...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',
                                  },
                                  interested_categories: {
                                      name: 'Interested Categories',
                                      field: 'interested_categories',
                                      type: '',
                                  },
                                  public_figure_type: {
                                      name: 'Interested Public Figure Type',
                                      field: 'public_figure_type',
                                      type: '',
                                  },
                                  preferred_price_range: {
                                      name: 'Preferred Price Range',
                                      field: 'preferred_price_range',
                                      type: '',
                                  },
                                  select_public_figure: {
                                      name: 'Selected Public Figures',
                                      field: 'select_public_figure',
                                      type: '',
                                  },
                                  last_login: {
                                      name: 'Last Login',
                                      field: 'last_login',
                                      type: 'datetime',
                                  },
                                  status: { name: 'Status', field: 'status', type: 'capitalize' },
                              },
                          }
                        : { ...replaceObjects }

                if (req.body.action === 'display') {
                    // console.log('req.body.action', req, 'typeeeee', type)
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.userRelatedReport(req, type, 0),
                        adminReportModule.userRelatedReport(req, type, 1),
                    ])
                    // console.log('records', records, 'totalrecoo', totalRecords)
                } 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 'open':
                        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
                }

                if (typeof global.configFeatures.lot_id_report !== 'undefined') {
                    if (parseInt(global.configFeatures.lot_id_report.enabled, 10) === 1) {
                        replaceObjects.lotId = {
                            name: 'Lot ID',
                            field: 'lot_no',
                            type: '',
                        }
                    }
                }

                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              ...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: '',
                                  },
                                  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: '',
                                  },
                                  winemail: { name: 'Winner Email', field: 'winemail', type: '' },
                              },
                          }
                        : { ...replaceObjects }

                if (typeof global.configFeatures.project_follow_count !== 'undefined') {
                    if (parseInt(global.configFeatures.project_follow_count.enabled, 10) === 1) {
                        replaceObjects = {
                            ...replaceObjects,
                            followCount: {
                                name: 'No. of followers',
                                field: 'followCount',
                                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 (type === 'sold_order') {
                topheading = 'SOLD ORDER'

                if (typeof global.configFeatures.lot_id_report !== 'undefined') {
                    if (parseInt(global.configFeatures.lot_id_report.enabled, 10) === 1) {
                        replaceObjects.lotId = {
                            name: 'Lot ID',
                            field: 'lot_no',
                            type: '',
                        }
                    }
                }

                replaceObjects = {
                    project_id: { name: 'Product ID', field: 'project_id', type: '' },
                    common_invoice: { name: 'Invoice ID', field: 'common_invoice', type: '' },
                    title: { name: 'Title', field: 'title', type: 'capitalize' },
                    winnerName: { name: 'Buyer Name', field: 'winnerName', type: '' },
                    buynowemail: { name: 'Buyer Email', field: 'buynowemail', type: '' },
                    sold_qty: { name: 'Purchased Qty', field: 'sold_qty', type: '' },
                    buynowamount: { name: 'Sold Price', field: 'buynowamount', type: 'price' },
                    totalbids: { name: 'No. of Bidders', field: 'totalbids', type: 'bids' },
                    numDiffBidders: {
                        name: 'No. of Different Bidders',
                        field: 'numDiffBidders',
                        type: 'bidders',
                    },
                    date_added: { name: 'Sale Date', field: 'date_added', type: 'date' },
                    market_status: { name: 'Status', field: 'market_status', type: 'capitalize' },
                    paid: { name: 'Paid Status', field: 'paid', type: 'paid_status' },
                    paid_date: { name: 'Paid Date', field: 'paid_date', type: 'date' },
                    total_invoice: { name: 'Total Amount', field: 'total_invoice', type: 'price' },
                }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.productRelatedSoldReport(req, type, 0),
                        adminReportModule.productRelatedSoldReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.productRelatedSoldReport(req, type, 2),
                    ])
                }
            } else if (type === 'employee_list') {
                topheading = 'EMPLOYEE DETAILS'
                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              ...replaceObjects,
                              emp_firstname: {
                                  name: 'First Name',
                                  field: 'emp_firstname',
                                  type: 'capitalize',
                              },
                              emp_lastname: {
                                  name: 'Last Name',
                                  field: 'emp_lastname',
                                  type: 'capitalize',
                              },
                              emp_type: {
                                  name: 'Employee Type',
                                  field: 'emp_type',
                                  type: 'em_type',
                              },
                              emp_email: { name: 'Email', field: 'emp_email', type: '' },
                              emp_phone: { name: 'Phone Number', field: 'emp_phone', type: '' },
                              emp_address1: {
                                  name: 'Address',
                                  field: 'emp_address1',
                                  type: 'capitalize',
                              },
                              emp_city: { name: 'City', field: 'emp_city', type: '' },
                              emp_zip: { name: 'Zip Code', field: 'emp_zip', type: '' },
                              emp_state: { name: 'State', field: 'emp_state', type: 'capitalize' },
                              emp_country: {
                                  name: 'Country',
                                  field: 'emp_country',
                                  type: 'capitalize',
                              },
                          }
                        : { ...replaceObjects }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.employeeReport(req, type, 0),
                        adminReportModule.employeeReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([adminReportModule.employeeReport(req, type, 2)])
                }
            } else if (type === 'total_amount') {
                topheading = 'TOTAL AMOUNT'
                replaceObjects = {
                    payment_status: { name: 'Payment Status', field: 'payment_status', type: '' },
                    total: { name: 'Total Amount', field: 'total', type: '' },
                }
                const [[paid], [unpaid]] = await Promise.all([
                    adminReportModule.totalAmountInviceReport(req, 'paid'),
                    adminReportModule.totalAmountInviceReport(req, 'unpaid'),
                ])
                const table = { ...paid, ...unpaid }
                const result = []
                // for (const key in table) {
                //     result.push({ payment_status: key, total: table[key] })
                // }
                Object.keys(table).forEach((key) => {
                    result.push({ payment_status: key, total: table[key] })
                })
                records = result
            } else if (type === 'deposit_balance') {
                topheading = 'WALLET DETAILS'

                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: '' },
                    last_login: { name: 'Last Login', field: 'last_login', type: 'datetime' },
                    status: { name: 'Status', field: 'status', type: 'capitalize' },
                    deposit_amount: {
                        name: 'Wallet Amount',
                        field: 'deposit_amount',
                        type: 'price',
                    },
                }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.userDepositReport(req, type, 0),
                        adminReportModule.userDepositReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.userDepositReport(req, type, 2),
                    ])
                }
            } else if (type === 'transaction_list') {
                topheading = 'TRANSACTION DETAILS'

                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              common_invoice: {
                                  name: 'Invoice ID',
                                  field: 'common_invoice',
                                  type: '',
                              },
                              trans_id: { name: 'Transaction ID', field: 'trans_id', type: '' },
                              amount: { name: 'Amount', field: 'amount', type: 'price' },
                              user_fullname: {
                                  name: 'Buyer Name',
                                  field: 'user_fullname',
                                  type: 'capitalize',
                              },
                              email: { name: ' Buyer Email', field: 'email', type: '' },
                              payment_method: {
                                  name: 'Payment Type',
                                  field: 'payment_method',
                                  type: 'capitalize',
                              },
                              card_type: {
                                  name: 'Gateway',
                                  field: 'card_type',
                                  type: 'capitalize',
                              },
                              created_at: {
                                  name: 'Paid Date',
                                  field: 'created_at',
                                  type: 'datetime',
                              },
                          }
                        : { ...replaceObjects }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.userTranscationReport(req, type, 0),
                        adminReportModule.userTranscationReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.userTranscationReport(req, type, 2),
                    ])
                }
            } else if (type.indexOf('_auction_management') !== -1) {
                type = type.split('_auction_management')[0]
                switch (type) {
                    case 'active':
                        topheading = 'ACTIVE AUCTION'
                        break
                    case 'open':
                        topheading = 'ACTIVE AUCTION'
                        break
                    case 'closed':
                        topheading = 'CLOSED AUCTION'
                        break
                    case 'draft':
                        topheading = 'DRAFT AUCTION'
                        break
                    case 'sold':
                        topheading = 'SOLD AUCTION'
                        break
                    case 'ending':
                        topheading = 'ENDING AUCTION'
                        break
                    default:
                        topheading = 'ALL AUCTION'
                        break
                }
                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              auctionid: { name: 'Auction ID', field: 'auctionid', type: '' },
                              auction_title: {
                                  name: 'Auction Title',
                                  field: 'auction_title',
                                  type: 'capitalize',
                              },
                              auction_description: {
                                  name: 'Auction Description',
                                  field: 'auction_description',
                                  type: 'capitalize',
                              },
                              auction_date_added: {
                                  name: 'Auction Start Date',
                                  field: 'auction_date_added',
                                  type: 'date',
                              },
                              auction_date_closed: {
                                  name: 'Auction End Date',
                                  field: 'auction_date_closed',
                                  type: 'date',
                              },
                              auction_status: {
                                  name: 'Auction Status',
                                  field: 'auction_status',
                                  type: 'capitalize',
                              },
                              lot_id: { name: 'Lot ID', field: 'lot_id', type: '' },
                              lot_title: {
                                  name: 'Lot Title',
                                  field: 'lot_title',
                                  type: 'capitalize',
                              },
                              lot_date_added: {
                                  name: 'Lot Starting Date',
                                  field: 'lot_date_added',
                                  type: 'date',
                              },
                              lot_date_closed: {
                                  name: 'Lot End Date',
                                  field: 'lot_date_closed',
                                  type: 'date',
                              },
                              sprice: { name: 'Starting Price', field: 'sprice', type: 'price' },
                              rprice: { name: 'Reserve Price', field: 'rprice', type: 'price' },
                              bprice: { name: 'buynow Price', field: 'bprice', type: 'price' },
                              qty: { name: 'Total Quantity', field: 'qty', type: '' },
                              sold: { name: 'Sold Quantity', field: 'sold', type: '' },
                              wprice: { name: 'Current Price', field: 'wprice', type: 'price' },
                              totalbids: {
                                  name: 'No. of Bidders',
                                  field: 'totalbids',
                                  type: 'bids',
                              },
                              p_status: {
                                  name: 'Lot Status',
                                  field: 'lot_status',
                                  type: 'capitalize',
                              },
                          }
                        : { ...replaceObjects }
                if (typeof global.configFeatures.auction_follow_count !== 'undefined') {
                    if (parseInt(global.configFeatures.auction_follow_count.enabled, 10) === 1) {
                        replaceObjects = {
                            ...replaceObjects,
                            followCount: {
                                name: 'No. of followers',
                                field: 'followCount',
                                type: '',
                            },
                        }
                    }
                }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.productRelatedAuctionLotReport(req, type, 0),
                        adminReportModule.productRelatedAuctionLotReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.productRelatedAuctionLotReport(req, type, 2),
                    ])
                }
            } else if (type.indexOf('_invoice_management') !== -1) {
                type = type.split('_invoice_management')[0]
                switch (type) {
                    case 'paid':
                        topheading = 'PAID INVOICE'
                        break
                    case 'unpaid':
                        topheading = 'UNPAID INVOICE'
                        break
                    case 'partial_paid':
                        topheading = 'PARTIAL PAID INVOICE'
                        break
                    default:
                        topheading = 'ALL INVOICE'
                        break
                }
                replaceObjects =
                    typeof req.body.isDefault === 'undefined' || req.body.isDefault
                        ? {
                              ...replaceObjects,
                              common_invoice: {
                                  name: 'Invoice ID',
                                  field: 'common_invoice',
                                  type: '',
                              },
                              sold_qty: { name: 'Purchased Qty', field: 'sold_qty', type: 'price' },
                              buynowamount: {
                                  name: 'Sold Price',
                                  field: 'buynowamount',
                                  type: 'price',
                              },
                              shipping_amount: {
                                  name: 'Shipping Price',
                                  field: 'shipping_amount',
                                  type: 'price',
                              },
                              total_invoice: {
                                  name: 'Total Amount',
                                  field: 'total_invoice',
                                  type: 'price',
                              },
                              date_added: { name: 'Sold Date', field: 'date_added', type: 'date' },
                              paid_date: { name: 'Paid Date', field: 'paid_date', type: 'date' },
                              paid: { name: 'Paid Status', field: 'paid', type: 'paid_status' },
                              winnerName: {
                                  name: 'Buyer Name',
                                  field: 'winnerName',
                                  type: 'capitalize',
                              },
                              winnerEmail: {
                                  name: 'Buyer Email',
                                  field: 'winnerEmail',
                                  type: 'capitalize',
                              },
                              winnerCompany: {
                                  name: 'Buyer Company',
                                  field: 'winnerCompany',
                                  type: 'capitalize',
                              },
                          }
                        : { ...replaceObjects }
                if (req.body.action === 'display') {
                    ;[records, totalRecords] = await Promise.all([
                        adminReportModule.productRelatedInvoiceReport(req, type, 0),
                        adminReportModule.productRelatedInvoiceReport(req, type, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([
                        adminReportModule.productRelatedInvoiceReport(req, type, 2),
                    ])
                }
            } else if (type.indexOf('all_paid_reports') !== -1) {
                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: '' },
                    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: '' },
                    auctionid: { name: 'Auction Id', field: 'auctionid', 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.allPaidReports(req, 0),
                        adminReportModule.allPaidReports(req, 1),
                    ])
                } else {
                    ;[records] = await Promise.all([adminReportModule.allPaidReports(req, 2)])
                }
            } else if (type === 'bid_history') {
                topheading = 'BID HISTORY'
                replaceObjects = {
                    date: { name: 'Date', field: 'created_at', type: 'datetime' },
                    user_id: { name: 'User ID', field: 'user_id', type: '' },
                    users_first_name: {
                        name: 'User Name',
                        field: 'users_first_name',
                        type: '',
                    },
                    proposed_amount: { name: 'Amount', field: 'proposed_amount', type: 'price' },
                }
                const [reportData] = await Promise.all([adminReportModule.bidHistory(req)])
                records = reportData
            }
        } 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]
}

const getHeaderValuesExport = async (body, headers) => {
    const headerstoshow = []
    const fieldstoshow = []
    const fieldstochange = []

    _.each(headers, function (val) {
        headerstoshow.push(val.name)
        fieldstoshow.push(val.field)
        fieldstochange.push({
            field: val.field,
            type: val.type,
            table: val.table || null,
        })
    })
    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
            req.body.action = 'export'
            try {
                ;[reportRequired, data, totalRecords, topheading] = await getRelatedBodyDetails(
                    req,
                    'report',
                )
                ;[head, field, fieldchange] = await getHeaderValues(req.body.fields, reportRequired)

                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 `"${commonCustomFunction.dateFormatFunction(
                                    val[valhead.field],
                                )}"`
                            }
                            if (valhead.type === 'datetime') {
                                return `"${commonCustomFunction.dateTimeFormatFunction(
                                    val[valhead.field],
                                )}"`
                            }
                            if (valhead.type === 'capitalize') {
                                return `"${commonCustomFunction.capitalize(val[valhead.field])}"`
                            }
                            if (valhead.type === 'paid_status') {
                                let paidStatus = ''
                                if (val[valhead.field] === 1) {
                                    paidStatus = 'Paid'
                                } else {
                                    paidStatus = 'UnPaid'
                                }
                                return `"${commonCustomFunction.capitalize(paidStatus)}"`
                            }
                            if (valhead.type === 'em_type') {
                                let empStatus = ''
                                if (val[valhead.field] === 'super_admin') {
                                    empStatus = 'Super admin'
                                } else if (val[valhead.field] === 'admin') {
                                    empStatus = 'Admin'
                                } else {
                                    empStatus = 'Employee'
                                }
                                return `"${commonCustomFunction.capitalize(empStatus)}"`
                            }
                            if (valhead.type === 'price') {
                                return `"${commonCustomFunction.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, 'req.body')
            try {
                ;[reportRequired, records, totalRecords, topheading] = await getRelatedBodyDetails(
                    req,
                    'report',
                )
                ;[head, field, fieldchange] = await getHeaderValues(req.body.fields, reportRequired)
            } finally {
                let responseData = {
                    topheading,
                    heading: head,
                    records,
                    totalRecords,
                    requests: req.body,
                    reportRequired: _.keys(reportRequired),
                }

                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!',
            })
        }
    },
    /**
     * Download Report
     *
     * @memberOf adminside.report
     * @param {adminside.report.getRelatedBodyDetails} modules
     * @param {adminside.report.getHeaderValues} modules
     */
    exportReport: 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,
                    'export',
                )
                ;[head, field, fieldchange] = await getHeaderValuesExport(
                    req.body.fields,
                    reportRequired,
                )

                data = _.map(data, (val) => {
                    val = _.map(fieldchange, function (valhead) {
                        if (val[valhead.field]) {
                            if (valhead.type === 'table') {
                                const [tableValue] = global.configurations.tableValues[
                                    valhead.table.name
                                ].filter((tab) => {
                                    if (tab[valhead.table.idField] === val[valhead.field]) {
                                        return true
                                    }
                                    return false
                                })
                                return `"${
                                    tableValue ? tableValue[valhead.table.fetchField] : '-'
                                } "`
                            }

                            if (valhead.type === 'date') {
                                return `"${commonCustomFunction.dateFormatFunction(
                                    val[valhead.field],
                                )}"`
                            }
                            if (valhead.type === 'datetime') {
                                return `"${commonCustomFunction.dateTimeFormatFunction(
                                    val[valhead.field],
                                )}"`
                            }
                            if (valhead.type === 'capitalize') {
                                return `"${commonCustomFunction.capitalize(val[valhead.field])}"`
                            }
                            if (valhead.type === 'paid_status') {
                                let paidStatus = ''
                                if (val[valhead.field] === 1) {
                                    paidStatus = 'Paid'
                                } else {
                                    paidStatus = 'UnPaid'
                                }
                                return `"${commonCustomFunction.capitalize(paidStatus)}"`
                            }
                            if (valhead.type === 'em_type') {
                                let empStatus = ''
                                if (val[valhead.field] === 'super_admin') {
                                    empStatus = 'Super admin'
                                } else if (val[valhead.field] === 'admin') {
                                    empStatus = 'Admin'
                                } else {
                                    empStatus = 'Employee'
                                }
                                return `"${commonCustomFunction.capitalize(empStatus)}"`
                            }
                            if (valhead.type === 'price') {
                                return `"${commonCustomFunction.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!',
            })
        }
    },
}