Преглед на файлове

Enable editing of recipes

Lee Morgan преди 6 години
родител
ревизия
5b6e21ff39
променени са 5 файла, в които са добавени 124 реда и са изтрити 17 реда
  1. 62 1
      controllers/recipeData.js
  2. 1 0
      routes.js
  3. 47 7
      views/dashboardPage/components/recipeDetails.ejs
  4. 10 9
      views/dashboardPage/controller.js
  5. 4 0
      views/shared/validation.js

+ 62 - 1
controllers/recipeData.js

@@ -41,8 +41,69 @@ module.exports = {
                 return res.json(newRecipe);
             })
             .catch((err)=>{
-                console.log(err);
                 return res.json("Error: unable to save new ingredient");
             });
+    },
+
+    //PUT - Update a single recipe
+    //Inputs:
+    //  req.body: An object representing a single recipe
+    //      _id: id of recipe
+    //      name: name of recipe
+    //      price: price of recipe
+    //      ingredients: list of objects representing ingredients
+    //          ingredient: id of ingredient
+    //          quantity: quantity of ingredient
+    updateRecipe: function(req, res){
+        if(!req.session.user){
+            req.session.error = "Must be logged in to do that";
+            return res.redirect("/");
+        }
+
+        Recipe.findOne({_id: req.body._id})
+            .then((recipe)=>{
+                recipe.name = req.body.name;
+                recipe.price = req.body.price;
+                
+                for(let i = 0; i < req.body.ingredients.length; i++){
+                    let isNew = true;
+                    for(let j = 0; j < recipe.ingredients.length; j++){
+                        if(req.body.ingredients[i].ingredient === recipe.ingredients[j]._id.toString()){
+                            isNew = false;
+                            recipe.ingredients[j].quantity = req.body.ingredients[i].quantity;
+                            break;
+                        }
+                    }
+
+                    if(isNew){
+                        recipe.ingredients.push(req.body.ingredients[i]);
+                    }
+                }
+
+                for(let i = 0; i < recipe.ingredients.length; i++){
+                    let doesntExist = true;
+                    for(let j = 0; j < req.body.ingredients.length; j++){
+                        if(recipe.ingredients[i]._id === req.body.ingredients[j]._id){
+                            doesntExist = false;
+                            break;
+                        }
+                    }
+
+                    if(doesntExist){
+                        recipe.ingredients.splice(i, 1);
+                    }
+                }
+
+                // console.log(recipe);
+
+                return recipe.save()
+            })
+            .then((response)=>{
+                return res.json({});
+            })
+            .catch((err)=>{
+                console.log(err);
+                return res.json("Error: unable to update your recipe");
+            })
     }
 }

+ 1 - 0
routes.js

@@ -32,6 +32,7 @@ module.exports = function(app){
 
     //Recipes
     app.post("/recipe/create", recipeData.createRecipe);
+    app.put("/recipe/update", recipeData.updateRecipe);
 
     //Orders
 

+ 47 - 7
views/dashboardPage/components/recipeDetails.ejs

@@ -33,7 +33,6 @@
 
     <div id="recipePrice">
         <h3>Price</h3>
-        
         <p></p>
         <input type="number" min="0" step="0.01" style="display: none;">
     </div>
@@ -42,9 +41,9 @@
 
     <template id="recipeIngredient">
         <div class="recipeIngredient">
-            <p></p>
             <p></p>
             <input type="number" min="0" step="0.01" style="display: none;">
+            <p></p>
         </div>
     </template>
 
@@ -70,7 +69,9 @@
                     ingredientDiv = template.cloneNode(true);
 
                     ingredientDiv.children[0].innerText = recipe.ingredients[i].ingredient.name;
-                    ingredientDiv.children[1].innerText = `${recipe.ingredients[i].quantity} ${recipe.ingredients[i].ingredient.unit}`;
+                    ingredientDiv.children[2].innerText = `${recipe.ingredients[i].quantity} ${recipe.ingredients[i].ingredient.unit}`;
+                    ingredientDiv._id = recipe.ingredients[i].ingredient._id;
+                    ingredientDiv.name = recipe.ingredients[i].ingredient.name;
 
                     ingredientList.appendChild(ingredientDiv);
                 }
