admin/modules/invoice.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  # ||
|| # ---------------------------------------------------------------------- # ||
|| ########################################################################## ||
\* ============================================================================ */

const dateFormat = require('dateformat')
const md5 = require('md5')
const _ = require('underscore')
const moment = require('moment')

const mysqclass = require('./mysqli').default
const commonProduct = require('../../common/products').default
/**
 * @class class to handle invoice functions
 */
class adminInvoiceModule {
    /**
     * Get All Invoices
     * @param {object} req request data
     * @param {string} count count for the pagination
     * @returns {object} sql response
     */
    static async fetchInvoicesAll(req, count) {
        const mysql = {}
        mysql.where = ''
        const { action } = req.body
        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        if (action === 'paid') {
            mysql.where += 'and pc.cart_paid = 1'
        } else if (action === 'unpaid') {
            mysql.where += 'and pc.cart_paid = 0'
        }

        mysql.order = 'order by pc.id desc'
        const order = req.body.order === '' ? 'asc' : req.body.order
        const orderby = req.body.orderby === '' && !req.body.orderby ? '' : req.body.orderby
        if (orderby !== '') {
            mysql.order = ` order by ${orderby} ${order}`
        }
        if (req.body.searchterm !== '' && req.body.searchterm !== undefined) {
            let changed = req.body.searchterm.replace(/\\/g, '\\\\\\\\')
            changed = changed.replace(/"/g, '\\"')
            mysql.where += ` and (bn.common_invoice like "%${changed}%")`
        }
        const dateSortValue = req.body.fielddate ? req.body.fielddate : 'pc.cart_paiddate'
        if (req.body.fromdate !== '' && req.body.fromdate !== undefined) {
            const date1 = dateFormat(
                new Date(
                    moment(req.body.fromdate, global.configurations.variables.time_format).format(),
                ),
                'yyyy-mm-dd',
            )
            mysql.where += ` and ${dateSortValue} >= "${date1} 00:00:00"`
        }
        if (req.body.todate !== '' && req.body.todate !== undefined) {
            const date2 = dateFormat(
                new Date(
                    moment(req.body.todate, global.configurations.variables.time_format).format(),
                ),
                'yyyy-mm-dd',
            )
            mysql.where += ` and ${dateSortValue} <= "${date2} 23:59:59"`
        }

        let row = ''
        const pagen = (req.body.page - 1) * req.body.limit
        const limitf = ` limit ${pagen},${req.body.limit}`
        mysql.limit = limitf
        mysql.dateNow = dateNow
        const escapeData = []
        if (count === 1) {
            row = 'get_all_invoices_limit'
        } else {
            row = 'get_all_invoices'
        }
        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Update Invoice status
     * @param {string} status Status of which the invoice has to be updated
     * @param {number} pid Project ID which the invoice entry has to be updated
     * @returns {object} sql response
     */

    static async invoiceStatusUpdate(status, pid) {
        const mysql = {}
        let paidDate = null
        let statusInt = 0
        let partialInt = 0
        if (status === 'paid') {
            statusInt = 1
            partialInt = 1
            paidDate = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        } else if (status === 'unpaid') {
            statusInt = 0
            partialInt = 0
        } else if (status === 'draft') {
            statusInt = 0
            partialInt = 1
        }
        const escapeData = [statusInt, partialInt, paidDate, pid]
        const strQuery = await mysqclass.mysqli(mysql, 'invoice_change_status')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }

    /**
     * Update buynow Status
     * @param {string} status Status of which the invoice has to be updated
     * @param {number} pid Project ID which the buynow entry has to be updated
     * @returns {object} sql response
     */
    static async invoiceBuynowStatusUpdate(status, pid) {
        const mysql = {}
        let statusInt = 0
        if (status === 'paid') {
            statusInt = 1
        } else if (status === 'unpaid') {
            statusInt = 0
        }
        const escapeData = [statusInt, pid]
        const strQuery = await mysqclass.mysqli(mysql, 'invoice_buynow_change_status')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        console.log('dataReturn', dataReturn)
        return dataReturn
    }

    /**
     * Update buynow Status
     * @param {number} pid Project ID which the buynow entry has to be updated
     * @returns {object} sql response
     */
    static async invoiceBuynowUserId(pid) {
        const mysql = {}
        const escapeData = [pid]
        const strQuery = await mysqclass.mysqli(mysql, 'invoice_buynow_user_id')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * Update buynow Status
     * @param {string} action action that we have to perform
     * @param {number} pid Project ID which the buynow entry has to be updated
     * @returns {object} sql response
     */
    static async buynowPartialStatusUpdate(action, id) {
        const mysql = {}
        const partial = action === 'draft' ? 1 : 0
        const escapeData = [partial, id]
        const strQuery = await mysqclass.mysqli(mysql, 'move_to_unpaid')
        console.log(strQuery, escapeData)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * Update buynow Status
     * @param {string} action action that we have to perform
     * @param {number} pid Project ID which the buynow entry has to be updated
     * @returns {object} sql response
     */
    static async buynowActiveStatusUpdate(action, id) {
        const mysql = {}
        const escapeData = [id]
        const custom_users = global.configColumns.custom_users.ext_name
        mysql.custom_users = custom_users
        const strQuery = await mysqclass.mysqli(mysql, 'get_invoice_buynow_id')
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
    /**
     * Update buynow Status
     * @param {object} req request object
     * @param {number} count no of invoies to fetch
     * @returns {object} sql response
     */
    static async fetchInvoicesAllNew(req, count) {
        const mysql = {}
        const { action } = req.body

        const baseTableUsed = global.configColumns.buynow
        const customTableUsed = { enabled: 0 }

        let row = ''
        let where = ''
        let limitf = ''
        let order = ''

        if (action) {
            if (action === 'paid') {
                where += 'and b.paid = 1'
            } else if (action === 'unpaid' || action === 'partial') {
                where += 'and b.paid = 0 AND partial = 0'
            } else if (action === 'draft') {
                where += 'and b.paid = 0 AND partial = 1 '
            }
        }

        const dateNow = dateFormat(new Date(), 'yyyy-mm-dd HH:MM:ss')
        if (typeof req.body.limit === 'undefined') {
            req.body.limit = global.configurations.variables.search_limit || 25
        }
        if (typeof req.body.page === 'undefined') {
            req.body.page = 1
        }

        order = `order by b.common_invoice desc `
        if (req.body.orderby || req.body.order) {
            const sortReturn = commonProduct.sortOrderData(req, where)
            if (sortReturn.order) {
                order = sortReturn.order
            }
            if (sortReturn.where) {
                where += sortReturn.where
            }
        }

        if (req.body.similars) {
            where += commonProduct.similarData(req)
        }
        if (req.body.filters) {
            where += commonProduct.filterData(req)
        }

        const generatedData = commonProduct.generateJoinWithColum(baseTableUsed, customTableUsed, [
            'id',
        ])

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        mysql.mainTable = generatedData.mainTableJoin

        const additionalTable = global.configColumns.projects
        const customAdditionalTable = global.configColumns.custom_projects

        const additionalGeneratedData = commonProduct.additionalTableJoin(
            additionalTable,
            customAdditionalTable,
            baseTableUsed,
            'left join',
            'id',
            'project_id',
        )

        const additionalTableSecond = global.configColumns.auctionlot
        const customAdditionalTableSecond = { enabled: 0 }

        const additionalGeneratedDataSecond = commonProduct.additionalTableJoin(
            additionalTableSecond,
            customAdditionalTableSecond,
            additionalTable,
            'left join',
            'id',
            'auctionid',
        )

        row = count === 1 ? 'invoice_all_item_cnt' : 'invoice_all_item'

        const limitrg = req.body.limit
        let uidc = 0
        if (req.user) {
            uidc = typeof req.user.id === 'undefined' ? 0 : req.user.id
        }

        const escapeData = []
        if (count === 1) {
            limitf = ` `
        } else {
            let pagen = (req.body.page - 1) * limitrg
            if (parseInt(pagen, 10) < 0) {
                pagen = 0
            }
            limitf = ` limit ${pagen},${limitrg}`
        }

        mysql.userid = uidc
        mysql.order = order
        mysql.where = where
        mysql.limitf = limitf
        mysql.dateNow = dateNow
        mysql.groupby = 'group by b.common_invoice'

        mysql.customTableJoin = generatedData.customTableJoin
        mysql.columns = generatedData.rowstoFetch
        mysql.mainTable = generatedData.mainTableJoin

        const additionalTableThird = global.configColumns.users
        const customAdditionalTableThird = global.configColumns.custom_users

        const additionalGeneratedDataThird = commonProduct.additionalTableJoin(
            additionalTableThird,
            customAdditionalTableThird,
            baseTableUsed,
            'inner join',
            'id',
            'user_id',
        )

        mysql.customTableJoin = `${mysql.customTableJoin} ${additionalGeneratedData.customTableJoin}`
        mysql.columns = mysql.columns.concat(additionalGeneratedData.rowstoFetch)

        mysql.customTableJoin = `${mysql.customTableJoin} ${additionalGeneratedDataSecond.customTableJoin}`
        mysql.columns = mysql.columns.concat(additionalGeneratedDataSecond.rowstoFetch)

        mysql.customTableJoin = `${mysql.customTableJoin} ${additionalGeneratedDataThird.customTableJoin}`
        mysql.columns = mysql.columns.concat(additionalGeneratedDataThird.rowstoFetch)

        const strQuery = await mysqclass.mysqli(mysql, row)
        const dataReturn = await global.mysql.query(strQuery, escapeData)
        return dataReturn
    }
}

module.exports.default = adminInvoiceModule