Skip to content

Commit

Permalink
Split out transactions into own report
Browse files Browse the repository at this point in the history
  • Loading branch information
ourwarmhouse committed Nov 7, 2021
1 parent b8ce68c commit 4b7566f
Show file tree
Hide file tree
Showing 16 changed files with 510 additions and 86 deletions.
8 changes: 8 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ const product = require('./routes/product');
const customer = require('./routes/customer');
const order = require('./routes/order');
const user = require('./routes/user');
const transactions = require('./routes/transactions');
const reviews = require('./routes/reviews');

const app = express();
Expand Down Expand Up @@ -263,6 +264,12 @@ handlebars = handlebars.create({
}
return '';
},
toUpper: (value) => {
if(value){
return value.toUpperCase();
}
return value;
},
upperFirst: (value) => {
if(value){
return value.replace(/^\w/, (chr) => {
Expand Down Expand Up @@ -405,6 +412,7 @@ app.use('/', product);
app.use('/', order);
app.use('/', user);
app.use('/', admin);
app.use('/', transactions);
app.use('/', reviews);

// Payment route(s)
Expand Down
1 change: 1 addition & 0 deletions lib/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ function initDb(dbUrl, callback){ // eslint-disable-line
db.products = db.collection('products');
db.variants = db.collection('variants');
db.orders = db.collection('orders');
db.transactions = db.collection('transactions');
db.pages = db.collection('pages');
db.menu = db.collection('menu');
db.customers = db.collection('customers');
Expand Down
34 changes: 34 additions & 0 deletions lib/indexing.js
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,38 @@ const indexOrders = async (app) => {
}
};

const indexTransactions = async(app) => {
// Get transactions
const transactionsList = await app.db.transactions.find({}).toArray();

// setup lunr indexing
const transactionsIndex = lunr(function(){
this.field('gatewayReference', { boost: 10 });
this.field('amount', { boost: 5 });
this.field('customer', { boost: 5 });
this.field('gatewayMessage');

const lunrIndex = this;

// add to lunr index
for(const transaction of transactionsList){
const doc = {
gatewayReference: transaction.gatewayReference,
amount: transaction.amount,
customer: transaction.customer,
gatewayMessage: transaction.gatewayMessage,
id: transaction._id
};
lunrIndex.add(doc);
};
});

app.transactionsIndex = transactionsIndex;
if(process.env.NODE_ENV !== 'test'){
console.log(colors.cyan('- Transaction indexing complete'));
}
};

const indexReviews = async(app) => {
// Get reviews
const reviewsList = await app.db.reviews.find({}).toArray();
Expand Down Expand Up @@ -129,13 +161,15 @@ const runIndexing = async (app) => {
await indexProducts(app);
await indexOrders(app);
await indexCustomers(app);
await indexTransactions(app);
await indexReviews(app);
};

module.exports = {
indexProducts,
indexCustomers,
indexOrders,
indexTransactions,
indexReviews,
runIndexing
};
37 changes: 32 additions & 5 deletions lib/payments/adyen.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const express = require('express');
const { indexOrders } = require('../indexing');
const { indexOrders, indexTransactions } = require('../indexing');
const numeral = require('numeral');
const got = require('got');
const { getId, sendEmail, getEmailTemplate } = require('../common');
Expand Down Expand Up @@ -48,18 +48,35 @@ router.post('/setup', async (req, res, next) => {
router.post('/checkout_action', async (req, res, next) => {
const db = req.app.db;
const config = req.app.config;
const adyenConfig = getPaymentConfig('adyen');

// Update response
let paymentStatus = 'Paid';
let approved = true;
if(req.body.paymentCode !== 'Authorised'){
paymentStatus = 'Declined';
approved = false;
}

// Create our transaction
const transaction = await db.transactions.insertOne({
gateway: 'adyen',
gatewayReference: req.body.paymentId,
gatewayMessage: req.body.paymentCode,
approved: approved,
amount: req.session.totalCartAmount,
currency: adyenConfig.currency,
customer: getId(req.session.customerId),
created: new Date()
});

const transactionId = transaction.insertedId;

// Index transactios
await indexTransactions(req.app);

// new order doc
const orderDoc = {
orderPaymentId: req.body.paymentId,
orderPaymentGateway: 'Adyen',
orderPaymentMessage: req.body.paymentCode,
orderTotal: req.session.totalCartAmount,
orderShipping: req.session.totalCartShipping,
orderItemCount: req.session.totalCartItems,
Expand All @@ -79,7 +96,8 @@ router.post('/checkout_action', async (req, res, next) => {
orderStatus: paymentStatus,
orderDate: new Date(),
orderProducts: req.session.cart,
orderType: 'Single'
orderType: 'Single',
transaction: transactionId
};

// insert order into DB
Expand All @@ -88,6 +106,15 @@ router.post('/checkout_action', async (req, res, next) => {
// get the new ID
const newId = newOrder.insertedId;

// Update order to transaction
await db.transactions.updateOne({
_id: getId(transactionId)
}, {
$set: {
order: getId(newId)
}
});

// add to lunr index
indexOrders(req.app)
.then(() => {
Expand Down
38 changes: 33 additions & 5 deletions lib/payments/authorizenet.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const express = require('express');
const axios = require('axios');
const stripBom = require('strip-bom');
const { indexOrders } = require('../indexing');
const { indexOrders, indexTransactions } = require('../indexing');
const { getId, sendEmail, getEmailTemplate } = require('../common');
const { getPaymentConfig } = require('../config');
const { emptyCart } = require('../cart');
Expand Down Expand Up @@ -52,15 +52,33 @@ router.post('/checkout_action', (req, res, next) => {

// order status if approved
let orderStatus = 'Paid';
let approved = true;
let paymentMessage = 'Your payment was successfully completed';
if(txn && txn.responseCode !== '1'){
console.log('Declined response payload', response.data);
paymentMessage = 'Your payment was declined';
orderStatus = 'Declined';
approved = false;
}

// Create our transaction
const transaction = await db.transactions.insertOne({
gateway: 'authorizenet',
gatewayReference: txn.transHash,
gatewayMessage: paymentMessage,
approved: approved,
amount: req.session.totalCartAmount,
currency: config.currencyISO,
customer: getId(req.session.customerId),
created: new Date()
});

const transactionId = transaction.insertedId;

// Index transactios
await indexTransactions(req.app);

const orderDoc = {
orderPaymentId: txn.transHash,
orderPaymentGateway: 'AuthorizeNet',
orderPaymentMessage: 'Your payment was successfully completed',
orderTotal: req.session.totalCartAmount,
orderShipping: req.session.totalCartShipping,
orderItemCount: req.session.totalCartItems,
Expand All @@ -80,7 +98,8 @@ router.post('/checkout_action', (req, res, next) => {
orderStatus: orderStatus,
orderDate: new Date(),
orderProducts: req.session.cart,
orderType: 'Single'
orderType: 'Single',
transaction: transactionId
};

// insert order into DB
Expand All @@ -90,6 +109,15 @@ router.post('/checkout_action', (req, res, next) => {
// get the new ID
const newId = newDoc.insertedId;

// Update order to transaction
await db.transactions.updateOne({
_id: getId(transactionId)
}, {
$set: {
order: getId(newId)
}
});

// add to lunr index
indexOrders(req.app)
.then(() => {
Expand Down
33 changes: 26 additions & 7 deletions lib/payments/paypal.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const express = require('express');
const { indexOrders } = require('../indexing');
const { indexOrders, indexTransactions } = require('../indexing');
const { getId, sendEmail, getEmailTemplate } = require('../common');
const { getPaymentConfig } = require('../config');
const { emptyCart } = require('../cart');
Expand All @@ -14,11 +14,12 @@ router.get('/checkout_cancel', (req, res, next) => {
router.get('/checkout_return', (req, res, next) => {
const db = req.app.db;
const config = req.app.config;
const paypalConfig = getPaymentConfig('paypal');
const paymentId = req.session.paymentId;
const payerId = req.query.PayerID;

const details = { payer_id: payerId };
paypal.payment.execute(paymentId, details, (error, payment) => {
paypal.payment.execute(paymentId, details, async(error, payment) => {
let paymentApproved = false;
let paymentMessage = '';
let paymentDetails = '';
Expand Down Expand Up @@ -50,7 +51,7 @@ router.get('/checkout_return', (req, res, next) => {
if(payment.state === 'approved'){
paymentApproved = true;
paymentStatus = 'Paid';
paymentMessage = 'Your payment was successfully completed';
paymentMessage = 'Succeeded';
paymentDetails = `<p><strong>Order ID: </strong>${paymentOrderId}</p><p><strong>Transaction ID: </strong>${payment.id}</p>`;

// clear the cart
Expand All @@ -62,16 +63,34 @@ router.get('/checkout_return', (req, res, next) => {
// failed
if(payment.failureReason){
paymentApproved = false;
paymentMessage = `Your payment failed - ${payment.failureReason}`;
paymentMessage = `Declined: ${payment.failureReason}`;
paymentStatus = 'Declined';
}

// Create our transaction
const transaction = await db.transactions.insertOne({
gateway: 'paypal',
gatewayReference: payment.id,
gatewayMessage: paymentMessage,
approved: paymentApproved,
amount: req.session.totalCartAmount,
currency: paypalConfig.paypalCurrency,
customer: getId(req.session.customerId),
created: new Date(),
order: getId(paymentOrderId)
});

const transactionId = transaction.insertedId;

// Index transactios
await indexTransactions(req.app);

// update the order status
db.orders.updateOne({ _id: getId(paymentOrderId) }, { $set: { orderStatus: paymentStatus } }, { multi: false }, (err, numReplaced) => {
db.orders.updateOne({ _id: getId(paymentOrderId) }, { $set: { orderStatus: paymentStatus, transaction: transactionId } }, { multi: false }, (err, numReplaced) => {
if(err){
console.info(err.stack);
}
db.orders.findOne({ _id: getId(paymentOrderId) }, (err, order) => {
db.orders.findOne({ _id: getId(paymentOrderId) }, async (err, order) => {
if(err){
console.info(err.stack);
}
Expand Down Expand Up @@ -134,7 +153,7 @@ router.post('/checkout_action', (req, res, next) => {
paypal.configure(paypalConfig);

// create payment
paypal.payment.create(payment, (error, payment) => {
paypal.payment.create(payment, async(error, payment) => {
if(error){
req.session.message = 'There was an error processing your payment. You have not been charged and can try again.';
req.session.messageType = 'danger';
Expand Down
36 changes: 31 additions & 5 deletions lib/payments/payway.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
const express = require('express');
const { indexOrders } = require('../indexing');
const { indexOrders, indexTransactions } = require('../indexing');
const { getId, sendEmail, getEmailTemplate } = require('../common');
const { getPaymentConfig } = require('../config');
const { emptyCart } = require('../cart');
Expand Down Expand Up @@ -50,15 +50,31 @@ router.post('/checkout_action', async (req, res, next) => {

// order status if approved
let orderStatus = 'Paid';
let approved = true;
if(txn && txn.status === 'declined'){
console.log('Declined response payload', txn);
orderStatus = 'Declined';
approved = false;
}

// Create our transaction
const transaction = await db.transactions.insertOne({
gateway: 'payway',
gatewayReference: txn.transactionId.toString(),
gatewayMessage: `${txn.responseCode} - ${txn.responseText}`,
approved: approved,
amount: req.session.totalCartAmount,
currency: 'aud',
customer: getId(req.session.customerId),
created: new Date()
});

const transactionId = transaction.insertedId;

// Index transactios
await indexTransactions(req.app);

const orderDoc = {
orderPaymentId: txn.transactionId.toString(),
orderPaymentGateway: 'PayWay',
orderPaymentMessage: `${txn.responseCode} - ${txn.responseText}`,
orderTotal: req.session.totalCartAmount,
orderShipping: req.session.totalCartShipping,
orderItemCount: req.session.totalCartItems,
Expand All @@ -78,7 +94,8 @@ router.post('/checkout_action', async (req, res, next) => {
orderStatus: orderStatus,
orderDate: new Date(),
orderProducts: req.session.cart,
orderType: 'Single'
orderType: 'Single',
transaction: transactionId
};

// insert order into DB
Expand All @@ -88,6 +105,15 @@ router.post('/checkout_action', async (req, res, next) => {
// get the new ID
const newId = newDoc.insertedId;

// Update order to transaction
await db.transactions.updateOne({
_id: getId(transactionId)
}, {
$set: {
order: getId(newId)
}
});

// add to lunr index
indexOrders(req.app)
.then(() => {
Expand Down
Loading

0 comments on commit 4b7566f

Please sign in to comment.