소스 검색

Refactor to move fetching of clover data to a helper function

Lee Morgan 6 년 전
부모
커밋
db16963f6c
5개의 변경된 파일95개의 추가작업 그리고 99개의 파일을 삭제
  1. 91 2
      controllers/helper.js
  2. 0 1
      controllers/merchantData.js
  3. 4 94
      controllers/renderer.js
  4. 0 1
      views/dashboardPage/bundle.js
  5. 0 1
      views/dashboardPage/js/recipeDetails.js

+ 91 - 2
controllers/helper.js

@@ -1,9 +1,97 @@
 const axios = require("axios");
 
 const Transaction = require("../models/transaction.js");
-const { response } = require("express");
 
 module.exports = {
+    getCloverData: async function(merchant){
+        const subscriptionCheck = axios.get(`${process.env.CLOVER_ADDRESS}/v3/apps/${process.env.SUBLINE_CLOVER_APPID}/merchants/${merchant.posId}/billing_info?access_token=${merchant.posAccessToken}`);
+        const transactionRetrieval = axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${merchant.posId}/orders?filter=modifiedTime>=${merchant.lastUpdatedTime}&expand=lineItems&expand=payment&access_token=${merchant.posAccessToken}`);
+        await Promise.all([subscriptionCheck, transactionRetrieval])
+            .then((response)=>{
+                if(response[0].data.status !== "ACTIVE"){
+                    req.session.error = "SUBSCRIPTION EXPIRED.  PLEASE RENEW ON CLOVER";
+                    return res.redirect("/");
+                }
+
+                const updatedTime = Date.now();
+                
+                //Create Subline transactions from Clover Transactions
+                let transactions = [];
+                for(let i = 0; i < response[1].data.elements.length; i++){
+                    let order = response[1].data.elements[i];
+                    if(order.paymentState !== "PAID"){
+                        break;
+                    }
+                    let newTransaction = new Transaction({
+                        merchant: merchant._id,
+                        date: new Date(order.createdTime),
+                        device: order.device.id,
+                        posId: order.id
+                    });
+
+                    //Go through lineItems from Clover
+                    //Get the appropriate recipe from Subline
+                    //Add it to the transaction or increment if existing
+                    for(let j = 0; j < order.lineItems.elements.length; j++){
+                        let recipe = {}
+                        for(let k = 0; k < merchant.recipes.length; k++){
+                            if(merchant.recipes[k].posId === order.lineItems.elements[j].item.id){
+                                recipe = merchant.recipes[k];
+                                break;
+                            }
+                        }
+
+                        if(recipe){
+                            let isNewRecipe = true;
+                            for(let k = 0; k < newTransaction.recipes.length; k++){
+                                if(newTransaction.recipes[k].recipe === recipe._id){
+                                    newTransaction.recipes[k].quantity++;
+                                    isNewRecipe = false;
+                                    break;
+                                }
+                            }
+
+                            if(isNewRecipe){
+                                newTransaction.recipes.push({
+                                    recipe: recipe._id,
+                                    quantity: 1
+                                });
+                            }
+
+                            //Subtract ingredients from merchants total for each ingredient in a recipe
+                            for(let k = 0; k < recipe.ingredients.length; k++){
+                                let inventoryIngredient = {};
+                                for(let l = 0; l < merchant.inventory.length; l++){
+                                    if(merchant.inventory[l].ingredient._id.toString() === recipe.ingredients[k].ingredient._id.toString()){
+                                        inventoryIngredient = merchant.inventory[l];
+                                        break;
+                                    }
+                                }
+                                inventoryIngredient.quantity = inventoryIngredient.quantity - ingredient.quantity;
+                            }
+                        }
+                    }
+
+                    transactions.push(newTransaction);
+                }
+
+                merchant.lastUpdatedTime = updatedTime;
+
+                //Remove any existing orders so that they can be replaced
+                let ids = [];
+                for(let i = 0; i < transactions.length; i++){
+                    ids.push(transactions[i].posId);
+                }
+                Transaction.deleteMany({posId: {$in: ids}});
+
+                return Transaction.create(transactions);
+            })
+            .catch((err)=>{
+                req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
+                return res.redirect("/");
+            });
+    },
+
     getSquareData: function(merchant){
         let now = new Date().toISOString();
         now = `${now.substring(0, now.length - 1)}+00:00`;
@@ -37,7 +125,6 @@ module.exports = {
             }
         })
             .then((response)=>{
-                console.log(response.data.orders.length);
                 let transactions = [];
 
                 if(response.data.orders){
@@ -87,6 +174,8 @@ module.exports = {
                     }
                 }
 
+                merchant.lastUpdatedTime = new Date();
+
                 return transactions;
             })
             .catch((err)=>{

+ 0 - 1
controllers/merchantData.js

@@ -233,7 +233,6 @@ module.exports = {
                     })
             })
             .catch((err)=>{
-                console.log(err);
                 return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
             });
     },

+ 4 - 94
controllers/renderer.js

@@ -1,4 +1,3 @@
-const axios = require("axios");
 const ObjectId = require("mongoose").Types.ObjectId;
 
 const Merchant = require("../models/merchant.js");
@@ -6,7 +5,6 @@ const Transaction = require("../models/transaction.js");
 const Activity = require("../models/activity.js");
 
 const helper = require("./helper.js");
-const merchant = require("../models/merchant.js");
 
 module.exports = {
     /*
@@ -71,101 +69,14 @@ module.exports = {
             .populate("inventory.ingredient")
             .populate("recipes")
             .then(async (merchant)=>{
-                let transactionPromise = {};
                 if(merchant.pos === "clover"){
-                    const subscriptionCheck = axios.get(`${process.env.CLOVER_ADDRESS}/v3/apps/${process.env.SUBLINE_CLOVER_APPID}/merchants/${merchant.posId}/billing_info?access_token=${merchant.posAccessToken}`);
-                    const transactionRetrieval = axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${merchant.posId}/orders?filter=modifiedTime>=${merchant.lastUpdatedTime}&expand=lineItems&expand=payment&access_token=${merchant.posAccessToken}`);
-                    await Promise.all([subscriptionCheck, transactionRetrieval])
-                        .then(async (response)=>{
-                            if(response[0].data.status !== "ACTIVE"){
-                                req.session.error = "SUBSCRIPTION EXPIRED.  PLEASE RENEW ON CLOVER";
-                                return res.redirect("/");
-                            }
-
-                            const updatedTime = Date.now();
-                            
-                            //Create Subline transactions from Clover Transactions
-                            let transactions = [];
-                            for(let i = 0; i < response[1].data.elements.length; i++){
-                                let order = response[1].data.elements[i];
-                                if(order.paymentState !== "PAID"){
-                                    break;
-                                }
-                                let newTransaction = new Transaction({
-                                    merchant: merchant._id,
-                                    date: new Date(order.createdTime),
-                                    device: order.device.id,
-                                    posId: order.id
-                                });
-
-                                //Go through lineItems from Clover
-                                //Get the appropriate recipe from Subline
-                                //Add it to the transaction or increment if existing
-                                for(let j = 0; j < order.lineItems.elements.length; j++){
-                                    let recipe = {}
-                                    for(let k = 0; k < merchant.recipes.length; k++){
-                                        if(merchant.recipes[k].posId === order.lineItems.elements[j].item.id){
-                                            recipe = merchant.recipes[k];
-                                            break;
-                                        }
-                                    }
-
-                                    if(recipe){
-                                        let isNewRecipe = true;
-                                        for(let k = 0; k < newTransaction.recipes.length; k++){
-                                            if(newTransaction.recipes[k].recipe === recipe._id){
-                                                newTransaction.recipes[k].quantity++;
-                                                isNewRecipe = false;
-                                                break;
-                                            }
-                                        }
-
-                                        if(isNewRecipe){
-                                            newTransaction.recipes.push({
-                                                recipe: recipe._id,
-                                                quantity: 1
-                                            });
-                                        }
-
-                                        //Subtract ingredients from merchants total for each ingredient in a recipe
-                                        for(let k = 0; k < recipe.ingredients.length; k++){
-                                            let inventoryIngredient = {};
-                                            for(let l = 0; l < merchant.inventory.length; l++){
-                                                if(merchant.inventory[l].ingredient._id.toString() === recipe.ingredients[k].ingredient._id.toString()){
-                                                    inventoryIngredient = merchant.inventory[l];
-                                                    break;
-                                                }
-                                            }
-                                            inventoryIngredient.quantity = inventoryIngredient.quantity - ingredient.quantity;
-                                        }
-                                    }
-                                }
-
-                                transactions.push(newTransaction);
-                            }
-
-                            merchant.lastUpdatedTime = updatedTime;
-
-                            //Remove any existing orders so that they can ber replaced
-                            let ids = [];
-                            for(let i = 0; i < transactions.length; i++){
-                                ids.push(transactions[i].posId);
-                            }
-                            Transaction.deleteMany({posId: {$in: ids}});
-
-                            transactionPromise = Transaction.create(transactions);
-                            // promiseArray.push(Transaction.create(transactions));
-                        })
-                        .catch((err)=>{
-                            req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
-                            return res.redirect("/");
-                        });
+                    await helper.getCloverData(merchant);
                 }else if(merchant.pos === "square"){
-                    transactionPromise = helper.getSquareData(merchant);
+                    await helper.getSquareData(merchant);
+                }else{
+                    return;
                 }
 
-                await transactionPromise;
-
                 return merchant.save();
             })
             .then((merchant)=>{
@@ -194,7 +105,6 @@ module.exports = {
                     .catch((err)=>{});
             })
             .catch((err)=>{
-                console.log(err);
                 req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
                 return res.redirect("/");
             });

+ 0 - 1
views/dashboardPage/bundle.js

@@ -4135,7 +4135,6 @@ module.exports = {
                 }
             })
             .catch((err)=>{
-                console.log(err);
                 banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
             })
             .finally(()=>{

+ 0 - 1
views/dashboardPage/js/recipeDetails.js

@@ -129,7 +129,6 @@ module.exports = {
                 }
             })
             .catch((err)=>{
-                console.log(err);
                 banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
             })
             .finally(()=>{