Kaynağa Gözat

Merge branch 'development'

Lee Morgan 5 yıl önce
ebeveyn
işleme
1c24bdda08

+ 28 - 0
controllers/helper.js

@@ -1,6 +1,7 @@
 const axios = require("axios");
 
 const Transaction = require("../models/transaction.js");
+const Merchant = require("../models/merchant.js");
 
 module.exports = {
     getCloverData: async function(merchant){
@@ -181,5 +182,32 @@ module.exports = {
             .catch((err)=>{
                 return "ERROR: UNABLE TO UPDATE TRANSACTION DATA";
             });
+    },
+
+    /*
+    Updates the quanties of ingredients from a list of transactions
+    ingredients = Object. keys = ingredient ids, values = quantity to change (g)
+    user = id of logged in user
+    */
+    updateIngredientQuantities: function(ingredients, user){
+        Merchant.findOne({_id: user})
+            .then((merchant)=>{
+                let keys = Object.keys(ingredients);
+
+                for(let i = 0; i < keys.length; i++){
+                    for(let j = 0; j < merchant.inventory.length; j++){
+                        if(merchant.inventory[j].ingredient._id.toString() === keys[i]){
+                            merchant.inventory[j].quantity -= ingredients[keys[i]];
+
+                            break;
+                        }
+                    }
+                }
+
+                return merchant.save();
+            })
+            .catch((err)=>{
+                return false;
+            });
     }
 }

+ 52 - 0
controllers/ingredientData.js

@@ -1,5 +1,6 @@
 const Merchant = require("../models/merchant");
 const Ingredient = require("../models/ingredient");
+const InventoryAdjustment = require("../models/inventoryAdjustment.js");
 const Validator = require("./validator.js");
 
 module.exports = {
@@ -67,5 +68,56 @@ module.exports = {
             .catch((err)=>{
                 return res.json("ERROR: UNABLE TO CREATE NEW INGREDIENT");
             });
+    },
+
+    /*
+    POST - Updates data for a single ingredient
+    req.body = {
+        id: id of the ingredient,
+        name: new name of the ingredient,
+        quantity: new quantity of the unit (in grams),
+        category: new category of the unit,
+        defaultUnit: new default unit of the ingredient
+    }
+    */
+    updateIngredient: function(req, res){
+        if(!req.session.user){
+            req.session.error = "MUST BE LOGGED IN TO DO THAT";
+            return res.redirect("/");
+        }
+
+        Ingredient.findOne({_id: req.body.id})
+            .then((ingredient)=>{
+                ingredient.name = req.body.name,
+                ingredient.category = req.body.category
+
+                return ingredient.save();
+            })
+            .then((ingredient)=>{
+                return Merchant.findOne({_id: req.session.user})
+            })
+            .then((merchant)=>{
+                for(let i = 0; i < merchant.inventory.length; i++){
+                    if(merchant.inventory[i].ingredient.toString() === req.body.id){
+                        merchant.inventory[i].quantity = req.body.quantity;
+                        merchant.inventory[i].defaultUnit = req.body.defaultUnit;
+
+                        new InventoryAdjustment({
+                            date: new Date(),
+                            merchant: req.session.user,
+                            ingredient: req.body.id,
+                            quantity: req.body.quantity - merchant.inventory[i].quantity
+                        }).save().catch(()=>{});
+                    }
+                }
+
+                return merchant.save();
+            })
+            .then((merchant)=>{
+                return res.json({});
+            })
+            .catch((err)=>{
+                return res.json("ERROR: UNABLE TO UPDATE INGREDIENT");
+            });
     }
 }

+ 8 - 63
controllers/merchantData.js

@@ -237,58 +237,6 @@ module.exports = {
             });
     },
 
-    /*
-    //POST - Adds an ingredient to merchant's inventory
-    req.body = [{
-        id: ingredient id,
-        quantity: quantity of ingredient for the merchant
-        defaultUnit: default unit of measurement to display
-    }]
-    */
-    addMerchantIngredient: function(req, res){
-        if(!req.session.user){
-            req.session.error = "MUST BE LOGGED IN TO DO THAT";
-            return res.redirect("/");
-        }
-
-        let validation;
-        for(let i = 0; i < req.body.length; i++){
-            validation = Validator.quantity(req.body[i].quantity);
-            if(validation !== true){
-                return res.json(validation);
-            }
-        }
-        
-
-        Merchant.findOne({_id: req.session.user})
-            .then((merchant)=>{
-                for(let i = 0; i < req.body.length; i++){
-                    for(let j = 0; j < merchant.inventory.length; j++){
-                        if(merchant.inventory[j].ingredient.toString() === req.body[i].id){
-                            return res.json("ERROR: DUPLICATE INGREDIENT DETECTED");
-                        }
-                    }
-                    
-                    merchant.inventory.push({
-                        ingredient: req.body[i].id,
-                        quantity: req.body[i].quantity,
-                        defaultUnit: req.body[i].defaultUnit
-                    });
-                }
-
-                merchant.save()
-                    .then((newMerchant)=>{
-                        return res.json({});
-                    })
-                    .catch((err)=>{
-                        return res.json("ERROR: UNABLE TO SAVE NEW INGREDIENT");
-                    });
-            })
-            .catch((err)=>{
-                return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
-            });
-    },
-
     //POST - Removes an ingredient from the merchant's inventory
     removeMerchantIngredient: function(req, res){
         if(!req.session.user){
@@ -380,25 +328,22 @@ module.exports = {
                         date: Date.now(),
                         merchant: req.session.user,
                         ingredient: req.body[i].id,
-                        quantity: req.body[i].quantity - updateIngredient.quantity
+                        quantity: req.body[i].quantity - updateIngredient.quantity,
                     }));
 
                     updateIngredient.quantity = req.body[i].quantity;
                 }
 
