فهرست منبع

Move recipes into the merchant schema. Refactor code for db changes.

Lee Morgan 6 سال پیش
والد
کامیت
5655ccfc8a

+ 42 - 45
controllers/home.js

@@ -2,7 +2,6 @@ const axios = require("axios");
 
 const Merchant = require("../models/merchant");
 const Ingredient = require("../models/ingredient");
-const Recipe = require("../models/recipe");
 
 // const merchantId = "HCVKASXH94531";
 // const token = "f1c88a69-e3e4-059a-da06-8858d0636e82";
@@ -12,16 +11,15 @@ const token = "b48068eb-411a-918e-ea64-52007147e42c";
 
 module.exports = {
     displayInventory: (req, res)=>{
-        Merchant.findOne({cloverId: merchantId})
+        Merchant.findOne({posId: merchantId})
             .populate("inventory.ingredient")
-            .populate("recipes")
             .then((merchant)=>{
                 if(merchant){
-                    axios.get(`https://apisandbox.dev.clover.com/v3/merchants/${merchant.cloverId}/orders?filter=clientCreatedTime>=${merchant.lastUpdatedTime}&expand=lineItems&access_token=${token}`)
+                    axios.get(`https://apisandbox.dev.clover.com/v3/merchants/${merchant.posId}/orders?filter=clientCreatedTime>=${merchant.lastUpdatedTime}&expand=lineItems&access_token=${token}`)
                         .then((result)=>{
                             for(let order of result.data.elements){
                                 for(let item of order.lineItems.elements){
-                                    let recipe = merchant.recipes.find(r => r.cloverId === item.item.id);
+                                    let recipe = merchant.recipes.find(r => r.posId === item.item.id);
                                     if(recipe){
                                         for(let ingredient of recipe.ingredients){
                                             let inventoryIngredient = {};
@@ -90,46 +88,39 @@ module.exports = {
     createMerchant: (req, res)=>{
         let data = JSON.parse(req.body.data);
 
-        Recipe.create(data.recipes)
-            .then((recipes)=>{
-                axios.get(`https://apisandbox.dev.clover.com/v3/merchants/${merchantId}?access_token=${token}`)
-                    .then((merchant)=>{
-                        let newMerchant = new Merchant({
-                            name: merchant.data.name,
-                            cloverId: merchant.data.id,
-                            lastUpdatedTime: Date.now(),
-                            inventory: [],
-                            recipes: []
-                        });
+        axios.get(`https://apisandbox.dev.clover.com/v3/merchants/${merchantId}?access_token=${token}`)
+            .then((merchant)=>{
+                let newMerchant = new Merchant({
+                    name: merchant.data.name,
+                    posId: merchant.data.id,
+                    lastUpdatedTime: Date.now(),
+                    inventory: [],
+                    recipes: []
+                });
 
-                        for(let ingredient of data.ingredients){
-                            let newIngredient = {
-                                ingredient: ingredient.id,
-                                quantity: parseInt(ingredient.quantity)
-                            }
-                            newMerchant.inventory.push(newIngredient);
-                        }
+                for(let ingredient of data.ingredients){
+                    let newIngredient = {
+                        ingredient: ingredient.id,
+                        quantity: parseInt(ingredient.quantity)
+                    }
+                    newMerchant.inventory.push(newIngredient);
+                }
 
-                        for(let recipe of recipes){
-                            newMerchant.recipes.push(recipe._id);
-                        }
+                for(let recipe of data.recipes){
+                    newMerchant.recipes.push(recipe);
+                }
 
-                        newMerchant.save()
-                            .then((newMerchant)=>{
-                                return res.redirect("/");
-                            })
-                            .catch((err)=>{
-                                console.log(err);
-                                return res.render("error");
-                            })
+                newMerchant.save()
+                    .then((newMerchant)=>{
+                        return res.redirect("/");
                     })
                     .catch((err)=>{
                         console.log(err);
-                    });
+                        return res.render("error");
+                    })
             })
             .catch((err)=>{
                 console.log(err);
-                return res.render("error");
             });
     },
 
@@ -216,16 +207,11 @@ module.exports = {
     },
 
     displayRecipes: function(req, res){
-        Merchant.findOne({cloverId: merchantId})
-            .populate({
-                path: "recipes",
-                populate: {
-                    path: "ingredients.id",
-                    model: "Ingredient"
-                }
-            })
+        Merchant.findOne({posId: merchantId})
+            .populate("recipes.ingredients.ingredient")
             .then((merchant)=>{
-                return res.render("recipesPage/recipes", {recipes: merchant.recipes});
+                console.log(merchant.recipes[0].ingredients);
+                return res.render("recipesPage/recipes", {merchant: merchant});
             })
             .catch((err)=>{
                 console.log(err);
@@ -283,6 +269,17 @@ module.exports = {
             .catch((err)=>{
                 console.log(err);
                 res.render("error");
+            });
+    },
+
+    updateMerchant: function(req, res){
+        Merchant.updateOne({_id: req.body._id}, req.body)
+            .then((merchant)=>{
+                return res.json(merchant);
             })
+            .catch((err)=>{
+                console.log(err);
+                return res.render("error");
+            });
     }
 }

+ 21 - 3
models/merchant.js

@@ -5,7 +5,7 @@ const MerchantSchema = new mongoose.Schema({
         type: String,
         required: true
     },
-    cloverId: {
+    posId: {
         type: String,
         required: true
     },
@@ -26,8 +26,26 @@ const MerchantSchema = new mongoose.Schema({
         }
     }],
     recipes: [{
-        type: mongoose.Schema.Types.ObjectId,
-        ref: "Recipe"
+        posId: {
+            type: String,
+            required: true
+        },
+        name: {
+            type: String,
+            required: true,
+        },
+        ingredients: [{
+            ingredient: {
+                type: mongoose.Schema.Types.ObjectId,
+                ref: "Ingredient",
+                required: [true, "Must provide ingredient"]
+            },
+            quantity: {
+                type: Number,
+                min: [0, "Cannot have a negative quantity"],
+                required: [true, "Must provide a quantity"]
+            }
+        }]
     }]
 });
 

+ 0 - 27
models/recipe.js

@@ -1,27 +0,0 @@
-const mongoose = require("mongoose");
-
-const RecipeSchema = new mongoose.Schema({
-    cloverId: {
-        type: String,
-        required: true
-    },
-    name: {
-        type: String,
-        required: true,
-        minlength: [3, "Name of recipe must contain at least three characters"]
-    },
-    ingredients: [{
-        id: {
-            type: mongoose.Schema.Types.ObjectId,
-            ref: "Ingredient",
-            required: [true, "Must provide ingredient"]
-        },
-        quantity: {
-            type: Number,
-            min: [0, "Cannot have a negative quantity"],
-            required: [true, "Must provide a quantity"]
-        }
-    }]
-});
-
-module.exports = mongoose.model("Recipe", RecipeSchema);

+ 2 - 1
routes.js

@@ -5,11 +5,12 @@ module.exports = function(app){
     app.get("/merchant/new", home.merchantSetup);
     app.get("/getrecipes", home.getRecipes);
     app.post("/merchant/create", home.createMerchant);
+    app.post("/merchant/update", home.updateMerchant);
     app.post("/ingredients/create", home.createNewIngredients);
     app.post("/ingredients/update", home.updateIngredient);
     app.post("/ingredients/remove", home.removeIngredient);
     app.post("/ingredients/createone", home.createIngredient);
     app.get("/recipes", home.displayRecipes);
     app.post("/recipes/ingredients/remove", home.deleteRecipeIngredient);
-    app.post("/recipes/ingredients/update", home.updateRecipeIngredient);
+    // app.post("/recipes/ingredients/update", home.updateRecipeIngredient);
 }

+ 0 - 3
views/merchantSetupPage/merchantSetup.js

@@ -1,3 +0,0 @@
-
-
-

+ 2 - 2
views/merchantSetupPage/recipeSetup.js

@@ -132,14 +132,14 @@ let recipeSetup = {
         if(isValid){
             for(let recipe of this.recipeData){
                 let newRecipe = {
-                    cloverId: recipe.id,
+                    posId: recipe.id,
                     name: recipe.name,
                     ingredients: []
                 };
 
                 for(let ingredient of recipe.ingredients){
                     newRecipe.ingredients.push({
-                        id: ingredient.id,
+                        ingredient: ingredient.id,
                         quantity: ingredient.quantity
                     });
                 }

+ 1 - 1
views/recipesPage/recipes.ejs

@@ -26,7 +26,7 @@
             </table>
         </div>
 
-        <script>let recipes = <%- JSON.stringify(recipes) %>;</script>
+        <script>let merchant = <%- JSON.stringify(merchant) %>;</script>
         <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
         <script src="../shared/validation.js"></script>
         <script src="/recipesPage/recipes.js"></script>

+ 16 - 32
views/recipesPage/recipes.js

@@ -7,7 +7,7 @@ let recipesPage = {
             body.removeChild(body.firstChild);
         }
         
-        for(let recipe of recipes){
+        for(let recipe of merchant.recipes){
             let recipeDiv = document.createElement("div");
             recipeDiv.classList = "recipe-card";
             recipeDiv.onclick = ()=>{this.displayOneRecipe(recipe)};
@@ -22,7 +22,7 @@ let recipesPage = {
 
             for(let ingredient of recipe.ingredients){
                 let ul = document.createElement("li");
-                ul.innerText = ingredient.id.name;
+                ul.innerText = ingredient.ingredient.name;
                 ingredientList.appendChild(ul);
             }
         }
@@ -45,11 +45,11 @@ let recipesPage = {
             tbody.appendChild(row);
 
             let name = document.createElement("td");
-            name.innerText = ingredient.id.name;
+            name.innerText = ingredient.ingredient.name;
             row.appendChild(name);
 
             let quantity = document.createElement("td");
-            quantity.innerText = `${ingredient.quantity} ${ingredient.id.unitType}`;
+            quantity.innerText = `${ingredient.quantity} ${ingredient.ingredient.unitType}`;
             row.appendChild(quantity);
 
             let actions = document.createElement("td");
@@ -71,8 +71,16 @@ let recipesPage = {
     //Delete ingredient from database
     deleteIngredient: function(recipeId, ingredientId, row){
         row.parentNode.removeChild(row);
+
+        let updateRecipe = merchant.recipes.find(r => r._id === recipeId);
+        for(let i = 0; i < updateRecipe.ingredients.length; i++){
+            if(updateRecipe.ingredients[i]._id === ingredientId){
+                updateRecipe.ingredients.splice(i, 1);
+                break;
+            }
+        }
         
-        axios.post("/recipes/ingredients/remove", {recipeId: recipeId, ingredientId:ingredientId})
+        axios.post("/merchant/update", merchant)
             .then((result)=>{
                 banner.createNotification("Ingredient has been removed from recipe");
             })
@@ -96,7 +104,7 @@ let recipesPage = {
         td.appendChild(input);
 
         let para = document.createElement("p");
-        para.innerText = ingredient.id.unitType;
+        para.innerText = ingredient.ingredient.unitType;
         td.appendChild(para);
 
         let button = row.children[2].children[0];
@@ -110,13 +118,13 @@ let recipesPage = {
         while(td.children.length > 0){
             td.removeChild(td.firstChild);
         }
-        td.innerText = `${ingredient.quantity} ${ingredient.id.unitType}`;
+        td.innerText = `${ingredient.quantity} ${ingredient.ingredient.unitType}`;
 
         let button = row.children[2].children[0];
         button.innerText = "Edit";
         button.onclick = ()=>{this.editIngredient(row, ingredient);};
 
-        axios.post("/recipes/ingredients/update", {recipeId: row.recipeId, ingredient: ingredient})
+        axios.post("/merchant/update", merchant)
             .then((recipe)=>{
                 banner.createNotification("Ingredient successfully updated");
             })
@@ -124,30 +132,6 @@ let recipesPage = {
                 console.log(err);
                 banner.createError("There was an error and the ingredient could not be updated");
             });
-    },
-
-    deleteRecipe: function(recipe){
-        for(let i = 0; i < recipes.length; i++){
-            if(recipes[i]._id === recipe._id){
-                recipes.splice(i, 1);
-                break;
-            }
-        }
-
-        let ingredientDiv = document.querySelector("#ingredient");
-        let recipesDiv = document.querySelector("#recipes");
-        ingredientDiv.style.display = "none";
-        recipesDiv.style.display = "flex";
-        this.displayRecipes();
-
-        axios.post("recipes/remove", {id: recipe._id})
-            .then((recipe)=>{
-                banner.createNotification("Recipe removed");
-            })
-            .catch((err)=>{
-                console.log(err);
-                banner.createError("There was an error and the recipe could not be removed");
-            });
     }
 }