📁 File Manager Pro
v10.0.3 | PHP: 8.2.31
Server: LiteSpeed
2026-06-30 00:53:10
📂
/ (Root)
/
home
/
orkouolp
/
node_js
/
orkofarms.com
/
controller
📍 /home/orkouolp/node_js/orkofarms.com/controller
🔄 Refresh
✏️
Editing: sales.controller.js
Writable
const { v4: uuidv4 } = require('uuid'), { createTransport } = require('nodemailer'); const { google } = require('googleapis'); const { createPayment, executePayment, refundTransaction } = require('bkash-payment') const bkashConfig = require('../bkash'); const firebase = require('../firebase'); const svAc = require('../service-account.json'); const salesController = {}; //---------------------------------------------------------------------------------------------------------// salesController.bkashCheckout = async (req, res) => { console.log('POST /bkash-checkout'); const { total, orderId, ref, callbackURL } = req.body; console.log('total:', total, ', orderId:', orderId, ', ref:', ref, ', callbackURL:', callbackURL); //--------------------------------------------------------------------------------// // const callbackURL = 'http://127.0.0.1:3000/bkash-callback'; //const orderId = 'Order_101'; //, ref = '1'; const paymentDetails = { amount: total, // your product price callbackURL : callbackURL, // your callback route orderID : orderId, // your orderID reference : ref // your reference }; //console.log('paymentDetails:',paymentDetails); try { const result = await createPayment(bkashConfig, paymentDetails); console.log('bKash result:', result); res.send(result); } catch (e) { console.log('bkash error:', e); res.status(200).json({error: e}); } //--------------------------------------------------------------------------------// // res.status(200).json({ total }); } //---------------------------------------------------------------------------------------------------------// salesController.bkashCallbackGet = async (req, res) => { console.log('GET /bkash-callback'); const { status, paymentID } = req.query; console.log('req.query:', req.query); console.log('status:', status, ', paymentID:', paymentID); let result =null; if(status === 'success') { try { console.log('Executing Payment..'); result = await executePayment(bkashConfig, paymentID); if(result?.transactionStatus === 'Completed'){ console.log('payment success'); // insert result in your db } } catch (e) { console.log(e); } } } //---------------------------------------------------------------------------------------------------------// salesController.getBkashToken = async (req, res) => { console.log('GET /get-bkash-token'); let token = ''; // Request Grant Token in bKash Playground //--------------------------------------------------------------------------------// const baseUrl = 'https://tokenized.sandbox.bka.sh/v1.2.0-beta', method = 'POST', endpoint = 'tokenized/checkout/token/grant', password = 'D7DaC<*E*eG', username = '01770618567', APP_KEY = '0vWQuCRGiUX7EPVjQDr0EUAYtc', APP_SECRET = 'jcUNPBgbcqEDedNKdvE4G1cAK7D3hCjmJccNPZZBq96QIxxwAMEx', body = { app_key: APP_KEY, app_secret: APP_SECRET }; const url = `${baseUrl}/${endpoint}`, options = { method, mode: 'cors', ...(body && { body: JSON.stringify(body) }), // headers: { 'Content-Type': 'application/json', 'Accept': 'application/json', username, password } }; console.log('url:', url, ', options:', options); // fetch(url, options).then((res, err) => { console.log('err', err, 'res:', res); }); try { const res = await fetch(url, options); console.log('res:', res, (typeof res)); // const res = await fetch('https://postman-echo.com/get?hand=wave' // , {method: 'GET', mode: 'cors'}); console.log('res:', res); //mockbin.com } catch(error) { console.log('error:', error); } //--------------------------------------------------------------------------------// res.status(200).json({ token }); } //---------------------------------------------------------------------------------------------------------// salesController.backOrder = async (req, res) => { console.log('POST /back-order'); const { currentUser } = req; //console.log('currentUser:', currentUser); if(!currentUser) { return res.status(400).json({ error: 'an error occured, unable to create order' }); } const { orDt, total, items, pmtMethod, shipping } = req.body; //{ uid } = currentUser; console.log('backOrder:', orDt, total, items, pmtMethod, shipping); //let phone = '', name = ''; if(shipping) {phone = shipping.phone; name = shipping.name;} let { phone, name } = shipping? shipping: { phone: '', name: '' }; if(!phone) { console.log('backOrder:: Phone number is required'); return res.status(400).json({ error: 'an error occured, unable to create order' }); } let uid = '', email = '', type = '', createdAt = new Date(), userRec, userDoc; const qrRef = firebase.db.collection('users').where('phoneNumber', '==', '+88'+phone); const qrSnapSh = await qrRef.get(); //console.log('qrSnapSh:', qrSnapSh); if(!qrSnapSh.empty) { const user = qrSnapSh.docs[0].data(); console.log('user:', user); if(user) { if(user.uid) uid = user.uid; if(user.email) email = user.email; if(user.type) type = user.type; if(user.createdAt) createdAt = user.createdAt; } } if(!uid) { if(!email) email = 'p_' + phone + '@test.com'; console.log('email:', email); userRec = { email, displayName: name, phoneNumber: '+88'+phone, password: 'Pass@123' }; console.log('Creating User:: name:', name, ', userRec:', userRec); try { uid = (await firebase.auth.createUser(userRec)).uid; } catch(error) { console.log('Error creating user:', error); return res.status(400).json({ error: 'an error occured, unable to create order' });; } } if(uid) { userDoc = { uid, displayName: name, phoneNumber: '+88'+phone, email, type, createdAt }; console.log('Updating User:: uid:', uid, ', userDoc:', userDoc); try { const userDb = firebase.db.collection('users'); await userDb.doc(uid).set(userDoc); } catch(error) { console.log('Error updating user:', error); return res.status(400).json({ error: 'an error occured, unable to create order' });; } } else { return res.status(400).json({ error: 'an error occured, unable to create order' });; } const ordersDb = firebase.db.collection('orders'), id = uuidv4(); //console.log("id:",id,(typeof id)); const orderDoc = { id, orDt, orSt:'', total, items, pmtMethod, shipping, uid }; try { console.log('Creating Order:: orderDoc:', orderDoc); await ordersDb.doc(id).set(orderDoc); res.status(200).json({orderDoc}); } catch(error) { console.log('Error Creating Order:', error); res.status(400).json({ error: 'an error occured, unable to create order' });; } } //---------------------------------------------------------------------------------------------------------// salesController.placeOrder = async (req, res) => { console.log('POST /place-order'); const { currentUser } = req; //console.log('currentUser:', currentUser); if(!currentUser) { res.status(400).json({ error: 'an error occured, unable to create order' });; } const { orderId, orDt, total, items, pmtMethod, shipping, bkash } = req.body, { uid } = currentUser; //console.log('placeOrder:', orderId, orDt, total, items, pmtMethod, shipping, bkash, uid); const ordersDb = firebase.db.collection('orders'); let bOrder = true; const id = orderId? orderId: uuidv4(); //console.log('id:', id, (typeof id)); // const orderDoc = { id, orDt, total, items, pmtMethod, shipping, uid }; const orderDoc = { id, orDt, orSt:'', total, items, pmtMethod, shipping, uid }; if(pmtMethod==='bKash' && bkash && bkash.paymentID) { console.log('salesController.placeOrder:: Call bKash Execute Payment API'); let result =null; if(bkash.status==='success') { try { console.log('Executing Payment..'); result = await executePayment(bkashConfig, bkash.paymentID); // if(result?.transactionStatus === 'Completed') { if(result) { console.log('transactionStatus:', result.transactionStatus); bkash.transactionStatus = result.transactionStatus; bkash.trxID = result.trxID; console.log('Updated bkash:', bkash); if(result.transactionStatus === 'Completed') { console.log('payment success'); orderDoc.pmtStatus = 'Paid'; orderDoc.paymentID = bkash.paymentID; orderDoc.bkshTrxID = result.trxID; orderDoc.paidAmt = result.amount; orderDoc.pyDt = new Date(); console.log('Updated orderDoc:', orderDoc); } else bOrder = false; console.log('Updated bOrder:', bOrder); } } catch (e) { console.log(e); res.status(400).json({ error: 'an error occured, unable to update payment status' }); } } } //console.log('bOrder:',bOrder); if(bOrder) { try { console.log('inserting order into db, orderDoc:', orderDoc); await ordersDb.doc(id).set(orderDoc); //console.log('orderDoc:', orderDoc); } catch(error) { console.log(error); res.status(400).json({ error: 'an error occured, unable to create order' }); } console.log('Returning success, bkash:', bkash); res.status(200).json({status: 'success', bkash, orderDoc}); } else { console.log('Returning failed, bkash:', bkash); res.status(200).json({status: 'failed', bkash, orderDoc}); } } //---------------------------------------------------------------------------------------------------------// // const updateOrder = async (orderDoc) => { console.log('updateOrder:: orderDoc:',orderDoc); // const ordersDb = firebase.db.collection('orders'); // if(!orderDoc || !orderDoc.id) return 'error'; // try { // await ordersDb.doc(orderDoc.id).set(orderDoc); //console.log('orderDoc:', orderDoc); // return 'success'; //res.status(200).json({orderDoc}); // } catch(error) { console.log(error); // return 'error'; //res.status(400).json({ error: 'an error occured, unable to create order' }); // } // } //---------------------------------------------------------------------------------------------------------// salesController.refundOrder = async (req, res) => { console.log('POST /refund-order'); // const { paymentID, bkshTrxID, total } = req.body; const { id, orDt, total, items, pmtMethod, pmtStatus, paymentID, pyDt, bkshTrxID, refundTrxID, paidAmt, refundAmt, rfDt, shipping, orSt, uid } = req.body; if(!id) { return res.status(400).json({ error: 'unable to update order, id may not be blank' }); } //console.log('paymentID:', paymentID, ', total:', total, ', bkshTrxID:', bkshTrxID); const refAmt = (refundAmt?refundAmt:0); const orderDoc = { id, orDt, total, items, pmtMethod, pyDt:(pyDt?pyDt:null), pmtStatus:(pmtStatus?pmtStatus:''), paymentID:(paymentID?paymentID:''), bkshTrxID:(bkshTrxID?bkshTrxID:''), refundTrxID:(refundTrxID?refundTrxID:''), paidAmt:(paidAmt?paidAmt:0), refundAmt: refAmt, rfDt:(rfDt?rfDt:null), shipping, orSt:(orSt?orSt:''), uid }; const ordersDb = firebase.db.collection('orders'); //--------------------------------------------------------------------------------// // const callbackURL = 'http://127.0.0.1:3000/bkash-callback'; //const orderId = 'Order_101'; //, ref = '1'; try { let result =null; if(pmtMethod==='bKash' && paymentID && bkshTrxID && paidAmt>refAmt) { const refundDetails = { paymentID : paymentID, trxID : bkshTrxID, amount: (paidAmt-refAmt) }; console.log('refundDetails:',refundDetails); result = await refundTransaction(bkashConfig, refundDetails); console.log('bKash Refund result:', result); if(result.transactionStatus==='Completed') { orderDoc.refundTrxID = result.refundTrxID; orderDoc.rfDt = new Date(); } } orderDoc.pmtStatus = 'Refunded'; orderDoc.refundAmt = paidAmt; await ordersDb.doc(id).set(orderDoc); console.log('orderDoc:', orderDoc); if(result) res.send(result); else res.status(200).json({orderDoc}); } catch (e) { console.log('bkash error:', e); res.status(200).json({error: e}); } //--------------------------------------------------------------------------------// } //---------------------------------------------------------------------------------------------------------// salesController.updateOrder = async (req, res) => { console.log('POST /update-order'); // const { id, orDt, total, items, pmtMethod, shipping, orSt, uid } = req.body; const { id, orDt, total, items, pmtMethod, pmtStatus, paymentID, pyDt, bkshTrxID, refundTrxID, paidAmt, refundAmt, rfDt, shipping, orSt, uid } = req.body; if(!id) { return res.status(400).json({ error: 'unable to update order, id may not be blank' }); } const orderDoc = { id, orDt, total, items, pmtMethod, pyDt:(pyDt?pyDt:null), pmtStatus:(pmtStatus?pmtStatus:''), paymentID:(paymentID?paymentID:''), bkshTrxID:(bkshTrxID?bkshTrxID:''), refundTrxID:(refundTrxID?refundTrxID:''), paidAmt:(paidAmt?paidAmt:0), refundAmt:(refundAmt?refundAmt:0), rfDt:(rfDt?rfDt:null), shipping, orSt:(orSt?orSt:''), uid }; const ordersDb = firebase.db.collection('orders'); try { await ordersDb.doc(id).set(orderDoc); //console.log('orderDoc:', orderDoc); res.status(200).json({orderDoc}); } catch(error) { console.log(error); res.status(400).json({ error: 'an error occured, unable to create order' }); } }; //---------------------------------------------------------------------------------------------------------// salesController.sendMail = async (req, res) => { console.log('POST /send-mail'); const { email, cc, bcc, subject, html, fileName, buffer } = req.body; //console.log(req.body); //console.log('salesController.sendMail:: fileName:', fileName, ', buffer:', buffer); const pdfBuffer = (buffer?Buffer.from(buffer):null); //console.log("pdfBuffer:", pdfBuffer); // console.log('svAc:', svAc); // Function to send the email using Gmail API async function sendMimeMessage(mimeMessage) { const gmail = google.gmail({ version: 'v1' }); const jwtClient = new google.auth.JWT( svAc.client_email, null, svAc.private_key, ['https://www.googleapis.com/auth/gmail.send'], process.env.GMAIL_USERNAME // Specify the email address of the user the service account is impersonating. // Ensure the service account has domain-wide authority to impersonate this user. ); // Authorize the JWT client and get a token to make API calls await jwtClient.authorize(); // Send the email using the Gmail API const response = await gmail.users.messages.send({ auth: jwtClient, userId: 'me', resource: { raw: mimeMessage } }); //console.log('Email sent:', response.data); } try { //console.log('email:', email); // const transporter = createTransport({ host: 'smtp.gmail.com', port: 465, secure: true, // auth: { type: 'OAuth2', // user: process.env.GMAIL_USERNAME, // your permissioned service account member e-mail // serviceClient: svAc.client_id, privateKey: svAc.private_key // } }); // const transporter = createTransport({ // streamTransport: true, newline: 'unix', buffer: true // }); // const transporter = createTransport({ //host: 'smtp.gmail.com', port: 465, secure: true, // service: "Gmail", auth: { // user: process.env.GMAIL_USERNAME, //"Your email" // pass: process.env.GMAIL_APP_PASS //"Google App Password Without Spaces" // } }); // console.log(process.env.EMAIL_HOST, process.env.EMAIL_USER, process.env.EMAIL_PASS); const transporter = createTransport({ host: process.env.EMAIL_HOST, port: 465, secure: true, auth: { user: process.env.EMAIL_USER, pass: process.env.EMAIL_PASS } }); await transporter.verify(); //console.log('transporter:', transporter); const username = `"ORKO Farms" <${process.env.EMAIL_USER}>`; console.log('username:', username); const mailOptions = { from: username, to: email, subject, html }; if(cc) mailOptions.cc = cc; if(bcc) mailOptions.bcc = bcc; if(fileName && pdfBuffer){ mailOptions.attachments = [ {filename: fileName, content: pdfBuffer, contentType: 'application/pdf'} ];} //console.log('mailOptions:', mailOptions); transporter.sendMail(mailOptions, (err, info) => { if(err){ console.log(err); const msg = 'The mail could NOT be sent to ' + email; console.log(msg); res.status(200).json({message: msg}); } else { //console.log("info:", info); // const mimeMessage = info.message.toString('base64'); //console.log('mimeMessage:', mimeMessage); // sendMimeMessage(mimeMessage).then(() => { console.log('Email sent successfully.'); res.status(200).json({message: 'Successfully sent Mail to: ' + email}); // }) // .catch(error => { console.error('Error sending email:', error); // res.status(200).json({message: 'The mail could NOT be sent to ' + email}); // }); } }); } catch (error) { console.log(error); res.status(200).json({message: 'The mail could NOT be sent to ' + email}); } } //---------------------------------------------------------------------------------------------------------// salesController.sendSms = async (req, res) => { console.log('POST /send-sms'); let { phone, msg } = req.body; console.log(phone, msg); //console.log(req.body); if(!(phone && msg)) { return res.status(400).json({ error: 'Must provide a phone number and a msg to send!' }); } switch(phone[0]) { case '+': phone = phone.substr(1); break; case '0': phone = '88' + phone; break; } console.log('phone:', phone); if(phone[0] !== '8') { return res.status(400).json({ error: 'Phone number must start with 880!' }); } const body = { api_key: process.env.ALPHA_SMS_API_KEY, msg, to: phone }; const url = 'https://api.sms.net.bd/sendsms', options = { method: 'POST', mode: 'cors', ...(body && { body: JSON.stringify(body) }), // // headers: { // 'Content-Type': 'application/json', // 'Accept': 'application/json', username, password // } }; console.log('url:', url, ', options:', options); try { const res = await fetch(url, options); //console.log('res:', res, (typeof res)); res.status(200).json(body); } catch(error) { console.log('error:', error); res.status(200).json({message: 'The SMS could NOT be sent to ' + phone}); } } //---------------------------------------------------------------------------------------------------------// module.exports = salesController;
💾 Save Changes
❌ Cancel