-                merchant.save()
-                    .then((newMerchant)=>{
-                        res.json({});
+                return merchant.save();
+            })
+            .then((newMerchant)=>{
+                res.json({});
 
-                        InventoryAdjustment.create(adjustments).catch(()=>{});
-                        return;
-                    })
-                    .catch((err)=>{
-                        return res.json("ERROR: UNABLE TO SAVE DATA");
-                    })
+                InventoryAdjustment.create(adjustments).catch(()=>{});
+                return;
             })
             .catch((err)=>{
-                return res.json("ERROR: UNABLE TO RETRIEVE DATA");
+                return res.json("ERROR: UNABLE TO UPDATE DATA");
             });        
     },
 

+ 9 - 1
controllers/transactionData.js

@@ -1,6 +1,8 @@
 const Transaction = require("../models/transaction");
 const Merchant = require("../models/merchant");
 
+const helper = require("./helper.js");
+
 const ObjectId = require("mongoose").Types.ObjectId;
 
 module.exports = {
@@ -58,8 +60,12 @@ module.exports = {
         date: date of the transaction,
         recipes: [{
             recipe: id of the recipe to add,
-            quantity: quantity of the recipe sold
+            quantity: quantity of the recipe sold (in main unit),
         }]
+        ingredientUpdates: an object that contains all of the ingredients that
+            need to be updated as well as the amount to change. 
+            keys = id
+            values = quantity to change in grams
     }
     */
     createTransaction: function(req, res){
@@ -75,6 +81,8 @@ module.exports = {
             recipes: req.body.recipes
         });
 
+        helper.updateIngredientQuantities(req.body.ingredientUpdates, req.session.user);
+
         newTransaction.save()
             .then((response)=>{
                 return res.json(response);

+ 3 - 1
package.json

@@ -6,7 +6,9 @@
   "scripts": {
     "test": "echo \"Error: no test specified\" && exit 1",
     "start": "node app.js",
-    "watch-js": "watchify views/dashboardPage/js/dashboard.js -o views/dashboardPage/bundle.js"
+    "build": "watchify ./views/dashboardPage/js/dashboard.js -o ./views/dashboardPage/bundle.js",
+    "nodemon": "nodemon app.js",
+    "dev": "npm run build | npm run nodemon"
   },
   "repository": {
     "type": "git",

+ 2 - 2
routes.js

@@ -18,15 +18,15 @@ module.exports = function(app){
     app.get("/merchant/create/clover", merchantData.createMerchantClover);
     app.get("/merchant/create/square", merchantData.createMerchantSquare);
     app.delete("/merchant/recipes/remove/:id", merchantData.removeRecipe);
-    app.post("/merchant/ingredients/add", merchantData.addMerchantIngredient);
     app.delete("/merchant/ingredients/remove/:id", merchantData.removeMerchantIngredient);
     app.put("/merchant/ingredients/update/:id/:unit", merchantData.ingredientDefaultUnit);
-    app.put("/merchant/ingredients/update", merchantData.updateMerchantIngredient);
+    app.put("/merchant/ingredients/update", merchantData.updateMerchantIngredient); //also updates some data in ingredients
     app.post("/merchant/password", merchantData.updatePassword);
 
     //Ingredients
     app.get("/ingredients", ingredientData.getIngredients);
     app.post("/ingredients/create", ingredientData.createIngredient);  //also adds to merchant
+    app.put("/ingredients/update", ingredientData.updateIngredient);
 
     //Recipes
     app.post("/recipe/create", recipeData.createRecipe);

Dosya farkı çok büyük olduğundan ihmal edildi
+ 0 - 0
views/dashboardPage/bundle.js


+ 4 - 4
views/dashboardPage/dashboard.css

@@ -262,20 +262,20 @@ Home Strand
     }
 
         .ingredientCheck p:first-of-type{
-            width: 37%;
+            width: 40%;
             font-weight: 300;
             font-size: 15px;
             margin-right: 25px;
         }
 
         .ingredientCheck p:last-of-type{
-            width: 25%
+            width: 15%
         }
 
         .numberInput{
             display: flex;
             justify-content: center;
-            width: 37%;
+            width: 45%;
             margin-right: 25px;
         }
 
@@ -300,7 +300,7 @@ Home Strand
             }
 
             .numberInput input{
-                width: 40%;
+                width: 55%;
                 font-size: 15px;
                 text-align: center;
             }

+ 1 - 2
views/dashboardPage/dashboard.ejs

@@ -150,7 +150,7 @@
                 <div class="strandHead">
                     <h1 class="strandTitle">INGREDIENT INVENTORY</h1>
 
-                    <button class="button mobileHide" onclick="controller.openSidebar('addIngredients')">NEW</button>
+                    <button class="button mobileHide" onclick="controller.openSidebar('newIngredient')">NEW</button>
                 </div>
 
                 <div class="searchBar">
@@ -366,7 +366,6 @@
         </div>
 
         <div id="sidebarDiv" class="sidebarHide">
-            <% include ./sidebars/addIngredients %>
             <% include ./sidebars/newIngredient %>
             <% include ./sidebars/ingredientDetails %>
             <% include ./sidebars/recipeDetails %>

+ 31 - 8
views/dashboardPage/js/Merchant.js

@@ -65,14 +65,14 @@ class Merchant{
     editIngredients(ingredients, remove = false, isOrder = false){
         for(let i = 0; i < ingredients.length; i++){
             let isNew = true;
-            for(let j = 0; j < merchant.ingredients.length; j++){
-                if(merchant.ingredients[j].ingredient === ingredients[i].ingredient){
+            for(let j = 0; j < this.ingredients.length; j++){
+                if(this.ingredients[j].ingredient === ingredients[i].ingredient){
                     if(remove){
-                        merchant.ingredients.splice(j, 1);
+                        this.ingredients.splice(j, 1);
                     }else if(!remove && isOrder){
-                        merchant.ingredients[j].quantity += ingredients[i].quantity;
+                        this.ingredients[j].quantity += ingredients[i].quantity;
                     }else{
-                        merchant.ingredients[j].quantity = ingredients[i].quantity;
+                        this.ingredients[j].quantity = ingredients[i].quantity;
                     }
     
                     isNew = false;
@@ -81,7 +81,7 @@ class Merchant{
             }
     
             if(isNew){
-                merchant.ingredients.push({
+                this.ingredients.push({
                     ingredient: ingredients[i].ingredient,
                     quantity: parseFloat(ingredients[i].quantity),
                     defaultUnit: ingredients[i].defaultUnit
@@ -117,7 +117,7 @@ class Merchant{
             }
 
             if(isNew){
-                merchant.recipes.push(recipes[i]);
+                this.recipes.push(recipes[i]);
             }
         }
 
@@ -156,7 +156,14 @@ class Merchant{
         controller.closeSidebar();
     }
 
-    editTransactions(transaction, remove = false){
+    /*
+    transaction = Transaction Object to add
+    ingredients = The ingredients that need to be updated
+        keys = ingredient ids
+        values = quantity to change in grams
+    remove = If true, removes transaction
+    */
+    editTransactions(transaction, ingredients, remove = false, ){
         let isNew = true;
         for(let i = 0; i < this.transactions.length; i++){
             if(this.transactions[i] === transaction){
@@ -174,6 +181,22 @@ class Merchant{
             this.transactions.sort((a, b) => a.date > b.date ? 1 : -1);
         }
 
+        let keys = Object.keys(ingredients);
+        for(let i = 0; i < keys.length; i++){
+            for(let j = 0; j < this.ingredients.length; j++){
+                if(this.ingredients[j].ingredient.id === keys[i]){
+                    if(remove === false){
+                        this.ingredients[j].quantity -= ingredients[keys[i]];
+                    }else{
+                        this.ingredients[j].quantity += ingredients[keys[i]];
+                    }
+
+                    break;
+                }
+            }
+        }
+
+        controller.updateData("ingredient");
         controller.updateData("transaction");
         controller.closeSidebar();
     }

+ 0 - 224
views/dashboardPage/js/addIngredients.js

@@ -1,224 +0,0 @@
-let addIngredients = {
-    isPopulated: false,
-    fakeMerchant: {},
-    chosenIngredients: [],
-
-    display: function(Merchant){
-        if(!this.isPopulated){
-            let loader = document.getElementById("loaderContainer");
-            loader.style.display = "flex";
-
-            fetch("/ingredients")
-                .then((response) => response.json())
-                .then((response)=>{
-                    if(typeof(response) === "string"){
-                        banner.createError(response);
-                    }else{
-                        for(let i = 0; i < merchant.ingredients.length; i++){
-                            for(let j = 0; j < response.length; j++){
-                                if(merchant.ingredients[i].ingredient.id === response[j]._id){
-                                    response.splice(j, 1);
-                                    break;
-                                }
-                            }
-                        }
-                        
-                        for(let i = 0; i < response.length; i++){
-                            response[i] = {ingredient: response[i]}
-                        }
-                        this.fakeMerchant = new Merchant({
-                                name: "none",
-                                inventory: response,
-                                recipes: [],
-                            },
-                            []
-                        );
-
-                        this.populateAddIngredients(true);
-                    }
-                })
-                .catch((err)=>{
-                    banner.createError("UNABLE TO RETRIEVE DATA");
-                })
-                .finally(()=>{
-                    loader.style.display = "none";
-                });
-
-            this.isPopulated = true;
-        }
-    },
-
-    populateAddIngredients: function(newRequest = false){
-        let addIngredientsDiv = document.getElementById("addIngredientList");
-        let categoryTemplate = document.getElementById("addIngredientsCategory");
-        let ingredientTemplate = document.getElementById("addIngredientsIngredient");
-
-        let categories = this.fakeMerchant.categorizeIngredients();
-
-        while(addIngredientsDiv.children.length > 0){
-            addIngredientsDiv.removeChild(addIngredientsDiv.firstChild);
-        }
-        for(let i = 0; i < categories.length; i++){
-            let categoryDiv = categoryTemplate.content.children[0].cloneNode(true);
-            categoryDiv.children[0].children[0].innerText = categories[i].name;
-            categoryDiv.children[0].children[1].onclick = ()=>{this.toggleAddIngredient(categoryDiv)};
-            categoryDiv.children[1].style.display = "none";
-            categoryDiv.children[0].children[1].children[1].style.display = "none";
-
-            addIngredientsDiv.appendChild(categoryDiv);
-            
-            for(let j = 0; j < categories[i].ingredients.length; j++){
-                let ingredientDiv = ingredientTemplate.content.children[0].cloneNode(true);
-                ingredientDiv.children[0].children[0].innerText = categories[i].ingredients[j].ingredient.name;
-                ingredientDiv.children[0].children[1].onclick = ()=>{this.addOne(ingredientDiv)};
-                ingredientDiv.ingredient = categories[i].ingredients[j].ingredient;
-
-                categoryDiv.children[1].appendChild(ingredientDiv);
-            }
-        }
-
-        if(newRequest){
-            let myIngredients = document.getElementById("myIngredients");
-            while(myIngredients.children.length > 0){
-                myIngredients.removeChild(myIngredients.firstChild);
-            }
-        }
-
-        document.getElementById("addIngredientsBtn").onclick = ()=>{this.submit()};
-        document.getElementById("openNewIngredient").onclick = ()=>{controller.openSidebar("newIngredient")};
-    },
-
-    toggleAddIngredient: function(categoryElement){
-        let button = categoryElement.children[0].children[1];
-        let ingredientDisplay = categoryElement.children[1];
-
-        if(ingredientDisplay.style.display === "none"){
-            ingredientDisplay.style.display = "flex";
-
-            button.children[0].style.display = "none";
-            button.children[1].style.display = "block";
-        }else{
-            ingredientDisplay.style.display = "none";
-
-            button.children[0].style.display = "block";
-            button.children[1].style.display = "none";
-        }
-    },
-
-    addOne: function(element){
-        element.parentElement.removeChild(element);
-        document.getElementById("myIngredients").appendChild(element);
-        document.getElementById("myIngredientsDiv").style.display = "flex";
-        element.children[1].style.display = "flex";
-
-        for(let i = 0; i < this.fakeMerchant.ingredients.length; i++){
-            if(this.fakeMerchant.ingredients[i].ingredient === element.ingredient){
-                this.fakeMerchant.ingredients.splice(i, 1);
-                this.chosenIngredients.push(element.ingredient);
-                break;
-            }
-        }
-
-        let select = element.children[1].children[1];
-        let units = merchant.units[element.ingredient.unitType];
-        for(let i = 0; i < units.length; i++){
-            let option = document.createElement("option");
-            option.innerText = units[i].toUpperCase();
-            option.type = element.ingredient.unitType;
-            option.value = units[i];
-            select.appendChild(option);
-        }
-
-        element.children[0].children[1].innerText = "-";
-        element.children[0].children[1].onclick = ()=>{this.removeOne(element)};
-    },
-
-    removeOne: function(element){
-        element.parentElement.removeChild(element);
-        element.children[1].style.display = "none";
-
-        let select = element.children[0].children[1];
-        while(select.children.length > 0){
-            select.removeChild(select.firstChild);
-        }
-
-        element.children[0].children[1].innerText = "+";
-        element.children[0].children[1].onclick = ()=>{this.addOne(element)};
-
-        if(document.getElementById("myIngredients").children.length === 0){
-            document.getElementById("myIngredientsDiv").style.display = "none";
-        }
-
-        for(let i = 0; i < this.chosenIngredients.length; i++){
-            if(this.chosenIngredients[i] === element.ingredient){
-                this.chosenIngredients.splice(i, 1);
-                this.fakeMerchant.ingredients.push({
-                    ingredient: element.ingredient
-                });
-                break;
-            }
-        }
-        
-        this.populateAddIngredients();
-    },
-
-    submit: function(){
-        let ingredients = document.getElementById("myIngredients").children;
-        let newIngredients = [];
-        let fetchable = [];
-
-        for(let i = 0; i < ingredients.length; i++){
-            let quantity = ingredients[i].children[1].children[0].value;
-            let unit = ingredients[i].children[1].children[1].value;
-
-            if(quantity === ""){
-                banner.createError("PLEASE ENTER A QUANTITY FOR EACH INGREDIENT YOU WANT TO ADD TO YOUR INVENTORY");
-                return;
-            }
-            quantity = controller.convertToMain(unit, quantity);
-
-            let newIngredient = {
-                ingredient: ingredients[i].ingredient,
-                quantity: quantity
-            }
-            newIngredient.ingredient.unit = unit;
-
-            newIngredients.push(newIngredient);
-
-            fetchable.push({
-                id: ingredients[i].ingredient.id,
-                quantity: quantity,
-                defaultUnit: unit
-            });
-        }
-
-        let loader = document.getElementById("loaderContainer");
-        loader.style.display = "flex";
-
-        fetch("/merchant/ingredients/add", {
-            method: "POST",
-            headers: {
-                "Content-Type": "application/json;charset=utf-8"
-            },
-            body: JSON.stringify(fetchable)
-        })
-            .then((response) => response.json())
-            .then((response)=>{
-                if(typeof(response) === "string"){
-                    banner.createError(response);
-                }else{
-                    merchant.editIngredients(newIngredients);
-                    this.isPopulated = false;
-                    banner.createNotification("ALL INGREDIENTS ADDED");
-                }
-            })
-            .catch((err)=>{
-                banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
-            })
-            .finally(()=>{
-                loader.style.display = "none";
-            });
-    }
-}
-
-module.exports = addIngredients;

+ 2 - 7
views/dashboardPage/js/dashboard.js

@@ -4,7 +4,6 @@ const recipeBook = require("./recipeBook.js");
 const orders = require("./orders.js");
 const transactions = require("./transactions.js");
 
-const addIngredients = require("./addIngredients.js");
 const ingredientDetails = require("./ingredientDetails.js");
 const newIngredient = require("./newIngredient.js");
 const newOrder = require("./newOrder.js");
@@ -221,9 +220,9 @@ controller = {
     updateData: function(item){
         switch(item){
             case "ingredient":
-                home.drawInventoryCheckCard();
+                home.isPopulated = false;
                 ingredients.populateByProperty("category");
-                addIngredients.isPopulated = false;
+                home.isPopulated = false;
                 break;
             case "recipe":
                 transactions.isPopulated = false;
@@ -236,10 +235,6 @@ controller = {
                 transactions.isPopulated = false;
                 transactions.display(Transaction);
                 break;
-            case "unit":
-                home.isPopulated = false;
-                ingredients.populateByProperty("category");
-                break;
         }
     }
 }

+ 5 - 4
views/dashboardPage/js/home.js

@@ -93,13 +93,14 @@ let home = {
         for(let i = 0; i < rands.length; i++){
             let ingredientCheck = template.cloneNode(true);
             let input = ingredientCheck.children[1].children[1];
+            const ingredient = merchant.ingredients[rands[i]];
 
-            ingredientCheck.ingredient = merchant.ingredients[rands[i]];
-            ingredientCheck.children[0].innerText = merchant.ingredients[rands[i]].ingredient.name;
+            ingredientCheck.ingredient = ingredient;
+            ingredientCheck.children[0].innerText = ingredient.ingredient.name;
             ingredientCheck.children[1].children[0].onclick = ()=>{input.value--};
-            input.value = merchant.ingredients[rands[i]].quantity.toFixed(2);
+            input.value = ingredient.ingredient.convert(ingredient.quantity).toFixed(2);
             ingredientCheck.children[1].children[2].onclick = ()=>{input.value++}
-            ingredientCheck.children[2].innerText = merchant.ingredients[rands[i]].ingredient.unit.toUpperCase();
+            ingredientCheck.children[2].innerText = ingredient.ingredient.unit.toUpperCase();
 
             ul.appendChild(ingredientCheck);
         }

+ 74 - 40
views/dashboardPage/js/ingredientDetails.js

@@ -5,17 +5,22 @@ let ingredientDetails = {
     display: function(ingredient){
         this.ingredient = ingredient;
 
-        document.getElementById("editIngBtn").onclick = ()=>{this.edit()};
-        document.getElementById("removeIngBtn").onclick = ()=>{this.remove(merchant)};
+        document.getElementById("ingredientDetailsCategory").innerText = ingredient.ingredient.category;
+
+        let categoryInput = document.getElementById("detailsCategoryInput");
+        categoryInput.value = "";
+        categoryInput.placeholder = ingredient.ingredient.category;
+
+        document.getElementById("ingredientDetailsName").innerText = ingredient.ingredient.name;
+        
+        let nameInput = document.getElementById("ingredientDetailsNameIn");
+        nameInput.value = "";
+        nameInput.placeholder = ingredient.ingredient.name;
 
-        document.querySelector("#ingredientDetails p").innerText = ingredient.ingredient.category;
-        document.querySelector("#ingredientDetails h1").innerText = ingredient.ingredient.name;
-        let ingredientStock = document.getElementById("ingredientStock");
-        ingredientStock.innerText = `${ingredient.ingredient.convert(ingredient.quantity).toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
-        ingredientStock.style.display = "block";
-        let ingredientInput = document.getElementById("ingredientInput");
-        ingredientInput.value = ingredient.ingredient.convert(ingredient.quantity).toFixed(2);
-        ingredientInput.style.display = "none";
+        let stockInput = document.getElementById("ingredientInput");
+        document.getElementById("ingredientStock").innerText = `${ingredient.ingredient.convert(ingredient.quantity).toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
+        stockInput.value = "";
+        stockInput.placeholder = ingredient.ingredient.convert(ingredient.quantity).toFixed(2);
 
         let quantities = [];
         let now = new Date();
@@ -36,9 +41,8 @@ let ingredientDetails = {
             sum += quantities[i];
         }
 
-        this.dailyUse = sum / quantities.length;
-
-        document.getElementById("dailyUse").innerText = `${ingredient.ingredient.convert(this.dailyUse).toFixed(2)} ${ingredient.ingredient.unit}`;
+        let dailyUse = sum / quantities.length;
+        document.getElementById("dailyUse").innerText = `${ingredient.ingredient.convert(dailyUse).toFixed(2)} ${ingredient.ingredient.unit}`;
 
         let ul = document.getElementById("ingredientRecipeList");
         let recipes = merchant.getRecipesForIngredient(ingredient.ingredient);
@@ -57,17 +61,9 @@ let ingredientDetails = {
 
         let ingredientButtons = document.getElementById("ingredientButtons");
         let units = [];
-        let unitLabel = document.getElementById("displayUnitLabel");
-        let defaultButton = document.getElementById("defaultUnit");
         if(this.ingredient.ingredient.unitType !== "other"){
             units = merchant.units[this.ingredient.ingredient.unitType];
-            unitLabel.style.display = "block";
-            defaultButton.style.display = "block";
-        }else{
-            unitLabel.style.display = "none";
-            defaultButton.style.display = "none";
         }
-        
         while(ingredientButtons.children.length > 0){
             ingredientButtons.removeChild(ingredientButtons.firstChild);
         }
@@ -83,11 +79,24 @@ let ingredientDetails = {
             }
         }
 
-        document.getElementById("defaultUnit").onclick = ()=>{this.changeUnitDefault()};
+        let add = document.querySelectorAll(".editAdd");
+        let remove = document.querySelectorAll(".editRemove");
+
+        for(let i = 0; i < add.length; i++){
+            add[i].style.display = "none";
+        }
+
+        for(let i = 0; i < remove.length; i++){
+            remove[i].style.display = "block";
+        }
+
         document.getElementById("editSubmitButton").onclick = ()=>{this.editSubmit()};
+        document.getElementById("editCancelButton").onclick = ()=>{this.display(this.ingredient)};
+        document.getElementById("editIngBtn").onclick = ()=>{this.edit()};
+        document.getElementById("removeIngBtn").onclick = ()=>{this.remove()};
     },
 
-    remove: function(merchant){
+    remove: function(){
         for(let i = 0; i < merchant.recipes.length; i++){
             for(let j = 0; j < merchant.recipes[i].ingredients.length; j++){
                 if(this.ingredient.ingredient === merchant.recipes[i].ingredients[j].ingredient){
@@ -119,26 +128,53 @@ let ingredientDetails = {
     },
 
     edit: function(){
-        document.getElementById("ingredientStock").style.display = "none";
-        document.getElementById("ingredientInput").style.display = "block";
-        document.getElementById("editSubmitButton").style.display = "block";
+        let add = document.querySelectorAll(".editAdd");
+        let remove = document.querySelectorAll(".editRemove");
+
+        for(let i = 0; i < add.length; i++){
+            add[i].style.display = "flex";
+        }
+
+        for(let i = 0; i < remove.length; i++){
+            remove[i].style.display = "none";
+        }
     },
 
     editSubmit: function(){
-        this.ingredient.quantity = controller.convertToMain(
-            this.ingredient.ingredient.unit,
-            Number(document.getElementById("ingredientInput").value)
-        );
+        let ingredientButtons = document.querySelectorAll(".unitButton");
+        for(let i = 0; i < ingredientButtons.length; i++){
+            if(ingredientButtons[i].classList.contains("unitActive")){
+                this.ingredient.ingredient.unit = ingredientButtons[i].innerText.toLowerCase();
+                break;
+            }
+        }
+
+        const quantityElem = document.getElementById("ingredientInput");
+        if(quantityElem.value !== ""){
+            this.ingredient.quantity = controller.convertToMain(
+                this.ingredient.ingredient.unit,
+                Number(document.getElementById("ingredientInput").value)
+            );
+        }
+
+        const category = document.getElementById("detailsCategoryInput");
+        this.ingredient.ingredient.category = (category.value === "") ? this.ingredient.ingredient.category : category.value;
+
+        const name = document.getElementById("ingredientDetailsNameIn");
+        this.ingredient.ingredient.name = (name.value === "") ? this.ingredient.ingredient.name : name.value;
         
-        let data = [{
+        let data = {
             id: this.ingredient.ingredient.id,
-            quantity: controller.convertToMain(this.ingredient.ingredient.unit, this.ingredient.quantity)
-        }];
+            name: this.ingredient.ingredient.name,
+            quantity: this.ingredient.quantity,
+            category: this.ingredient.ingredient.category,
+            defaultUnit: this.ingredient.ingredient.unit
+        };
 
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
 
-        fetch("/merchant/ingredients/update", {
+        fetch("/ingredients/update", {
             method: "PUT",
             headers: {
                 "Content-Type": "application/json;charset=utf-8"
@@ -151,10 +187,14 @@ let ingredientDetails = {
                     banner.createError(response);
                 }else{
                     merchant.editIngredients([this.ingredient]);
+
+                    this.display(this.ingredient);
+
                     banner.createNotification("INGREDIENT UPDATED");
                 }
             })
             .catch((err)=>{
+                console.log(err);
                 banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
             })
             .finally(()=>{
@@ -163,18 +203,12 @@ let ingredientDetails = {
     },
 
     changeUnit: function(newActive, unit){
-        this.ingredient.ingredient.unit = unit;
-
         let ingredientButtons = document.querySelectorAll(".unitButton");
         for(let i = 0; i < ingredientButtons.length; i++){
             ingredientButtons[i].classList.remove("unitActive");
         }
 
         newActive.classList.add("unitActive");
-
-        controller.updateData("unit");
-        document.getElementById("ingredientStock").innerText = `${this.ingredient.ingredient.convert(this.ingredient.quantity).toFixed(2)} ${this.ingredient.ingredient.unit.toUpperCase()}`;
-        document.getElementById("dailyUse").innerText = `${this.ingredient.ingredient.convert(this.dailyUse).toFixed(2)} ${this.ingredient.ingredient.unit}`;
     },
 
     changeUnitDefault: function(){

+ 20 - 8
views/dashboardPage/js/newTransaction.js

@@ -27,25 +27,37 @@ let newTransaction = {
             return;
         }
         
-        let newTransaction = {
+        let data = {
             date: date,
-            recipes: []
+            recipes: [],
+            ingredientUpdates: {}
         };
 
         for(let i = 0; i < recipeDivs.children.length;  i++){
             let quantity = recipeDivs.children[i].children[1].value;
+            const recipe = recipeDivs.children[i].recipe;
             if(quantity !== "" && quantity > 0){
-                newTransaction.recipes.push({
-                    recipe: recipeDivs.children[i].recipe.id,
+                data.recipes.push({
+                    recipe: recipe.id,
                     quantity: quantity
                 });
+
+                for(let j = 0; j < recipe.ingredients.length; j++){
+                    const ingredient = recipe.ingredients[j];
+
+                    if(data.ingredientUpdates[ingredient.ingredient.id]){
+                        data.ingredientUpdates[ingredient.ingredient.id] += ingredient.quantity * quantity;
+                    }else{
+                        data.ingredientUpdates[ingredient.ingredient.id] = ingredient.quantity * quantity;
+                    }
+                }
             }else if(quantity < 0){
                 banner.createError("CANNOT HAVE NEGATIVE VALUES");
                 return;
             }
         }
 
-        if(newTransaction.recipes.length > 0){
+        if(data.recipes.length > 0){
             let loader = document.getElementById("loaderContainer");
             loader.style.display = "flex";
 
@@ -54,7 +66,7 @@ let newTransaction = {
                 headers: {
                     "Content-Type": "application/json;charset=utf-8"
                 },
-                body: JSON.stringify(newTransaction)
+                body: JSON.stringify(data)
             })
                 .then(response => response.json())
                 .then((response)=>{
@@ -67,8 +79,8 @@ let newTransaction = {
                             response.recipes,
                             merchant
                         );
-                        merchant.editTransactions(transaction);
-                        banner.createNotification("NEW TRANSACTION CREATED");
+                        merchant.editTransactions(transaction, data.ingredientUpdates);
+                        banner.createNotification("NEW TRANSACTION CREATED, INGREDIENTS UPDATED ACCORDINGLY");
                     }
                 })
                 .catch((err)=>{

+ 0 - 64
views/dashboardPage/sidebars/addIngredients.ejs

@@ -1,64 +0,0 @@
-<div id="addIngredients">
-    <div class="sidebarIconButtons">
-        <button class="iconButton" onclick="controller.closeSidebar()">
-            <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-                <line x1="5" y1="12" x2="19" y2="12"></line>
-                <polyline points="12 5 19 12 12 19"></polyline>
-            </svg>
-        </button>
-    </div>
-    
-    <h2>AVAILABLE INGREDIENTS</h2>
-
-    <div id="addIngredientList"></div>
-
-    <div class="lineBorder"></div>
-
-    <div id="myIngredientsDiv">
-        <h2>MY INGREDIENTS</h2>
-
-        <div id="myIngredients"></div>
-
-        <div class="lineBorder"></div>
-    </div>
-
-    <button id="addIngredientsBtn" class="button">CREATE</button>
-
-    <button class="button2Link" id="openNewIngredient">CAN'T FIND WHAT YOU'RE LOOKING FOR? CREATE IT...</button>
-
-    <template id="addIngredientsCategory">
-        <div class="addIngredientsCategory">
-            <div class="categoryHeader">
-                <h5></h5>
-                
-                <button>
-                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-                        <polyline points="6 9 12 15 18 9"></polyline>
-                    </svg>
-
-                    <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-                        <polyline points="18 15 12 9 6 15"></polyline>
-                    </svg>
-                </button>
-            </div>
-
-            <div class="addIngredientsIngredients"></div>
-        </div>
-    </template>
-
-    <template id="addIngredientsIngredient">
-        <div class="addIngredientsIngredient">
-            <div>
-                <p></p>
-
-                <button class="addButton">+</button>
-            </div>
-
-            <div style="display: none;">
-                <input type="number" min="0" step="0.01" placeholder="QUANTITY">
-
-                <select></select>
-            </div>
-        </div>
-    </template>
-</div>

+ 18 - 12
views/dashboardPage/sidebars/ingredientDetails.ejs

@@ -22,36 +22,42 @@
         </button>
     </div>
 
-    <p></p>
+    <p class="editRemove" id="ingredientDetailsCategory"></p>
+
+    <input class="editAdd" id="detailsCategoryInput" type="text">
     
-    <h1></h1>
+    <h1 class="editRemove" id="ingredientDetailsName"></h1>
+
+    <input class="editAdd" id="ingredientDetailsNameIn" type="text">
 
     <div class="lineBorder"></div>
 
     <label>CURRENT STOCK
-        <p id="ingredientStock"></p>
-        <input id="ingredientInput" type="number" min="0" step="0.01" style="display: none;">
+        <p class="editRemove" id="ingredientStock"></p>
+        <input class="editAdd" id="ingredientInput" type="number" min="0" step="0.01">
     </label>
 
     <div class="lineBorder"></div>
 
-    <label>AVERAGE DAILY USE (30 DAYS)
+    <label class="editRemove">AVERAGE DAILY USE (30 DAYS)
         <p id="dailyUse"></p>
     </label>
 
-    <div class="lineBorder"></div>
+    <div class="lineBorder editRemove"></div>
 
-    <label>RECIPES:
+    <label class="editRemove">RECIPES:
         <ul id="ingredientRecipeList"></ul>
     </label>
 
-    <div class="lineBorder"></div>
+    <div class="lineBorder editRemove"></div>
 
-    <label id="displayUnitLabel">DISPLAY UNIT:</label>
+    <label class="editAdd" id="displayUnitLabel" style="display: none">DISPLAY UNIT:</label>
 
-    <div id="ingredientButtons" class="ingredientButtons"></div>
+    <div class="editAdd" id="ingredientButtons" style="display: none"></div>
 
-    <button id="defaultUnit" class="button">SET DEFAULT</button>
+    <div class="buttonBox editAdd" id="editIngredientButtons" style="display: none">
+        <button id="editSubmitButton" class="button">SAVE</button>
 
-    <button id="editSubmitButton" class="button" style="display: none;">SAVE CHANGES</button>
+        <button id="editCancelButton" class="button">CANCEL</button>
+    </div>
 </div>

+ 7 - 132
views/dashboardPage/sidebars/sidebars.css

@@ -202,138 +202,6 @@
         color: rgb(255, 99, 107);
     }
 
-/* 
-Add Ingredients 
-*/
-#addIngredients{
-    flex-direction: column;
-    align-items: center;
-    width: 100%;
-    text-align: center;
-}
-
-    #addIngredients > *{
-        width: 100%;
-    }
-
-    #addIngredientList{
-        display: flex;
-        flex-direction: column;
-        align-items: center;
-        overflow-y: auto;
-        margin-bottom: 15px;
-        max-height: 35%;
-    }
-    
-    #myIngredientsDiv{
-        display: none;
-        flex-direction: column;
-        align-items: center;
-        max-height: 40%;
-    }
-
-        #myIngredients{
-            display: flex;
-            flex-direction: column;
-            width: 100%;
-            overflow-y: auto;
-        }
-
-    #addIngredientsBtn{
-        width: 25%;
-        margin-left: auto;
-    }
-
-    .addIngredientsCategory{
-        width: 90%;
-    }
-
-        .categoryHeader{
-            display: flex;
-            justify-content: space-between;
-            align-items: center;
-            width: 100%;
-            border: 1px solid black;
-            background: rgb(240, 252, 255);
-            border-radius: 5px;
-            padding: 5px;
-        }
-
-            .categoryHeader > button{
-                display: flex;
-                align-items: center;
-                background: none;
-                border: none;
-                padding: 5px;
-                border-radius: 5px;
-                cursor: pointer;
-            }
-
-            .categoryHeader > button:hover{
-                background: rgb(0, 27, 45);
-                color: white;
-            }
-
-        .addIngredientsIngredients{
-            flex-direction: column;
-            padding: 0 20px;
-        }
-
-            .addIngredientsIngredient{
-                display: flex;
-                flex-direction: column;
-                align-items: center;
-                margin: 5px;
-                border: 1px solid black;
-                background: rgb(240, 252, 255);
-                padding: 1px 3px;
-                border-radius: 5px;
-            }
-
-                .addIngredientsIngredient div{
-                    display: flex;
-                    width: 100%;
-                    align-items: center;
-                }
-
-                .addIngredientsIngredient div:first-of-type{
-                    justify-content: space-around;
-                }
-
-                .addIngredientsIngredient div:last-of-type > *{
-                    margin: 0 5px;
-                }
-
-                .addIngredientsIngredient div:last-of-type{
-                    justify-content: center;
-                }
-
-                .addIngredientsIngredient input[type=number]{
-                    width: 100px;
-                }
-
-                .addIngredientsIngredient select{
-                    width: 100px;
-                }
-
-                .addButton{
-                    display: flex;
-                    align-items: center;
-                    justify-content: center;
-                    font-size: 25px;
-                    font-weight: bold;
-                    background: none;
-                    border: none;
-                    border-radius: 5px;
-                    width: 30px;
-                    cursor: pointer;
-                }
-
-                    .addButton:hover{
-                        background:rgb(0, 27, 45);
-                        color: white;
-                    }
-
 /* 
 Ingredient Details 
 */
@@ -418,6 +286,13 @@ Ingredient Details
             color: white;
         }
 
+    .buttonBox{
+        display: flex;
+        justify-content: space-around;
+        width: 100%;
+        margin-top: 50px;
+    }
+
 /* 
 Recipe Details 
 */

Bu fark içinde çok fazla dosya değişikliği olduğu için bazı dosyalar gösterilmiyor