@@ -78,7 +79,7 @@
                 let price = document.querySelector("#recipePrice");
                 price.children[1].style.display = "block";
                 price.children[2].style.display = "none";
-                document.querySelector("#recipePrice p").innerText = `$${(recipe.price / 100).toFixed(2)}`;
+                price.children[1].innerText = `$${(recipe.price / 100).toFixed(2)}`;
 
                 document.querySelector("#recipeUpdate").style.display = "none";
             },
@@ -95,9 +96,9 @@
                 for(let i = 0; i < ingredientDivs.children.length; i++){
                     let div = ingredientDivs.children[i];
 
-                    div.children[1].style.display = "none";
-                    div.children[2].style.display = "block";
-                    div.children[2].placeholder = div.children[1].innerText;
+                    div.children[2].innerText = this.recipe.ingredients[i].ingredient.unit;
+                    div.children[1].style.display = "block";
+                    div.children[1].placeholder = this.recipe.ingredients[i].quantity;
                 }
 
                 let price = document.querySelector("#recipePrice");
@@ -108,6 +109,45 @@
                 document.querySelector("#recipeUpdate").style.display = "block";
             },
 
+            update: function(){
+                let updatedRecipe = {
+                    _id: this.recipe._id,
+                    name: document.querySelector("#recipeNameIn").value || this.recipe.name,
+                    price: Math.round((document.querySelector("#recipePrice").children[2].value * 100)) || this.recipe.price,
+                    ingredients: []
+                }
+
+                let divs = document.querySelector("#recipeIngredientList").children;
+                for(let i = 0; i < divs.length; i++){
+                    updatedRecipe.ingredients.push({
+                        ingredient: divs[i]._id,
+                        quantity: divs[i].children[1].value || divs[i].children[1].placeholder
+                    });
+                }
+
+                if(validator.recipe(updatedRecipe)){
+                    fetch("/recipe/update", {
+                        method: "PUT",
+                        headers: {
+                            "Content-Type": "application/json;charset=utf-8"
+                        },
+                        body: JSON.stringify(updatedRecipe)
+                    })
+                        .then((response) => response.json())
+                        .then((response)=>{
+                            if(typeof(response) === "string"){
+                                banner.createError(response);
+                            }else{
+                                updateRecipes(updatedRecipe);
+                                banner.createNotification("Recipe successfully updated");
+                            }
+                        })
+                        .catch((err)=>{
+                            banner.createError("Something went wrong.  Please refresh the page");
+                        })
+                }
+            },
+
             remove: function(){
                 fetch(`/merchant/recipes/remove/${this.recipe._id}`, {
                     method: "DELETE"

+ 10 - 9
views/dashboardPage/controller.js

@@ -78,6 +78,16 @@ Inputs:
 let updateRecipes = (recipe, remove = false)=>{
     let isNew = true;
     let index = 0;
+
+    for(let i = 0; i < recipe.ingredients.length; i++){
+        for(let j = 0; j < merchant.inventory.length; j++){
+            if(merchant.inventory[j].ingredient._id === recipe.ingredients[i].ingredient){
+                recipe.ingredients[i].ingredient = merchant.inventory[j].ingredient;
+                break;
+            }
+        }
+    }
+
     for(let i = 0; i < merchant.recipes.length; i++){
         if(recipe._id === merchant.recipes[i]._id){
             if(remove){
@@ -97,15 +107,6 @@ let updateRecipes = (recipe, remove = false)=>{
         index = merchant.recipes.length - 1;
     }
 
-    for(let i = 0; i < recipe.ingredients.length; i++){
-        for(let j = 0; j < merchant.inventory.length; j++){
-            if(merchant.inventory[j].ingredient._id === recipe.ingredients[i].ingredient){
-                recipe.ingredients[i].ingredient = merchant.inventory[j].ingredient;
-                break;
-            }
-        }
-    }
-
     recipeBookStrandObj.populateRecipes();
     closeSidebar();
 }

+ 4 - 0
views/shared/validation.js

@@ -166,6 +166,10 @@ let validator = {
             errors.push("Recipe contains duplicate ingredients");
         }
 
+        if(isNaN(newRecipe.price) || newRecipe.price === "" || newRecipe.price< 0){
+            errors.push("Must enter a valid price");
+        }
+
         if(errors.length > 0){
             if(createBanner){
                 for(let error of errors){