/* ============================================================================ *\
|| ########################################################################## ||
|| # 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 request = require('request')
const productModule = require('../../modules/product').default
const commonFunction = require('../../../common/function').default
const schemaModule = require('./schema').default
const { jsonResponse, errorResponse } = require('../logger')
/**
* Sort values in the format for frontend
*
* @memberOf frontend.product
* @param {object} sortValues sortValues which has to be fetched
* @param {object} responseData All response which is to be filtered
*/
const getSortValues = async (sortValues, responseData) => {
const returnResponse = responseData
returnResponse.sorts = {}
const processAllItems = async (items) => {
const tableValue = global.configColumns[items]
if (tableValue.search && tableValue.enabled) {
returnResponse.sorts[`sort${tableValue.ext_name}`] = sortValues[0][
`sort${tableValue.ext_name}`
]
? sortValues[0][`sort${tableValue.ext_name}`].split(',')
: []
}
}
await commonFunction.asyncForEach(Object.keys(global.configColumns), async (element) => {
await processAllItems(element)
})
return returnResponse
}
const securitydata = async (message) => {
const crypto = require('crypto')
const fs = require('fs')
const ulrPath = `${global.path}public/private.key`
const ulrPath2 = `${global.path}public/publickey.cer`
const privateKey = fs.readFileSync(ulrPath, 'utf8')
const publicKey = fs.readFileSync(ulrPath2, 'utf8')
const RSASign = async (privateKeyRSA, data) => {
const sign = crypto.createSign('RSA-SHA1')
sign.update(data)
const sig = sign.sign(privateKeyRSA, 'base64')
return sig
}
const RSAVerify = async (publicKeyRSA, signature, data) => {
const verify = crypto.createVerify('RSA-SHA1')
verify.update(data)
const verify34 = verify.verify(publicKeyRSA, signature, 'base64')
return verify34
}
const dataToSign = message
const sig = RSASign(privateKey, dataToSign)
const verify2 = RSAVerify(publicKey, sig, dataToSign)
return sig
}
/**
* Image Uploader Function
*
* @memberOf frontend.product
* @param {object} req req data with images which has to be uploaded
* @param {number} projectID Project ID for the image uploader
*/
const imageUploader = async (req, projectID) => {
if (req.body.uploadimages !== '') {
req.body.uploadimagesfinal = req.body.uploadimages.toString()
const upimgfinal = req.body.uploadimagesfinal.split(',')
// await Promise.all([productModule.addattachementtoproduct(upimgfinal[0], postinglist[0].insertId)]);
upimgfinal.forEach(async ([value, index]) => {
const imagobj = {
file_name: value,
user_id: req.body.user_id,
orderby: index,
}
await Promise.all([productModule.addattachement(imagobj, projectID)])
// if (index === upimgfinal.length - 1) {
// }
})
} else {
req.body.uploadimagesfinal = ''
}
return true
}
/**
* Get Dynamic contects for the pagination for frontend
*
* @memberOf frontend.product
* @param {object} req req data with images which has to be uploaded
* @param {number} sortValues Sort values
* @param {number} responseData response Data which has to be retrieved
*/
const getdynamicinnercontents = async (req, sortValues, responseData) => {
let returnResponse = responseData
returnResponse.totalRecords = returnResponse.totalRecords[0]
? returnResponse.totalRecords[0].totallength
: 0
if (sortValues) {
returnResponse = await getSortValues(sortValues, responseData)
}
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
}
/**
* Add image link to the data
*
* @memberOf frontend.product
* @param {array} items Items array in which image url is added to the name
*/
const shortDescribeSCHOnlyAvatar = async (items) => {
function changingdata(item) {
item.avatarorg =
item.file_name === '' || item.file_name === null
? `${global.s3_static_image_url}images/pics-coming.jpg`
: `${global.s3_static_image_url}uploads/product/${item.file_name}`
return item
}
const promises = items.map(changingdata)
items = await Promise.all(promises)
return items
}
/**
* Array of elements which add all bidding data
*
* @memberOf frontend.product
* @param {object} req req object
* @param {array} items Items array in which image url is added to the name
*/
const shortDescribeSCH = async (req, items) => {
async function changingdata(item) {
const userId = req.user ? req.user.id : 0
const productId = item.id
const [
results0,
results1,
results2,
results4,
results5,
results6,
results7,
] = await Promise.all([
productModule.fetchAllAttachments(productId),
productModule.checkbidPlacedwhoutlogin(productId),
productModule.getProxyDetails(productId, 'get_highest_biduser'),
productModule.bidsawarded(productId, userId),
productModule.getUserProxyAmt(productId, userId),
productModule.isbuyerbidstarted(productId, userId),
productModule.bidHistory(productId, 0),
])
item.bidwinneruser = 0
item.proxy_bid_details = results2[0]
item.bid_or_not = results6.length
item.biddercurrentbid = results6.length > 0 ? results6[0].proposed_amount : 0
item.bidderproxyant = 0
if (results5.length > 0) {
if (results5[0].prev_maxamount) {
item.bidderproxyant = results5[0].prev_maxamount
}
}
item.current_bid = item.wprice
item.incrementamt = commonFunction.calculateArrayIncrement(item.current_bid)
if (results1.length > 0) {
item.cbidtext = item.market_status !== 'open' ? 'Sold Price' : 'Current Price'
item.next_bid = commonFunction.sumFloat(item.wprice, item.incrementamt)
} else {
item.cbidtext = item.market_status !== 'open' ? 'Sold Price' : 'Starting Price'
item.next_bid = commonFunction.sumFloat(item.wprice, 0)
}
if (results1.length > 0 && typeof req.user !== 'undefined') {
if (
parseInt(global.configurations.variables.proxy_bidding_settings, 10) > 0 &&
results1.length > 0 &&
item.proxy_bid_details.user_id === req.user.id
) {
item.incrementamt = commonFunction.calculateArrayIncrement(
item.proxy_bid_details.maxamount,
)
item.next_bid = commonFunction.sumFloat(
item.proxy_bid_details.maxamount,
item.incrementamt,
)
} else if (
results1[0].user_id === req.user.id &&
parseInt(global.configurations.variables.proxy_bidding_settings, 10) === 0
) {
item.next_bid = commonFunction.sumFloat(item.wprice, item.incrementamt)
}
}
if (results6.length > 0 && results2.length > 0) {
if (item.auctiontype === 'live') {
if (item.proxy_bid_details.user_id === req.user.id) {
if (item.market_status === 'open') {
if (item.wprice < item.proxy_bid_details.maxamount) {
item.bidtopstatus = 'winner'
} else {
item.bidtopstatus = 'winner'
}
} else if (item.booked === 1) {
item.bidwinneruser = item.buynowed !== req.user.id ? 0 : 1
item.bidtopstatus = item.buynowed !== req.user.id ? 'lost' : 'won'
} else {
item.bidwinneruser = results4.length === 0 ? 0 : 1
item.bidtopstatus = results4.length === 0 ? 'lost' : 'won'
}
} else if (item.market_status === 'open') {
if (
results6[0].proposal === 'tie_bid' &&
results6[0].proposed_amount === item.proxy_bid_details.maxamount
) {
item.bidtopstatus = 'outbid'
} else {
item.bidtopstatus = 'outbid'
}
} else if (item.booked === 1) {
item.bidwinneruser = item.buynowed !== req.user.id ? 0 : 1
item.bidtopstatus = item.buynowed !== req.user.id ? 'lost' : 'won'
} else {
item.bidwinneruser = results4.length === 0 ? 0 : 1
item.bidtopstatus = results4.length === 0 ? 'lost' : 'won'
}
} else {
item.bidtopstatus = ''
}
} else {
item.bidtopstatus = ''
}
item.avatarorg =
item.file_name === '' || item.file_name === null
? `${global.s3_static_image_url}images/pics-coming.jpg`
: `${global.s3_static_image_url}uploads/product/${item.file_name}`
item.allattachmentlist = results0
item.bid_count = results7.length
item.bidhistory = results7
return item
}
const promises = items.map(changingdata)
items = await Promise.all(promises)
return items
}
/**
* Get all Return Invoice Details
*
* @memberOf frontend.product
* @param {object} req req object
* @param {productModule.allReturnInvoiceItems} modules
* @param {productModule.getReturnInvoiceCartDetails} modules
* @param {productModule.getAllReturnTransactions} modules
* @param {productModule.getReturnAppointmentDetails} modules
* @param {productModule.getReturnLocationDetails} modules
* @param {array} items Items array in which image url is added to the name
*/
const getReturnInvoiceDetails = async (req) => {
let responseData = {}
let [invoiceItems] = await Promise.all([productModule.allReturnInvoiceItems(req, req.body, 1)])
if (invoiceItems.length > 0) {
req.body.returncart_id = invoiceItems[0].returncart_id
const [cartValues, allTransactions, appointmentDetail, locationDetail] = await Promise.all([
productModule.getReturnInvoiceCartDetails(req.body.returncart_id),
productModule.getAllReturnTransactions(req.body.returncart_id),
productModule.getReturnAppointmentDetails(req.body.returncart_id),
productModule.getReturnLocationDetails(req.body.returncart_id),
])
invoiceItems = await shortDescribeSCHOnlyAvatar(invoiceItems)
responseData = {
status: 'success',
responseType: 1,
message: 'Invoice items retrieved!',
responseData: {
invoiceItems,
cartValues: cartValues[0],
allTransactions,
appointmentDetail: appointmentDetail[0],
locationDetail: locationDetail[0],
},
}
} else {
responseData = {
status: 'error',
responseType: 2,
message: 'No record found!',
}
}
return responseData
}
/**
* Get all Invoice Details
*
* @memberOf frontend.product
* @param {object} req req object
* @param {productModule.getInvoiceCartDetails} modules
* @param {productModule.getAllTransactions} modules
* @param {productModule.getAppointmentDetails} modules
* @param {productModule.getLocationDetails} modules
* @param {array} items Items array in which image url is added to the name
*/
const getInvoiceDetails = async (req) => {
let responseData = {}
let [invoiceItems] = await Promise.all([productModule.allInvoiceItems(req, req.body, 1)])
if (invoiceItems.length > 0) {
req.body.cart_id = invoiceItems[0].cart_id
const [cartValues, allTransactions, appointmentDetail, locationDetail] = await Promise.all([
productModule.getInvoiceCartDetails(req.body.cart_id),
productModule.getAllTransactions(req.body.cart_id),
productModule.getAppointmentDetails(req.body.cart_id),
productModule.getLocationDetails(req.body.cart_id),
])
invoiceItems = await shortDescribeSCHOnlyAvatar(invoiceItems)
responseData = {
status: 'success',
responseType: 1,
message: 'Invoice items retrieved!',
responseData: {
invoiceItems,
cartValues: cartValues[0],
allTransactions,
appointmentDetail: appointmentDetail[0],
locationDetail: locationDetail[0],
},
}
} else {
responseData = {
status: 'error',
responseType: 2,
message: 'No record found!',
}
}
return responseData
}
/**
* Re configure the end time for the auction projects
*
* @memberOf frontend.product
* @param {string} auctionLotId auctionID for which the configuration end time has to be changed
* @param {productModule.fetchAuctionbyID} modules
* @param {productModule.updateAllCloseDates} modules
* @param {productModule.getAllSubLotsnew} modules
* @param {productModule.updatelofdetails} modules
*/
const reConfigureEndTime = async (auctionLotId) => {
const [auctionLot] = await Promise.all([productModule.fetchAuctionbyID(auctionLotId)])
await Promise.all([
productModule.updateAllCloseDates(
auctionLot[0].date_added,
auctionLot[0].date_closed,
auctionLotId,
),
])
if (auctionLot[0].ending_enable === 1) {
const [subLots] = await Promise.all([productModule.getAllSubLotsnew(auctionLotId)])
let updatelotcnt = 0
let updatelottime = auctionLot[0].ending_mins
let list = 1
let belowFiveIncrement = new Date()
const processAllItems = async (items) => {
const newdt = new Date(auctionLot[0].date_closed)
updatelotcnt += 1
if (auctionLot[0].ending_mins === updatelottime && list === 1) {
belowFiveIncrement = new Date(auctionLot[0].date_closed)
} else {
const minutesaddition = parseInt(updatelottime, 10) * 60000
belowFiveIncrement = new Date(newdt.getTime() + minutesaddition)
}
productModule.updatelofdetails(items.id, belowFiveIncrement)
if (auctionLot[0].ending_items === updatelotcnt) {
updatelotcnt = 0
if (auctionLot[0].ending_mins === updatelottime && list === 1) {
list = 0
} else {
updatelottime += auctionLot[0].ending_mins
}
return true
}
return true
}
const resultloop = []
subLots.forEach(async (element) => {
const looptoformat = await processAllItems(element)
resultloop.push(looptoformat)
})
await Promise.all(resultloop)
}
return true
}
module.exports = {
/**
* Search Product
*
* @memberOf frontend.product
* @param {productModule.searchProducts} modules
* @param {productModule.getSearchSortCategories} modules
*/
search: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
let [records, totalRecords, sortValues] = await Promise.all([
productModule.searchProducts(req, req.body, 1),
productModule.searchProducts(req, req.body, 0),
productModule.getSearchSortCategories(req, req.body),
])
let responseData = { records, totalRecords }
records = await shortDescribeSCH(req, records)
responseData = await getdynamicinnercontents(req, sortValues, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get Active Sorts Details
*
* @memberOf frontend.product
* @param {frontend.product.getSortValues} modules
* @param {productModule.getSearchSortCategories} modules
*/
activeSorts: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
const [sortValues] = await Promise.all([
productModule.getSearchSortCategories(req, req.body),
])
let responseData = {}
responseData = await getSortValues(sortValues, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get Invoice details
*
* @memberOf frontend.product
* @param {frontend.product.getInvoiceDetails} modules
*/
invoice: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
const [responseData] = await Promise.all([getInvoiceDetails(req)])
jsonResponse(res, responseData.status, responseData)
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get Return Invoice details
*
* @memberOf frontend.product
* @param {frontend.product.getReturnInvoiceDetails} modules
*/
returninvoice: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
const [responseData] = await Promise.all([getReturnInvoiceDetails(req)])
jsonResponse(res, responseData.status, responseData)
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get Dashboard details
*
* @memberOf frontend.product
* @param {productModule.searchDashboardProducts} modules
* @param {productModule.getSearchSortCategories} modules
*/
dashboard: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
let [records, totalRecords, sortValues] = await Promise.all([
productModule.searchDashboardProducts(req, req.body, 1),
productModule.searchDashboardProducts(req, req.body, 0),
productModule.getSearchSortCategories(req, req.body),
])
let responseData = { records, totalRecords }
records = await shortDescribeSCH(req, records)
responseData = await getdynamicinnercontents(req, sortValues, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get All Invoice
*
* @memberOf frontend.product
* @param {productModule.searchInvoiceProducts} modules
*/
allinvoices: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
const [records, totalRecords] = await Promise.all([
productModule.searchInvoiceProducts(req, req.body, 1),
productModule.searchInvoiceProducts(req, req.body, 0),
])
let responseData = { records, totalRecords }
responseData = await getdynamicinnercontents(req, null, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get All Returns
*
* @memberOf frontend.product
* @param {productModule.searchReturnProducts} modules
*/
allreturns: async (req, res) => {
try {
await schemaModule.search().validateSync(req.body)
const [records, totalRecords] = await Promise.all([
productModule.searchReturnProducts(req, req.body, 1),
productModule.searchReturnProducts(req, req.body, 0),
])
let responseData = { records, totalRecords }
responseData = await getdynamicinnercontents(req, null, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
} catch (e) {
errorResponse(e, res)
}
},
/**
* Get All Bid History
*
* @memberOf frontend.product
* @param {productModule.bidHistoryViewPage} modules
*/
bidhistory: async (req, res) => {
let records = []
let totalRecords = []
try {
;[records, totalRecords] = await Promise.all([
productModule.bidHistoryViewPage(req, 0),
productModule.bidHistoryViewPage(req, 1),
])
totalRecords = [{ totallength: totalRecords.length }]
} catch (e) {
errorResponse(e, res)
} finally {
let responseData = { records, totalRecords }
responseData = await getdynamicinnercontents(req, null, responseData)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
responseData,
})
}
},
postlisting: async (req, res) => {
try {
await schemaModule.posting().validateSync(req.body)
req.body.wprice = req.body.sprice
const postinglist = await Promise.all([
productModule.postalltypeoflisting(req, req.body, global.configColumns.projects),
])
req.body.uploadimages = req.body.uploadimages ? req.body.uploadimages : ''
if (global.configColumns.custom_projects.enabled) {
req.body.product_id = postinglist[0].insertId
await Promise.all([
productModule.postalltypeoflisting(
req,
req.body,
global.configColumns.custom_projects,
),
])
}
await imageUploader(req, postinglist[0].insertId)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
updatelisting: async (req, res) => {
try {
await schemaModule.posting().validateSync(req.body)
req.body.wprice = req.body.sprice
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
req.body.id,
'id',
global.configColumns.projects,
),
])
req.body.uploadimages = req.body.uploadimages ? req.body.uploadimages : ''
if (global.configColumns.custom_projects.enabled) {
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
req.body.id,
'product_id',
global.configColumns.custom_projects,
),
])
}
await Promise.all([productModule.deleteattachement(req, req.body.id)])
await imageUploader(req, req.body.id)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
categorypost: async (req, res) => {
try {
await Promise.all([productModule.addcategory(req, req.body)])
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
categorygetlist: async (req, res) => {
try {
const [catlisting] = await Promise.all([
productModule.commonselectparenttable(
'*',
'id',
req.body.id,
global.configColumns.categories,
),
])
const postinglist = catlisting
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
postinglist,
})
} catch (e) {
errorResponse(e, res)
}
},
categoryupdate: async (req, res) => {
try {
await Promise.all([productModule.updatecategory(req, req.body)])
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
auctionlisting: async (req, res) => {
try {
const postinglist = await Promise.all([
productModule.postalltypeoflisting(req, req.body, global.configColumns.auctionlot),
])
if (global.configColumns.custom_auction.enabled) {
req.body.auction_id = postinglist[0].insertId
await Promise.all([
productModule.postalltypeoflisting(
req,
req.body,
global.configColumns.custom_auction,
),
])
}
req.body.project_id = req.body.project_id ? req.body.project_id : ''
if (req.body.project_id !== '') {
req.body.auction_id = postinglist[0].insertId
await Promise.all([productModule.auctionProjectUpdateexist(req)])
}
const auctionLotId = postinglist[0].insertId
await reConfigureEndTime(auctionLotId)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
updateauction: async (req, res) => {
try {
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
req.body.id,
'id',
global.configColumns.auctionlot,
),
])
if (global.configColumns.custom_auction.enabled) {
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
req.body.id,
'auction_id',
global.configColumns.custom_auction,
),
])
}
req.body.project_id = req.body.project_id ? req.body.project_id : ''
if (req.body.project_id !== '') {
req.body.auction_id = req.body.id
await Promise.all([productModule.auctionProjectUpdateexistrest(req)])
await Promise.all([productModule.auctionProjectUpdateexist(req)])
}
const auctionLotId = req.body.id
await reConfigureEndTime(auctionLotId)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} catch (e) {
errorResponse(e, res)
}
},
getauctiondetails: async (req, res) => {
try {
const auctionobj = {}
const [auctionlisting] = await Promise.all([
productModule.commonselectparenttable(
'*',
'id',
req.body.id,
global.configColumns.auctionlot,
),
])
const postinglist = auctionlisting
auctionobj.auction_list = postinglist
if (global.configColumns.custom_auction.enabled) {
const [auctionlistingcus] = await Promise.all([
productModule.commonselectparenttable(
'*',
'auction_id',
req.body.id,
global.configColumns.custom_auction,
),
])
const postinglist2 = auctionlistingcus
auctionobj.auctioncus_list = postinglist2
}
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
auctionobj,
})
} catch (e) {
errorResponse(e, res)
}
},
getlotdetails: async (req, res) => {
try {
const auctionobj = {}
const [auctionlisting] = await Promise.all([
productModule.commonselectparenttable(
'*',
'id',
req.body.id,
global.configColumns.projects,
),
])
const postinglist = auctionlisting
auctionobj.auction_list = postinglist
if (global.configColumns.custom_projects.enabled) {
const [auctionlistingcus] = await Promise.all([
productModule.commonselectparenttable(
'*',
'product_id',
req.body.id,
global.configColumns.custom_projects,
),
])
const postinglist2 = auctionlistingcus
auctionobj.auctioncus_list = postinglist2
}
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
auctionobj,
})
} catch (e) {
errorResponse(e, res)
}
},
addtocart: async (req, res) => {
try {
if (typeof req.body.user_id === 'undefined') {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Invaild user data!',
})
} else {
const [productData, cartData] = await Promise.all([
productModule.getlotdetails(
'id,market_status,user_id,sold,bprice,booked,qty',
req.body.pro_id,
global.configColumns.projects,
),
productModule.getlotcartsdetails(
'id',
req.body.pro_id,
req.body.user_id,
global.configColumns.cart_temp,
),
])
const prdt = productData[0]
const prdCart = cartData
prdt.qty_add = req.body.qty
if (prdt.qty <= 0) {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Product Sold!',
})
} else if (prdt.qty - prdt.qty_add < 0) {
const availableQty = parseInt(prdt.qty, 30) - parseInt(prdt.sold, 30)
const errMsg = ` Only ${availableQty} quantity is available!`
jsonResponse(res, 'success', {
responseType: 3,
message: errMsg,
})
} else if (prdt.qty - prdt.sold === 0) {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Project Sold!',
})
} else if (prdt.qty - prdt.sold - prdt.qty_add < 0) {
const availableQty = parseInt(prdt.qty, 30) - parseInt(prdt.sold, 30)
const errMsg = ` Only ${availableQty} quantity is available!`
jsonResponse(res, 'success', {
responseType: 3,
message: errMsg,
})
} else if (prdt.market_status !== 'open') {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Project Sold!',
})
} else if (prdCart.length > 0) {
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
prdCart[0].id,
'id',
global.configColumns.cart_temp,
),
productModule.cartqtyproductsub(req.body.qty, req.body.pro_id),
productModule.cartqtyproduct(req.body.qty, req.body.pro_id),
])
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
} else {
await Promise.all([
productModule.postalltypeoflisting(
req,
req.body,
global.configColumns.cart_temp,
),
productModule.cartqtyproduct(req.body.qty, req.body.pro_id),
])
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
}
}
} catch (e) {
errorResponse(e, res)
}
},
updateTocart: async (req, res) => {
try {
if (typeof req.body.user_id === 'undefined') {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Invaild user data!',
})
} else {
const [productData] = await Promise.all([
productModule.getlotdetails(
'id,market_status,user_id,sold,bprice,booked,qty',
req.body.pro_id,
global.configColumns.projects,
),
])
const prdtData = productData
const cartStatus = []
const object1 = req.body
const processAllItemscarts = async (prdt) => {
const [cartData] = await Promise.all([
productModule.getlotcartsdetails(
'id',
prdt.id,
req.body.user_id,
global.configColumns.cart_temp,
),
])
const prdCart = cartData
prdt.qty_add =
typeof req.body[`qty${prdt.id}`] !== 'undefined'
? req.body[`qty${prdt.id}`]
: 1
if (prdt.qty <= 0) {
const data = { success: false, cartid: prdt.id, error: 'Product Sold!' }
cartStatus.push(data)
} else if (prdt.qty - prdt.qty_add < 0) {
const availableQty = parseInt(prdt.qty, 30) - parseInt(prdt.sold, 30)
const errMsg = ` Only ${availableQty} quantity is available!`
const data = { success: false, cartid: prdt.id, error: errMsg }
cartStatus.push(data)
} else if (prdt.qty - prdt.sold === 0) {
const data = { success: false, cartid: prdt.id, error: 'Product Sold!' }
cartStatus.push(data)
} else if (prdt.qty - prdt.sold - prdt.qty_add < 0) {
const availableQty = parseInt(prdt.qty, 30) - parseInt(prdt.sold, 30)
const errMsg = ` Only ${availableQty} quantity is available!`
const data = { success: false, cartid: prdt.id, error: errMsg }
cartStatus.push(data)
} else if (prdt.market_status !== 'open') {
const data = { success: false, cartid: prdt.id, error: 'Product Sold!' }
cartStatus.push(data)
} else if (prdCart.length > 0) {
const objectarry = Object.keys(req.body)
const processAllItemscarts2 = async (prdt2) => {
req.body[prdt2] = req.body[`${prdt2}${prdt.id}`]
return true
}
objectarry.forEach(async (element) => {
const looptoformat = await processAllItemscarts2(element)
})
await Promise.all([
productModule.updatealltypeofproduct(
req,
req.body,
prdCart[0].id,
'id',
global.configColumns.cart_temp,
),
productModule.cartqtyproductsub(req.body.qty, prdt.id),
productModule.cartqtyproduct(req.body.qty, prdt.id),
])
}
return true
}
const resultloop = []
prdtData.forEach(async (element) => {
const looptoformat = await processAllItemscarts(element)
resultloop.push(looptoformat)
})
await Promise.all(resultloop)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
cartStatus,
})
}
} catch (e) {
errorResponse(e, res)
}
},
cartupdateTobuynow: async (req, res) => {
try {
if (typeof req.body.user_id === 'undefined') {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Invaild user data!',
})
} else {
const [productData, invoiceNumber] = await Promise.all([
productModule.getlotdetails(
'id,market_status,user_id,sold,bprice,booked,qty',
req.body.pro_id,
global.configColumns.projects,
),
productModule.getCommonInvoiceNo(
'common_invoice',
req.body.pro_id,
global.configColumns.buynow,
),
])
const prdtData = productData
const invoiceData = invoiceNumber
let cinvoiceno = 10000
if (invoiceData.length > 0) {
cinvoiceno =
invoiceData[0].common_invoice === 0 || invoiceData[0].common_invoice === ''
? 10000
: parseInt(invoiceData[0].common_invoice, 10) + 1
}
let totalProInv = 0
let totalShipamount = 0
let totalInvoice = 0
let totalTax = 0
const processAllItemscartsbuynow = async (prdt) => {
const [cartData] = await Promise.all([
productModule.getlotcartsdetails(
'*',
prdt.id,
req.body.user_id,
global.configColumns.cart_temp,
),
])
const cid = cartData[0]
let proAmt = Number(cid.qty * cid.price)
proAmt = parseFloat(proAmt).toFixed(2)
let vatAmt = Number(proAmt / 100) * Number(cid.tax_price)
vatAmt = parseFloat(vatAmt).toFixed(2)
totalTax = Number(totalTax) + Number(vatAmt)
totalTax = parseFloat(totalTax).toFixed(2)
totalProInv = Number(totalProInv) + Number(proAmt)
totalProInv = parseFloat(totalProInv).toFixed(2)
totalShipamount = Number(totalShipamount) + Number(cid.shipping_cost)
totalShipamount = parseFloat(totalShipamount).toFixed(2)
let proInvoice = Number(proAmt) + Number(vatAmt)
proInvoice = Number(proInvoice) + Number(cid.shipping_cost)
proInvoice = parseFloat(proInvoice).toFixed(2)
totalInvoice = Number(totalInvoice) + Number(proInvoice)
totalInvoice = parseFloat(totalInvoice).toFixed(2)
req.body.project_id = prdt.id
req.body.amount = proAmt
req.body.shipping_amount = cid.shipping_cost
req.body.qty = cid.qty
req.body.cart_id = cid.id
req.body.paid = 1
req.body.active = 1
req.body.buynow_autype = 'buynow'
req.body.common_invoice = cinvoiceno
req.body.invoice_id = cinvoiceno
req.body.sales_tax = vatAmt
const buynowlist = await Promise.all([
productModule.updatecartsbuynow(req, req.body, global.configColumns.buynow),
])
if (global.configColumns.custom_buynow.enabled) {
req.body.buynow_id = buynowlist[0].insertId
await Promise.all([
productModule.postalltypeoflisting(
req,
req.body,
global.configColumns.custom_buynow,
),
])
}
await Promise.all([
productModule.cartqtyproductsoldvalue(cid.qty, prdt.id),
productModule.cartqtyproductsub(cid.qty, prdt.id),
])
const [productDatanew] = await Promise.all([
productModule.getlotdetails(
'id,market_status,sold,booked,qty',
prdt.id,
global.configColumns.projects,
),
])
if (productDatanew[0].length > 0) {
if (productDatanew[0].sold >= productDatanew[0].qty) {
await Promise.all([productModule.productstatusupdate('sold', prdt.id)])
}
}
return true
}
const resultloop = []
prdtData.forEach(async (element) => {
const looptoformat = await processAllItemscartsbuynow(element)
resultloop.push(looptoformat)
})
await Promise.all(resultloop)
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
})
}
} catch (e) {
errorResponse(e, res)
}
},
getcheckoutdetails: async (req, res) => {
try {
if (typeof req.body.user_id === 'undefined') {
jsonResponse(res, 'success', {
responseType: 3,
message: 'Invaild user data!',
})
} else {
const objectname = global.configColumns.cart_temp.array_columns
req.body.seller_id = req.body.seller_id ? req.body.seller_id : 0
const [productData] = await Promise.all([
productModule.getcartsdetails(
'p.id,p.market_status,p.user_id,p.sold,p.bprice,p.booked,p.qty,c.id as cart_id',
req.body.user_id,
req.body.seller_id,
global.configColumns.projects,
global.configColumns.cart_temp,
),
])
const prdtData = productData
const _ = require('underscore')
const projectids = _.pluck(prdtData, 'id')
const cartId = _.pluck(prdtData, 'cart_id')
const resData = {
prdtData,
projectids,
cartId,
}
jsonResponse(res, 'success', {
responseType: 1,
message: 'Details successfully retrieved!',
resData,
})
}
} catch (e) {
errorResponse(e, res)
}
},
removecarts: async (req, res) => {
try {
await Promise.all([
productModule.commondeleteparenttable(
req.body.cart_id,
global.configColumns.cart_temp,
'id',
),
productModule.cartqtyproductsub(req.body.qty, req.body.product_id),
])
jsonResponse(res, 'success', {
responseType: 1,
message: 'Removed successfully!',
})
} catch (e) {
errorResponse(e, res)
}
},
rosoomPaymentcall: async (req, res) => {
try {
const uniq = `S${new Date().getTime()}`
req.body.serviceDescription = 'Product Charges'
req.body.responseURL = `${global.url}/api/front/product/rosoom_success`
req.body.customerReferenceNumber = `Customer${req.body.user_id}`
req.body.documentationCharges = 0
const totalAmount = req.body.amount ? req.body.amount : 0
if (totalAmount === 0) {
jsonResponse(res, 'success', {
responseType: 0,
message: 'Invaild Amount!',
})
}
const encryptData = `soTransactionID::${uniq}||serviceID::${global.rosoompayment.serviceID}||serviceOwnerID::${global.rosoompayment.serviceOwnerID}||serviceCost::${totalAmount}||documentationCharges::${req.body.documentationCharges}||serviceDescription::${req.body.serviceDescription}||responseURL::${req.body.responseURL}||licenseKey::${global.rosoompayment.licenseKey}||serviceChannel::${global.rosoompayment.serviceChannel}||customerReferenceNumber::${req.body.customerReferenceNumber}||buEncryptionMode::${global.rosoompayment.buEncryptionMode}||`
const payload = {
soTransactionID: uniq,
serviceID: global.rosoompayment.serviceID,
serviceOwnerID: global.rosoompayment.serviceOwnerID,
serviceCost: totalAmount,
documentationCharges: req.body.documentationCharges,
serviceDescription: req.body.serviceDescription,
responseURL: req.body.responseURL,
licenseKey: global.rosoompayment.licenseKey,
serviceChannel: global.rosoompayment.serviceChannel,
customerReferenceNumber: req.body.customerReferenceNumber,
buEncryptionMode: global.rosoompayment.buEncryptionMode,
popup: req.body.popup,
signature: securitydata(encryptData),
}
const urlrosoom = global.rosoompayment.url
const successRes = {}
request.get(
{
url: urlrosoom,
qs: payload,
},
(err, response, body) => {
if (err) {
successRes.result = err
successRes.url = ''
} else if (response.statusCode === '200') {
let payurl = response.request.url.href
payurl = payurl.replace('Yes', 'NO')
successRes.result = response.body
successRes.url = payurl
} else {
let payurl = response.request.url.href
payurl = payurl.replace('Yes', 'NO')
successRes.result = response.body
successRes.url = payurl
}
jsonResponse(res, 'success', {
responseType: 1,
message: 'data successfully!',
successRes,
})
},
)
} catch (e) {
errorResponse(e, res)
}
},
rosoomPaymentsuccess: async (req, res) => {
try {
if (req.query.status === 1) {
jsonResponse(res, 'success', {
responseType: 1,
message: 'Payment completed!',
})
} else {
jsonResponse(res, 'success', {
responseType: 1,
message: 'Payment Not completed!',
})
}
} catch (e) {
errorResponse(e, res)
}
},
}