Переглянути джерело

Build backend for updating square user's recipes. There is still a bug where they don't match up with the local merchants recipes because I am comparing the wrong ids. I need to populate the merchants recipes.

Lee Morgan 6 роки тому
батько
коміт
03450e33f5

+ 93 - 2
controllers/recipeData.js

@@ -1,9 +1,10 @@
+const axios = require("axios");
+
 const Recipe = require("../models/recipe.js");
 const Merchant = require("../models/merchant.js");
 const RecipeChange = require("../models/recipeChange.js");
 const Validator = require("./validator.js");
-
-const axios = require("axios");
+const merchant = require("../models/merchant.js");
 
 module.exports = {
     /*
@@ -225,5 +226,95 @@ module.exports = {
             .catch((err)=>{
                 return res.json("ERROR: UNABLE TO RETRIEVE MERCHANT DATA");
             });
+    },
+
+    updateRecipesSquare: function(req, res){
+        
+        if(!req.session.user){
+            req.session.error = "Must be logged in to do that";
+            return res.redirect("/");
+        }
+
+        let merchant = {};
+        let merchantRecipes = [];
+        let newRecipes = [];
+
+        Merchant.findOne({_id: req.session.user})
+            .then((fetchedMerchant)=>{
+                merchant = fetchedMerchant;
+                return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
+                    object_types: ["ITEM"]
+                }, {
+                    headers: {
+                        Authorization: `Bearer ${merchant.posAccessToken}`
+                    }
+                });
+            })
+            .then(async (response)=>{
+                merchantRecipes = merchant.recipes.slice();
+
+                
+                for(let i = 0; i < response.data.objects.length; i++){
+                    let itemData = response.data.objects[i].item_data;
+                    for(let j = 0; j < itemData.variations.length; j++){
+                        let isFound = false;
+
+                        for(let k = 0; k < merchantRecipes.length; k++){
+                            merchantRecipes[k] = merchantRecipes[k].toString();
+                            //I'm comparing posId to recipe id
+                            console.log(itemData.variations[j].id);
+                            console.log(merchantRecipes[k]);
+                            console.log();
+                            if(itemData.variations[j].id === merchantRecipes[k]){
+                                merchantRecipes.splice(k, 1);
+                                k--;
+                                isFound = true;
+                                break;
+                            }
+                        }
+
+                        if(!isFound){
+                            let newRecipe = new Recipe({
+                                posId: itemData.variations[j].id,
+                                merchant: merchant._id,
+                                name: "",
+                                price: itemData.variations[j].item_variation_data.price_money.amount,
+                                ingredients: []
+                            });
+
+                            if(itemData.variations.length > 1){
+                                newRecipe.name = `${itemData.name} '${itemData.variations[j].item_variation_data.name}'`;
+                            }else{
+                                newRecipe.name = itemData.name;
+                            }
+
+                            newRecipes.push(newRecipe);
+                            merchant.recipes.push(newRecipe);
+                        }
+                    }
+                }
+
+                for(let i = 0; i < merchantRecipes.length; i++){
+                    for(let j = 0; j < merchant.recipes.length; j++){
+                        if(merchantRecipes[i] === merchant.recipes[j]._id.toString()){
+                            merchant.recipes.splice(j, 1);
+                            break;
+                        }
+                    }
+                }
+
+                if(merchantRecipes.length > 0){
+                    Recipe.deleteMany({_id: {$in: merchantRecipes}});
+                }
+
+                return merchant.save();
+            })
+            .then((merchant)=>{
+                return res.json({new: newRecipes, removed: merchantRecipes});
+            })
+            .catch((err)=>{
+                console.log(err);
+                return "ERROR: UNABLE TO RETRIEVE RECIPE DATA FROM SQUARE";
+            });
     }
 }

+ 1 - 0
routes.js

@@ -32,6 +32,7 @@ module.exports = function(app){
     app.post("/recipe/create", recipeData.createRecipe);
     app.put("/recipe/update", recipeData.updateRecipe);
     app.get("/recipe/update/clover", recipeData.updateRecipesClover);
+    app.get("/recipe/update/square", recipeData.updateRecipesSquare);
 
     //Orders
     app.get("/order", orderData.getOrders);

+ 9 - 6
views/dashboardPage/bundle.js

@@ -2447,7 +2447,7 @@ controller = {
             case "recipeBook":
                 activeButton = document.getElementById("recipeBookBtn");
                 document.getElementById("recipeBookStrand").style.display = "flex";
-                recipeBook.display();
+                recipeBook.display(Recipe);
                 break;
             case "orders":
                 activeButton = document.getElementById("ordersBtn");
@@ -3889,12 +3889,12 @@ module.exports = {
     isPopulated: false,
     recipeDivList: [],
 
-    display: function(){
+    display: function(Recipe){
         if(!this.isPopulated){
             this.populateRecipes();
 
-            if(merchant.pos === "clover"){
-                document.getElementById("posUpdateRecipe").onclick = ()=>{this.posUpdate()};
+            if(merchant.pos !== "none"){
+                document.getElementById("posUpdateRecipe").onclick = ()=>{this.posUpdate(Recipe)};
             }
             document.getElementById("recipeSearch").oninput = ()=>{this.search()};
             document.getElementById("recipeClearButton").onclick = ()=>{this.clearSorting()};
@@ -3956,11 +3956,12 @@ module.exports = {
         this.search();
     },
 
-    posUpdate: function(){
+    posUpdate: function(Recipe){
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
+        let url = `/recipe/update/${merchant.pos}`;
 
-        fetch("/recipe/update/clover", {
+        fetch(url, {
             method: "GET",
             headers: {
                 "Content-Type": "application/json;charset=utf-8"
@@ -3968,6 +3969,7 @@ module.exports = {
         })
             .then(response => response.json())
             .then((response)=>{
+                console.log(response);
                 let newRecipes = [];
                 for(let i = 0; i < response.new.length; i++){
                     newRecipes.push(new Recipe(
@@ -3996,6 +3998,7 @@ module.exports = {
                 }
             })
             .catch((err)=>{
+                console.log(err);
                 banner.createError("SOMETHING WENT WRONG.  PLEASE REFRESH THE PAGE");
             })
             .finally(()=>{

+ 1 - 1
views/dashboardPage/dashboard.ejs

@@ -213,7 +213,7 @@
 
                     <% if(merchant.pos === "none"){ %>
                         <button class="button mobileHide" onclick="controller.openSidebar('addRecipe')">NEW</button>
-                    <% }else if(merchant.pos === "clover"){ %>
+                    <% }else{ %>
                         <button id="posUpdateRecipe" class="button mobileHide">UPDATE</button>
                     <% } %>
                 </div>

+ 1 - 1
views/dashboardPage/js/dashboard.js

@@ -52,7 +52,7 @@ controller = {
             case "recipeBook":
                 activeButton = document.getElementById("recipeBookBtn");
                 document.getElementById("recipeBookStrand").style.display = "flex";
-                recipeBook.display();
+                recipeBook.display(Recipe);
                 break;
             case "orders":
                 activeButton = document.getElementById("ordersBtn");

+ 8 - 5
views/dashboardPage/js/recipeBook.js

@@ -2,12 +2,12 @@ module.exports = {
     isPopulated: false,
     recipeDivList: [],
 
-    display: function(){
+    display: function(Recipe){
         if(!this.isPopulated){
             this.populateRecipes();
 
-            if(merchant.pos === "clover"){
-                document.getElementById("posUpdateRecipe").onclick = ()=>{this.posUpdate()};
+            if(merchant.pos !== "none"){
+                document.getElementById("posUpdateRecipe").onclick = ()=>{this.posUpdate(Recipe)};
             }
             document.getElementById("recipeSearch").oninput = ()=>{this.search()};
             document.getElementById("recipeClearButton").onclick = ()=>{this.clearSorting()};
@@ -69,11 +69,12 @@ module.exports = {
         this.search();
     },
 
-    posUpdate: function(){
+    posUpdate: function(Recipe){
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
+        let url = `/recipe/update/${merchant.pos}`;
 
-        fetch("/recipe/update/clover", {
+        fetch(url, {
             method: "GET",
             headers: {
                 "Content-Type": "application/json;charset=utf-8"
@@ -81,6 +82,7 @@ module.exports = {
         })
             .then(response => response.json())
             .then((response)=>{
+                console.log(response);
                 let newRecipes = [];
                 for(let i = 0; i < response.new.length; i++){
                     newRecipes.push(new Recipe(
@@ -109,6 +111,7 @@ module.exports = {
                 }
             })
             .catch((err)=>{
+                console.log(err);
                 banner.createError("SOMETHING WENT WRONG.  PLEASE REFRESH THE PAGE");
             })
             .finally(()=>{