Преглед изворни кода

Merge branch 'development'

Lee Morgan пре 5 година
родитељ
комит
1658b3bb3d
35 измењених фајлова са 1838 додато и 1096 уклоњено
  1. 24 0
      controllers/helper.js
  2. 59 20
      controllers/ingredientData.js
  3. 0 33
      controllers/merchantData.js
  4. 46 52
      controllers/recipeData.js
  5. 31 14
      controllers/validator.js
  6. 15 11
      models/archivedRecipe.js
  7. 1 1
      routes.js
  8. 2 1
      views/dashboardPage/dashboard.ejs
  9. 112 37
      views/dashboardPage/js/Ingredient.js
  10. 441 171
      views/dashboardPage/js/Merchant.js
  11. 189 17
      views/dashboardPage/js/Order.js
  12. 182 13
      views/dashboardPage/js/Recipe.js
  13. 55 8
      views/dashboardPage/js/Transaction.js
  14. 11 9
      views/dashboardPage/js/analytics.js
  15. 20 142
      views/dashboardPage/js/dashboard.js
  16. 134 0
      views/dashboardPage/js/editIngredient.js
  17. 123 0
      views/dashboardPage/js/editRecipe.js
  18. 20 17
      views/dashboardPage/js/home.js
  19. 19 239
      views/dashboardPage/js/ingredientDetails.js
  20. 6 4
      views/dashboardPage/js/ingredients.js
  21. 25 23
      views/dashboardPage/js/newIngredient.js
  22. 57 16
      views/dashboardPage/js/newOrder.js
  23. 21 7
      views/dashboardPage/js/newRecipe.js
  24. 6 13
      views/dashboardPage/js/newTransaction.js
  25. 9 22
      views/dashboardPage/js/orderDetails.js
  26. 27 14
      views/dashboardPage/js/orders.js
  27. 16 17
      views/dashboardPage/js/recipeBook.js
  28. 20 124
      views/dashboardPage/js/recipeDetails.js
  29. 5 13
      views/dashboardPage/js/transactionDetails.js
  30. 8 7
      views/dashboardPage/js/transactions.js
  31. 34 0
      views/dashboardPage/sidebars/editIngredient.ejs
  32. 58 0
      views/dashboardPage/sidebars/editRecipe.ejs
  33. 7 23
      views/dashboardPage/sidebars/ingredientDetails.ejs
  34. 1 28
      views/dashboardPage/sidebars/recipeDetails.ejs
  35. 54 0
      views/dashboardPage/sidebars/sidebars.css

+ 24 - 0
controllers/helper.js

@@ -209,5 +209,29 @@ module.exports = {
             .catch((err)=>{
             .catch((err)=>{
                 return false;
                 return false;
             });
             });
+    },
+
+    convertQuantityToBaseUnit: function(quantity, unit){
+        switch(unit){
+            case "g":return quantity; 
+            case "kg": return quantity * 1000;
+            case "oz": return quantity * 28.3495;
+            case "lb": return quantity * 453.5924;
+            case "ml": return quantity / 1000;
+            case "l": return quantity;
+            case "tsp": return quantity / 202.8842;
+            case "tbsp": return quantity / 67.6278;
+            case "ozfl": return quantity / 33.8141;
+            case "cup": return quantity / 4.1667;
+            case "pt": return quantity / 2.1134;
+            case "qt": return quantity / 1.0567;
+            case "gal": return quantity * 3.7854;
+            case "mm": return quantity / 1000;
+            case "cm": return quantity / 100;
+            case "m": return quantity;
+            case "in": return quantity / 39.3701;
+            case "ft": return quantity / 3.2808;
+            default: return quantity;
+        }
     }
     }
 }
 }

+ 59 - 20
controllers/ingredientData.js

@@ -1,6 +1,8 @@
 const Merchant = require("../models/merchant");
 const Merchant = require("../models/merchant");
 const Ingredient = require("../models/ingredient");
 const Ingredient = require("../models/ingredient");
 const InventoryAdjustment = require("../models/inventoryAdjustment.js");
 const InventoryAdjustment = require("../models/inventoryAdjustment.js");
+
+const Helper = require("./helper.js");
 const Validator = require("./validator.js");
 const Validator = require("./validator.js");
 
 
 module.exports = {
 module.exports = {
@@ -41,27 +43,48 @@ module.exports = {
         if(validation !== true){
         if(validation !== true){
             return res.json(validation);
             return res.json(validation);
         }
         }
+
         validation = Validator.quantity(req.body.quantity);
         validation = Validator.quantity(req.body.quantity);
         if(validation !== true){
         if(validation !== true){
             return res.json(validation);
             return res.json(validation);
         }
         }
-        validation = Validator.quantity(req.body.ingredient.unitSize);
-        if(validation !== true){
-            return res.json(validation);
+
+        if(req.body.ingredient.unitSize){
+            validation = Validator.quantity(req.body.ingredient.unitSize);
+            if(validation !== true){
+                return res.json(validation);
+            }
         }
         }
 
 
-        let ingredientPromise = Ingredient.create((req.body.ingredient));
+        let newIngredient = {};
+        if(req.body.ingredient.specialUnit === "bottle"){
+            newIngredient = new Ingredient({
+                name: req.body.ingredient.name,
+                category: req.body.ingredient.category,
+                unitType: req.body.ingredient.unitType,
+                specialUnit: req.body.ingredient.specialUnit,
+                unitSize: Helper.convertQuantityToBaseUnit(req.body.ingredient.unitSize, req.body.defaultUnit)
+            });
+        }else{
+            newIngredient = new Ingredient(req.body.ingredient);
+        }
+
+        let ingredientPromise = newIngredient.save();
         let merchantPromise = Merchant.findOne({_id: req.session.user});
         let merchantPromise = Merchant.findOne({_id: req.session.user});
-        let newIngredient;
 
 
         Promise.all([ingredientPromise, merchantPromise])
         Promise.all([ingredientPromise, merchantPromise])
             .then((response)=>{
             .then((response)=>{
                 newIngredient = {
                 newIngredient = {
                     ingredient: response[0],
                     ingredient: response[0],
-                    quantity: req.body.quantity,
                     defaultUnit: req.body.defaultUnit
                     defaultUnit: req.body.defaultUnit
                 }
                 }
 
 
+                if(response[0].specialUnit === "bottle"){
+                    newIngredient.quantity = req.body.quantity * response[0].unitSize;
+                }else{
+                    newIngredient.quantity = Helper.convertQuantityToBaseUnit(req.body.quantity, req.body.defaultUnit);
+                }
+
                 response[1].inventory.push(newIngredient);
                 response[1].inventory.push(newIngredient);
 
 
                 return response[1].save();
                 return response[1].save();
@@ -81,7 +104,8 @@ module.exports = {
         name: new name of the ingredient,
         name: new name of the ingredient,
         quantity: new quantity of the unit (in grams),
         quantity: new quantity of the unit (in grams),
         category: new category of the unit,
         category: new category of the unit,
-        defaultUnit: new default unit of the ingredient
+        unit: new default unit of the ingredient,
+        unitSize: unit size for special unit, if any
     }
     }
     */
     */
     updateIngredient: function(req, res){
     updateIngredient: function(req, res){
@@ -90,45 +114,60 @@ module.exports = {
             return res.redirect("/");
             return res.redirect("/");
         }
         }
 
 
+        const ingredientCheck = Validator.ingredient(req.body);
+        if(ingredientCheck !== true){
+            return res.json(ingredientCheck);
+        }
+
+        let updatedIngredient = {};
         Ingredient.findOne({_id: req.body.id})
         Ingredient.findOne({_id: req.body.id})
             .then((ingredient)=>{
             .then((ingredient)=>{
                 ingredient.name = req.body.name,
                 ingredient.name = req.body.name,
                 ingredient.category = req.body.category
                 ingredient.category = req.body.category
-                if(ingredient.specialUnit = "bottle"){
+                if(ingredient.specialUnit === "bottle"){
                     ingredient.unitSize = req.body.unitSize;
                     ingredient.unitSize = req.body.unitSize;
                 }
                 }
 
 
                 return ingredient.save();
                 return ingredient.save();
             })
             })
             .then((ingredient)=>{
             .then((ingredient)=>{
-                return Merchant.findOne({_id: req.session.user})
+                updatedIngredient.ingredient = ingredient;
+                return Merchant.findOne({_id: req.session.user});
             })
             })
             .then((merchant)=>{
             .then((merchant)=>{
                 for(let i = 0; i < merchant.inventory.length; i++){
                 for(let i = 0; i < merchant.inventory.length; i++){
                     if(merchant.inventory[i].ingredient.toString() === req.body.id){
                     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(()=>{});
+                        merchant.inventory[i].defaultUnit = req.body.unit;
+
+                        if(merchant.inventory[i].quantity !== req.body.quantity){
+                            new InventoryAdjustment({
+                                date: new Date(),
+                                merchant: req.session.user,
+                                ingredient: req.body.id,
+                                quantity: req.body.quantity - merchant.inventory[i].quantity
+                            }).save().catch(()=>{});
+
+                            merchant.inventory[i].quantity = req.body.quantity;
+                        }
+
+                        updatedIngredient.quantity = req.body.quantity;
+                        updatedIngredient.unit = req.body.unit;
+                        
+                        break;
                     }
                     }
                 }
                 }
 
 
                 return merchant.save();
                 return merchant.save();
             })
             })
             .then((merchant)=>{
             .then((merchant)=>{
-                return res.json({});
+                return res.json(updatedIngredient);
             })
             })
             .catch((err)=>{
             .catch((err)=>{
                 return res.json("ERROR: UNABLE TO UPDATE INGREDIENT");
                 return res.json("ERROR: UNABLE TO UPDATE INGREDIENT");
             });
             });
     },
     },
 
 
-    //POST - Removes an ingredient from the merchant's inventory
+    //DELETE - Removes an ingredient from the merchant's inventory
     removeIngredient: function(req, res){
     removeIngredient: function(req, res){
         if(!req.session.user){
         if(!req.session.user){
             req.session.error = "MUST BE LOGGED IN TO DO THAT";
             req.session.error = "MUST BE LOGGED IN TO DO THAT";

+ 0 - 33
controllers/merchantData.js

@@ -204,39 +204,6 @@ module.exports = {
             });
             });
     },
     },
 
 
-    //DELETE - removes a single recipe from the merchant
-    removeRecipe: function(req, res){
-        if(!req.session.user){
-            req.session.error = "MUST BE LOGGED IN TO DO THAT";
-            return res.redirect("/");
-        }
-
-        Merchant.findOne({_id: req.session.user})
-            .then((merchant)=>{
-                if(merchant.pos === "clover"){
-                    return res.json("YOU MUST EDIT YOUR RECIPES INSIDE CLOVER");
-                }
-                
-                for(let i = 0; i < merchant.recipes.length; i++){
-                    if(merchant.recipes[i].toString() === req.params.id){
-                        merchant.recipes.splice(i, 1);
-                        break;
-                    }
-                }
-
-                merchant.save()
-                    .then((updatedMerchant)=>{
-                        return res.json({});
-                    })
-                    .catch((err)=>{
-                        return res.json("ERROR: UNABLE TO SAVE DATA");
-                    })
-            })
-            .catch((err)=>{
-                return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
-            });
-    },
-
     //PUT - Update the default unit for a single ingredient
     //PUT - Update the default unit for a single ingredient
     ingredientDefaultUnit: function(req, res){
     ingredientDefaultUnit: function(req, res){
         if(!req.session.user){
         if(!req.session.user){

+ 46 - 52
controllers/recipeData.js

@@ -2,9 +2,8 @@ const axios = require("axios");
 
 
 const Recipe = require("../models/recipe.js");
 const Recipe = require("../models/recipe.js");
 const Merchant = require("../models/merchant.js");
 const Merchant = require("../models/merchant.js");
-const RecipeChange = require("../models/recipeChange.js");
+const ArchivedRecipe = require("../models/archivedRecipe.js");
 const Validator = require("./validator.js");
 const Validator = require("./validator.js");
-const merchant = require("../models/merchant.js");
 
 
 module.exports = {
 module.exports = {
     /*
     /*
@@ -82,70 +81,65 @@ module.exports = {
             return res.json(validation);
             return res.json(validation);
         }
         }
 
 
-        let changes = [];
-
         Recipe.findOne({_id: req.body.id})
         Recipe.findOne({_id: req.body.id})
             .then((recipe)=>{
             .then((recipe)=>{
-                for(let i = 0; i < req.body.ingredients.length; i++){
-                    let isMatch = false;
-                    for(let j = 0; j < recipe.ingredients.length; j++){
-                        if(req.body.ingredients[i].ingredient === recipe.ingredients[j].ingredient.toString()){
-                            let difference = parseFloat((req.body.ingredients[i].quantity - recipe.ingredients[j].quantity).toFixed(2));
-                            if(difference !== 0){        
-                                changes.push({
-                                    ingredient: recipe.ingredients[j].ingredient,
-                                    change: difference
-                                });
-                            }
-                            isMatch = true;
+                new ArchivedRecipe({
+                    merchant: req.session.user,
+                    name: recipe.name,
+                    price: recipe.price,
+                    date: new Date(),
+                    ingredients: recipe.ingredients
+                }).save().catch(()=>{});
 
 
-                            break;
-                        }
-                    }
+                recipe.name = req.body.name;
+                recipe.price = req.body.price;
+                recipe.ingredients = req.body.ingredients;
 
 
-                    if(!isMatch){
-                        changes.push({
-                            ingredient: req.body.ingredients[i].ingredient,
-                            change: req.body.ingredients[i].quantity
-                        });
-                    }
-                }
+                return recipe.save();
+            })
+            .then((recipe)=>{
+                res.json(recipe);
+            })
+            .catch((err)=>{
+                return res.json("ERROR: UNABLE TO UPDATE RECIPE");
+            });
+    },
 
 
-                for(let i = 0; i < recipe.ingredients.length; i++){
-                    let isMatch = false;
-                    for(let j = 0; j < req.body.ingredients.length; j++){
-                        if(recipe.ingredients[i].ingredient.toString() === req.body.ingredients[i].ingredient){
-                            isMatch = true;
-                        }
-                    }
+    //DELETE - removes a single recipe from the merchant and the database
+    removeRecipe: function(req, res){
+        if(!req.session.user){
+            req.session.error = "MUST BE LOGGED IN TO DO THAT";
+            return res.redirect("/");
+        }
 
 
-                    if(!isMatch){
-                        changes.push({
-                            ingredient: recipe.ingredients[i].ingredient,
-                            change: -recipe.ingredients[i].quantity
-                        });
+        Merchant.findOne({_id: req.session.user})
+            .then((merchant)=>{
+                if(merchant.pos === "clover"){
+                    return res.json("YOU MUST EDIT YOUR RECIPES INSIDE CLOVER");
+                }
+                
+                for(let i = 0; i < merchant.recipes.length; i++){
+                    if(merchant.recipes[i].toString() === req.params.id){
+                        merchant.recipes.splice(i, 1);
+                        break;
                     }
                     }
                 }
                 }
 
 
-                recipe.name = req.body.name;
-                recipe.price = req.body.price;
-                recipe.ingredients = req.body.ingredients;
+                merchant.save()
+                    .then((updatedMerchant)=>{
+                        return res.json({});
+                    })
+                    .catch((err)=>{
+                        return res.json("ERROR: UNABLE TO SAVE DATA");
+                    })
 
 
-                return recipe.save()
+                return Recipe.deleteOne({_id: req.params.id});
             })
             })
             .then((response)=>{
             .then((response)=>{
-                res.json({});
-
-                let recipeChange = new RecipeChange({
-                    recipe: response._id,
-                    date: new Date(),
-                    changes: changes
-                });
-
-                return recipeChange.save()
+                return res.json({});
             })
             })
             .catch((err)=>{
             .catch((err)=>{
-                return res.json("ERROR: UNABLE TO UPDATE RECIPE");
+                return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
             });
             });
     },
     },
 
 

+ 31 - 14
controllers/validator.js

@@ -3,17 +3,17 @@ const Merchant = require("../models/merchant.js");
 module.exports = {
 module.exports = {
     merchant: async function(merchant){
     merchant: async function(merchant){
         if(!this.isSanitary([merchant.name])){
         if(!this.isSanitary([merchant.name])){
-            return "Name contains illegal characters";
+            return "NAME CONTAINS ILLEGAL CHARACTERS";
         }
         }
 
 
         if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(merchant.email)){
         if(!/^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/.test(merchant.email)){
-            return "Invalid email address";
+            return "INVALID EMAIL ADDRESS";
         }
         }
 
 
         let checkMerchant = await Merchant.findOne({email: merchant.email});
         let checkMerchant = await Merchant.findOne({email: merchant.email});
 
 
         if(checkMerchant){
         if(checkMerchant){
-            return "An account with that email address already exists";
+            return "AN ACCOUNT WITH THAT EMAIL ADDRESS ALREADY EXISTS";
         }
         }
 
 
         let checkPassword = this.password(merchant.password, merchant.confirmPassword);
         let checkPassword = this.password(merchant.password, merchant.confirmPassword);
@@ -26,11 +26,11 @@ module.exports = {
 
 
     password: function(password, confirmPassword){
     password: function(password, confirmPassword){
         if(password.length < 10){
         if(password.length < 10){
-            return "Password must contain at least 10 characters";
+            return "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
         }
         }
 
 
         if(password !== confirmPassword){
         if(password !== confirmPassword){
-            return "Passwords do not match";
+            return "PASSWORDS DO NOT MATCH";
         }
         }
 
 
         return true;
         return true;
@@ -38,11 +38,11 @@ module.exports = {
 
 
     quantity: function(num){
     quantity: function(num){
         if(isNaN(num) || num === ""){
         if(isNaN(num) || num === ""){
-            return "Quantity must be a number";
+            return "QUANTITY MUST BE A NUMBER";
         }
         }
 
 
         if(num < 0){
         if(num < 0){
-            return "Quantity cannot be a negative number";
+            return "QUANTITY CANNOT BE A NEGATIVE NUMBER";
         }
         }
 
 
         return true;
         return true;
@@ -50,19 +50,36 @@ module.exports = {
 
 
     price: function(price){
     price: function(price){
         if(price < 0){
         if(price < 0){
-            return "Price cannot be a negative number";
+            return "PRICE CANNOT BE A NEGATIVE NUMBER";
         }
         }
 
 
         if(isNaN(price) || price === ""){
         if(isNaN(price) || price === ""){
-            return "Price must be a number";
+            return "PRICE MUST BE A NUMBER";
         }
         }
 
 
         return true;
         return true;
     },
     },
 
 
+    /*
+    ingredient = {
+        name: required,
+        category: required,
+        unit: required,
+        quantity: required,
+        specialUnit: optional,
+        unitSize: optional
+    }
+    */
     ingredient: function(ingredient){
     ingredient: function(ingredient){
         if(!this.isSanitary([ingredient.name, ingredient.category])){
         if(!this.isSanitary([ingredient.name, ingredient.category])){
-            return "Ingredient contains illegal characters";
+            return "INGREDIENT CONTAINS ILLEGAL CHARACTERS";
+        }
+
+        if(ingredient.specialUnit === "bottle"){
+            let quantityCheck = this.quantity(ingredient.unitSize);
+            if(quantityCheck !== true){
+                return "BOTTLE SIZE MUST BE A NON-NEGATIVE NUMBER";
+            }
         }
         }
 
 
         return true;
         return true;
@@ -70,7 +87,7 @@ module.exports = {
 
 
     recipe: function(recipe){
     recipe: function(recipe){
         if(!this.isSanitary([recipe.name])){
         if(!this.isSanitary([recipe.name])){
-            return "Ingredient contains illegal characters";
+            return "INGREDIENT CONTAINS ILLEGAL CHARACTERS";
         }
         }
 
 
         let priceCheck = this.price(recipe.price);
         let priceCheck = this.price(recipe.price);
@@ -88,7 +105,7 @@ module.exports = {
         for(let i = 0; i < recipe.ingredients.length; i++){
         for(let i = 0; i < recipe.ingredients.length; i++){
             for(let j = i + 1; j < recipe.ingredients.length; j++){
             for(let j = i + 1; j < recipe.ingredients.length; j++){
                 if(recipe.ingredients[i].ingredient === recipe.ingredients[j].ingredient){
                 if(recipe.ingredients[i].ingredient === recipe.ingredients[j].ingredient){
-                    return "Recipe cannot contain duplicate ingredients";
+                    return "RECIPE CANNOT CONTAIN DUPLICATE INGREDIENTS";
                 }
                 }
             }
             }
         }
         }
@@ -98,11 +115,11 @@ module.exports = {
 
 
     order: function(order){
     order: function(order){
         if(!this.isSanitary([order.name])){
         if(!this.isSanitary([order.name])){
-            return "Order name contains illegal characters";
+            return "ORDER NAME CONTAINS ILLEGAL CHARACTERS";
         }
         }
 
 
         if(new Date(order.date) > new Date()){
         if(new Date(order.date) > new Date()){
-            return "Date cannot be in the future";
+            return "DATE CANNOT BE IN THE FUTURE";
         }
         }
 
 
         if(this.quantity(order.taxes) !== true){
         if(this.quantity(order.taxes) !== true){

+ 15 - 11
models/recipeChange.js → models/archivedRecipe.js

@@ -1,30 +1,34 @@
 const mongoose = require("mongoose");
 const mongoose = require("mongoose");
 
 
-const RecipeChangeSchema = new mongoose.Schema({
-    recipe: {
+const ArchivedRecipeSchema = new mongoose.Schema({
+    merchant: {
         type: mongoose.Schema.Types.ObjectId,
         type: mongoose.Schema.Types.ObjectId,
-        ref: "Recipe",
+        ref: "Merchant",
+        required: true
+    },
+    name: {
+        type: String,
+        required: true
+    },
+    price: {
+        type: Number,
         required: true
         required: true
     },
     },
     date: {
     date: {
         type: Date,
         type: Date,
         default: Date.now
         default: Date.now
     },
     },
-    changes: [{
+    ingredients: [{
         ingredient: {
         ingredient: {
             type: mongoose.Schema.Types.ObjectId,
             type: mongoose.Schema.Types.ObjectId,
             ref: "Ingredient",
             ref: "Ingredient",
             required: true
             required: true
         },
         },
-        change: {
+        quantity: {
             type: Number,
             type: Number,
             required: true
             required: true
         }
         }
-    }],
-    date: {
-        type: Date,
-        default: Date.now
-    }
+    }]
 });
 });
 
 
-module.exports = mongoose.model("RecipeChange", RecipeChangeSchema);
+module.exports = mongoose.model("RecipeChange", ArchivedRecipeSchema);

+ 1 - 1
routes.js

@@ -18,7 +18,6 @@ module.exports = function(app){
     app.post("/merchant/create/none", merchantData.createMerchantNone);
     app.post("/merchant/create/none", merchantData.createMerchantNone);
     app.get("/merchant/create/clover", merchantData.createMerchantClover);
     app.get("/merchant/create/clover", merchantData.createMerchantClover);
     app.get("/merchant/create/square", merchantData.createMerchantSquare);
     app.get("/merchant/create/square", merchantData.createMerchantSquare);
-    app.delete("/merchant/recipes/remove/:id", merchantData.removeRecipe);
     app.put("/merchant/ingredients/update/:id/:unit", merchantData.ingredientDefaultUnit);
     app.put("/merchant/ingredients/update/:id/:unit", merchantData.ingredientDefaultUnit);
     app.put("/merchant/ingredients/update", merchantData.updateMerchantIngredient); //also updates some data in ingredients
     app.put("/merchant/ingredients/update", merchantData.updateMerchantIngredient); //also updates some data in ingredients
     app.post("/merchant/password", merchantData.updatePassword);
     app.post("/merchant/password", merchantData.updatePassword);
@@ -32,6 +31,7 @@ module.exports = function(app){
     //Recipes
     //Recipes
     app.post("/recipe/create", recipeData.createRecipe);
     app.post("/recipe/create", recipeData.createRecipe);
     app.put("/recipe/update", recipeData.updateRecipe);
     app.put("/recipe/update", recipeData.updateRecipe);
+    app.delete("/recipe/remove/:id", recipeData.removeRecipe);
     app.get("/recipe/update/clover", recipeData.updateRecipesClover);
     app.get("/recipe/update/clover", recipeData.updateRecipesClover);
     app.get("/recipe/update/square", recipeData.updateRecipesSquare);
     app.get("/recipe/update/square", recipeData.updateRecipesSquare);
 
 

+ 2 - 1
views/dashboardPage/dashboard.ejs

@@ -482,18 +482,19 @@
                     </div>
                     </div>
                 </template>
                 </template>
             </div>
             </div>
-
         </div>
         </div>
 
 
         <div id="sidebarDiv" class="sidebarHide">
         <div id="sidebarDiv" class="sidebarHide">
             <% include ./sidebars/newIngredient %>
             <% include ./sidebars/newIngredient %>
             <% include ./sidebars/ingredientDetails %>
             <% include ./sidebars/ingredientDetails %>
+            <% include ./sidebars/editIngredient %>
             <% include ./sidebars/recipeDetails %>
             <% include ./sidebars/recipeDetails %>
             <% include ./sidebars/newRecipe %>
             <% include ./sidebars/newRecipe %>
             <% include ./sidebars/orderDetails %>
             <% include ./sidebars/orderDetails %>
             <% include ./sidebars/newOrder %>
             <% include ./sidebars/newOrder %>
             <% include ./sidebars/transactionDetails %>
             <% include ./sidebars/transactionDetails %>
             <% include ./sidebars/newTransaction %>
             <% include ./sidebars/newTransaction %>
+            <% include ./sidebars/editRecipe %>
         </div>
         </div>
 
 
         <% include ../shared/loader %>
         <% include ../shared/loader %>

+ 112 - 37
views/dashboardPage/js/Ingredient.js

@@ -1,49 +1,124 @@
 class Ingredient{
 class Ingredient{
     constructor(id, name, category, unitType, unit, parent, specialUnit = undefined, unitSize = undefined){
     constructor(id, name, category, unitType, unit, parent, specialUnit = undefined, unitSize = undefined){
-        this.id = id;
-        this.name = name;
-        this.category = category;
-        this.unitType = unitType;
-        this.unit = unit;
-        this.parent = parent;
+        if(!this.isSanitaryString(name)){
+            banner.createError("NAME CONTAINS ILLEGAL CHARCTERS");
+            return false;
+        }
+        if(!this.isSanitaryString(category)){
+            banner.createError("CATEGORY CONTAINS ILLEGAL CHARACTERS");
+            return false;
+        }
+
+        this._id = id;
+        this._name = name;
+        this._category = category;
+        this._unitType = unitType;
+        this._unit = unit;
+        this._parent = parent;
         if(specialUnit){
         if(specialUnit){
-            this.specialUnit = specialUnit;
-            this.unitSize = unitSize;
+            this._specialUnit = specialUnit;
+            this._unitSize = unitSize;
         }
         }
-        
     }
     }
 
 
-    convert(quantity){
-        if(this.unitType === "mass"){
-            switch(this.unit){
-                case "g": break;
-                case "kg": quantity /= 1000; break;
-                case "oz":  quantity /= 28.3495; break;
-                case "lb":  quantity /= 453.5924; break;
-            }
-        }else if(this.unitType === "volume"){
-            switch(this.unit){
-                case "ml": quantity *= 1000; break;
-                case "l": break;
-                case "tsp": quantity *= 202.8842; break;
-                case "tbsp": quantity *= 67.6278; break;
-                case "ozfl": quantity *= 33.8141; break;
-                case "cup": quantity *= 4.1667; break;
-                case "pt": quantity *= 2.1134; break;
-                case "qt": quantity *= 1.0567; break;
-                case "gal": quantity /= 3.7854; break;
-            }
-        }else if(this.unitType === "length"){
-            switch(this.unit){
-                case "mm": quantity *= 1000; break;
-                case "cm": quantity *= 100; break;
-                case "m": break;
-                case "in": quantity *= 39.3701; break;
-                case "ft": quantity *= 3.2808; break;
+    get id(){
+        return this._id;
+    }
+
+    get name(){
+        return this._name;
+    }
+
+    set name(name){
+        if(!this.isSanitaryString(name)){
+            return false;
+        }
+
+        this._name = name;
+    }
+
+    get category(){
+        return this._category;
+    }
+
+    set category(category){
+        if(!this.isSanitaryString(category)){
+            return false;
+        }
+
+        this._category = category;
+    }
+
+    get unitType(){
+        return this._unitType;
+    }
+
+    get unit(){
+        return this._unit;
+    }
+
+    set unit(unit){
+        this._unit = unit;
+    }
+
+    get parent(){
+        return this._parent;
+    }
+
+    get specialUnit(){
+        return this._specialUnit;
+    }
+
+    get unitSize(){
+        switch(this._unit){
+            case "g":return this._unitSize; 
+            case "kg": return this._unitSize / 1000;
+            case "oz": return this._unitSize / 28.3495;
+            case "lb": return this._unitSize / 453.5924;
+            case "ml": return this._unitSize * 1000;
+            case "l": return this._unitSize;
+            case "tsp": return this._unitSize * 202.8842;
+            case "tbsp": return this._unitSize * 67.6278;
+            case "ozfl": return this._unitSize * 33.8141;
+            case "cup": return this._unitSize * 4.1667;
+            case "pt": return this._unitSize * 2.1134;
+            case "qt": return this._unitSize * 1.0567;
+            case "gal": return this._unitSize / 3.7854;
+            case "mm": return this._unitSize * 1000;
+            case "cm": return this._unitSize * 100;
+            case "m": return this._unitSize;
+            case "in": return this._unitSize * 39.3701;
+            case "ft": return this._unitSize * 3.2808;
+            default: return this._unitSize;
+        }
+    }
+
+    set unitSize(unitSize){
+        if(unitSize < 0){
+            return false;
+        }
+
+        this._unitSize = unitSize;
+    }
+
+    getNameAndUnit(){
+        if(this._specialUnit === "bottle"){
+            return `${this._name} (BOTTLES)`;
+        }
+
+        return `${this._name} (${this._unit.toUpperCase()})`;
+    }
+
+    isSanitaryString(str){
+        let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
+
+        for(let i = 0; i < disallowed.length; i++){
+            if(str.includes(disallowed[i])){
+                return false;
             }
             }
         }
         }
 
 
-        return quantity;
+        return true;
     }
     }
 }
 }
 
 

+ 441 - 171
views/dashboardPage/js/Merchant.js

@@ -1,51 +1,152 @@
-const Ingredient = require("./Ingredient.js");
-const Recipe = require("./Recipe.js");
-const Transaction = require("./Transaction.js");
+class MerchantIngredient{
+    constructor(ingredient, quantity){
+        if(quantity < 0){
+            banner.createError("QUANTITY CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+        
+        this._quantity = quantity;
+        this._ingredient = ingredient;
+    }
+
+    get ingredient(){
+        return this._ingredient;
+    }
+
+    get quantity(){
+        if(this._ingredient.specialUnit === "bottle"){
+            return this._quantity / this._ingredient._unitSize;
+        }
+
+        switch(this._ingredient.unit){
+            case "g":return this._quantity; 
+            case "kg": return this._quantity / 1000;
+            case "oz": return this._quantity / 28.3495;
+            case "lb": return this._quantity / 453.5924;
+            case "ml": return this._quantity * 1000;
+            case "l": return this._quantity;
+            case "tsp": return this._quantity * 202.8842;
+            case "tbsp": return this._quantity * 67.6278;
+            case "ozfl": return this._quantity * 33.8141;
+            case "cup": return this._quantity * 4.1667;
+            case "pt": return this._quantity * 2.1134;
+            case "qt": return this._quantity * 1.0567;
+            case "gal": return this._quantity / 3.7854;
+            case "mm": return this._quantity * 1000;
+            case "cm": return this._quantity * 100;
+            case "m": return this._quantity;
+            case "in": return this._quantity * 39.3701;
+            case "ft": return this._quantity * 3.2808;
+            default: return this._quantity;
+        }
+    }
+
+    set quantity(quantity){
+        if(quantity < 0){
+            return false;
+        }
+
+        this._quantity = quantity;
+    }
+
+    convertToBase(quantity){
+        switch(this._ingredient.unit){
+            case "g": return quantity;
+            case "kg": return quantity * 1000; 
+            case "oz":  return quantity * 28.3495; 
+            case "lb":  return quantity * 453.5924;
+            case "ml": return quantity / 1000; 
+            case "l": return quantity;
+            case "tsp": return quantity / 202.8842; 
+            case "tbsp": return quantity / 67.6278; 
+            case "ozfl": return quantity / 33.8141; 
+            case "cup": return quantity / 4.1667; 
+            case "pt": return quantity / 2.1134; 
+            case "qt": return quantity / 1.0567; 
+            case "gal": return quantity * 3.7854;
+            case "mm": return quantity / 1000; 
+            case "cm": return quantity / 100; 
+            case "m": return quantity;
+            case "in": return quantity / 39.3701; 
+            case "ft": return quantity / 3.2808;
+            default: return quantity;
+        }
+    }
+
+    getQuantityDisplay(){
+        if(this._ingredient.specialUnit === "bottle"){
+            return `${this.quantity.toFixed(2)} BOTTLES`;
+        }
+
+        return `${this.quantity.toFixed(2)} ${this._ingredient.unit.toUpperCase()}`;
+    }
+}
 
 
 class Merchant{
 class Merchant{
-    constructor(oldMerchant, transactions){
-        this.name = oldMerchant.name;
-        this.pos = oldMerchant.pos;
-        this.ingredients = [];
-        this.recipes = [];
-        this.transactions = [];
-        this.orders = [];
-        this.units = {
+    constructor(oldMerchant, transactions, modules){
+        this._modules = modules;
+        this._name = oldMerchant.name;
+        this._pos = oldMerchant.pos;
+        this._ingredients = [];
+        this._recipes = [];
+        this._transactions = [];
+        this._orders = [];
+        this._units = {
             mass: ["g", "kg", "oz", "lb"],
             mass: ["g", "kg", "oz", "lb"],
             volume: ["ml", "l", "tsp", "tbsp", "ozfl", "cup", "pt", "qt", "gal"],
             volume: ["ml", "l", "tsp", "tbsp", "ozfl", "cup", "pt", "qt", "gal"],
             length: ["mm", "cm", "m", "in", "ft"],
             length: ["mm", "cm", "m", "in", "ft"],
             other: ["each", "bottle"]
             other: ["each", "bottle"]
         }
         }
         
         
+        //populate ingredients
         for(let i = 0; i < oldMerchant.inventory.length; i++){
         for(let i = 0; i < oldMerchant.inventory.length; i++){
-
-            this.ingredients.push({
-                ingredient: new Ingredient(
-                    oldMerchant.inventory[i].ingredient._id,
-                    oldMerchant.inventory[i].ingredient.name,
-                    oldMerchant.inventory[i].ingredient.category,
-                    oldMerchant.inventory[i].ingredient.unitType,
-                    oldMerchant.inventory[i].defaultUnit,
-                    this,
-                    oldMerchant.inventory[i].ingredient.specialUnit,
-                    oldMerchant.inventory[i].ingredient.unitSize
-                ),
-                quantity: oldMerchant.inventory[i].quantity
-            });
+            const ingredient = new modules.Ingredient(
+                oldMerchant.inventory[i].ingredient._id,
+                oldMerchant.inventory[i].ingredient.name,
+                oldMerchant.inventory[i].ingredient.category,
+                oldMerchant.inventory[i].ingredient.unitType,
+                oldMerchant.inventory[i].defaultUnit,
+                this,
+                oldMerchant.inventory[i].ingredient.specialUnit,
+                oldMerchant.inventory[i].ingredient.unitSize
+            );
+
+            const merchantIngredient = new MerchantIngredient(
+                ingredient,
+                oldMerchant.inventory[i].quantity,
+            );
+
+            this._ingredients.push(merchantIngredient);
         }
         }
 
 
+        //populate recipes
         for(let i = 0; i < oldMerchant.recipes.length; i++){
         for(let i = 0; i < oldMerchant.recipes.length; i++){
-            this.recipes.push(new Recipe(
+            let ingredients = [];
+            for(let j = 0; j < oldMerchant.recipes[i].ingredients.length; j++){
+                const ingredient = oldMerchant.recipes[i].ingredients[j];
+                for(let k = 0; k < this._ingredients.length; k++){
+                    if(ingredient.ingredient === this._ingredients[k].ingredient.id){
+                        ingredients.push({
+                            ingredient: this._ingredients[k].ingredient,
+                            quantity: ingredient.quantity
+                        });
+                        break;
+                    }
+                }
+            }
+
+            this._recipes.push(new this._modules.Recipe(
                 oldMerchant.recipes[i]._id,
                 oldMerchant.recipes[i]._id,
                 oldMerchant.recipes[i].name,
                 oldMerchant.recipes[i].name,
                 oldMerchant.recipes[i].price,
                 oldMerchant.recipes[i].price,
-                oldMerchant.recipes[i].ingredients,
+                ingredients,
                 this
                 this
             ));
             ));
         }
         }
 
 
+        //populate transactions
         for(let i = 0; i < transactions.length; i++){
         for(let i = 0; i < transactions.length; i++){
-            this.transactions.push(new Transaction(
+            this._transactions.push(new modules.Transaction(
                 transactions[i]._id,
                 transactions[i]._id,
                 transactions[i].date,
                 transactions[i].date,
                 transactions[i].recipes,
                 transactions[i].recipes,
@@ -54,162 +155,275 @@ class Merchant{
         }
         }
     }
     }
 
 
+    get modules(){
+        return this._modules;
+    }
+
+    get name(){
+        return this._name;
+    }
+
+    set name(name){
+        if(this.isSanitaryString(name)){
+            this._name = name;
+        }
+        return false;
+    }
+
+    get pos(){
+        return this._pos;
+    }
+
+    get ingredients(){
+        return this._ingredients;
+    }
+
+    addIngredient(ingredient, quantity){
+        const merchantIngredient = new MerchantIngredient(ingredient, quantity);
+        this._ingredients.push(merchantIngredient);
+
+        this._modules.home.isPopulated = false;
+        this._modules.ingredients.isPopulated = false;
+    }
+
+    removeIngredient(ingredient){
+        const index = this._ingredients.indexOf(ingredient);
+        if(index === undefined){
+            return false;
+        }
+
+        this._ingredients.splice(index, 1);
+
+        this._modules.home.isPopulated = false;
+        this._modules.ingredients.isPopulated = false;
+    }
+
+    updateIngredient(ingredient, quantity){
+        const index = this._ingredients.indexOf(ingredient);
+        if(index === undefined){
+            return false;
+        }
+
+        this._ingredients[index].quantity = quantity;
+
+        this._modules.home.isPopulated = false;
+        this._modules.ingredients.isPopulated = false;
+    }
+
+    getIngredient(id){
+        for(let i = 0; i < this._ingredients.length; i++){
+            if(this._ingredients[i].ingredient.id === id){
+                return this._ingredients[i].ingredient;
+            }
+        }
+    }
+
+    get recipes(){
+        return this._recipes;
+    }
+
+    addRecipe(recipe){
+        this._recipes.push(recipe);
+
+        this._modules.transactions.isPopulated = false;
+        this._modules.recipeBook.isPopulated = false;
+    }
+
+    removeRecipe(recipe){
+        const index = this._recipes.indexOf(recipe);
+        if(index === undefined){
+            return false;
+        }
+
+        this._recipes.splice(index, 1);
+
+        this._modules.transactions.isPopulated = false;
+        this._modules.recipeBook.isPopulated = false;
+    }
+
     /*
     /*
-    Updates all specified item in the merchant's inventory and updates the page
-    If ingredient doesn't exist, add it
-    ingredients = [{
-        ingredient: Ingredient object,
-        quantity: new quantity,
-    }]
-    remove = set true if removing
-    isOrder = set true if this is coming from an order
+    recipe = {
+        name: required,
+        price: required,
+        ingredients: [{
+            ingredient: id of ingredient,
+            quantity: quantity of ingredient
+        }]
+    }
     */
     */
-    editIngredients(ingredients, remove = false, isOrder = false){
-        for(let i = 0; i < ingredients.length; i++){
-            let isNew = true;
-            for(let j = 0; j < this.ingredients.length; j++){
-                if(this.ingredients[j].ingredient === ingredients[i].ingredient){
-                    if(remove && !isOrder){
-                        this.ingredients.splice(j, 1);
-                    }else if(!remove && isOrder){
-                        this.ingredients[j].quantity += ingredients[i].quantity;
-                    }else{
-                        this.ingredients[j].quantity = ingredients[i].quantity;
+    updateRecipe(recipe){
+        for(let i = 0; i < this._recipes.length; i++){
+            if(this._recipes[i].id === recipe._id){
+                this._recipes[i].name = recipe.name;
+                this._recipes[i].price = recipe.price;
+                
+                this._recipes[i].removeIngredients();
+                for(let j = 0; j < recipe.ingredients.length; j++){
+                    for(let k = 0; k < this._ingredients.length; k++){
+                        if(this._ingredients[k].ingredient.id === recipe.ingredients[j].ingredient){
+                            this._recipes[i].addIngredient(
+                                this._ingredients[k].ingredient,
+                                recipe.ingredients[j].quantity
+                            );
+
+                            break;
+                        }
                     }
                     }
-    
-                    isNew = false;
-                    break;
                 }
                 }
-            }
-    
-            if(isNew){
-                this.ingredients.push({
-                    ingredient: ingredients[i].ingredient,
-                    quantity: parseFloat(ingredients[i].quantity)
-                });
+
+                break;
             }
             }
         }
         }
-    
-        controller.updateData("ingredient");
-        controller.closeSidebar();
+
+        this._modules.transactions.isPopulated = false;
+        this._modules.recipeBook.isPopulated = false;
     }
     }
 
 
-    /*
-    Updates a recipe in the merchants list of recipes
-    Can create, edit or remove
-    recipe = [Recipe object]
-    remove = will remove recipe when true
-    */
-    editRecipes(recipes, remove = false){
-        let isNew = true;
+    getTransactions(from = 0, to = new Date()){
+        if(merchant._transactions.length <= 0){
+            return [];
+        }
 
 
-        for(let i = 0; i < recipes.length; i++){
-            for(let j = 0; j < this.recipes.length; j++){
-                if(recipes[i] === this.recipes[j]){
-                    if(remove){
-                        this.recipes.splice(j, 1);
-                    }else{
-                        this.recipes[j] = recipes[i];
-                    }
+        if(from === 0){
+            from = this._transactions[this._transactions.length-1].date;
+        }
 
 
-                    isNew = false;
-                    break;
-                }
+        const {start, end} = this.getTransactionIndices(from, to);
+
+        return this._transactions.slice(start, end + 1);
+    }
+
+    addTransaction(transaction){
+        this._transactions.push(transaction);
+        this._transactions.sort((a, b)=>{
+            if(a.date > b.date){
+                return -1;
             }
             }
+            return 1;
+        });
+
+        let ingredients = {};
+        for(let i = 0; i < transaction.recipes.length; i++){
+            const recipe = transaction.recipes[i];
+            for(let j = 0; j < recipe.recipe.ingredients.length; j++){
+                const ingredient = recipe.recipe.ingredients[i];
+                if(ingredients[ingredient.ingredient.id]){
+                    ingredients[ingredient.ingredient.id] += recipe.quantity * ingredient.quantity;
+                }else{
+                    ingredients[ingredient.ingredient.id] = recipe.quantity * ingredient.quantity;
+                }
+            } 
+        }
 
 
-            if(isNew){
-                this.recipes.push(recipes[i]);
+        const keys = Object.keys(ingredients);
+        for(let i = 0; i < keys.length; i++){
+            for(let j = 0; j < this._ingredients.length; j++){
+                if(keys[i] === this._ingredients[j].ingredient.id){
+                    this._ingredients.quantity -= ingredients[keys[i]];
+                }
             }
             }
         }
         }
 
 
-        controller.updateData("recipe");
-        controller.closeSidebar();
+        this._modules.home.isPopulated = false;
+        this._modules.ingredients.isPopulated = false;
+        this._modules.transactions.isPopulated = false;
+        this._modules.analytics.newData = true;
     }
     }
 
 
-    /*
-    Updates a list of orders in the merchants list of orders
-    Create/edit/remove
-    orders = [Order object]
-    remove = will remove order when true
-    */
-    editOrders(orders, remove = false){
-        for(let i = 0; i < orders.length; i++){
-            let isNew = true;
-            for(let j = 0; j < this.orders.length; j++){
-                if(orders[i] === this.orders[j]){
-                    if(remove){
-                        this.orders.splice(j, 1);
-                    }else{
-                        this.orders[j] = orders[i];
-                    }
+    removeTransaction(transaction){
+        const index = this._transactions.indexOf(transaction);
+        if(index === undefined){
+            return false;
+        }
 
 
-                    isNew = false;
-                    break;
+        this._transactions.splice(index, 1);
+
+        let ingredients = {};
+        for(let i = 0; i < transaction.recipes.length; i++){
+            const recipe = transaction.recipes[i];
+            for(let j = 0; j < recipe.recipe.ingredients.length; j++){
+                const ingredient = recipe.recipe.ingredients[i];
+                if(ingredients[ingredient.ingredient.id]){
+                    ingredients[ingredient.ingredient.id] += ingredient.quantity * recipe.quantity;
+                }else{
+                    ingredients[ingredient.ingredient.id] = ingredient.quantity * recipe.quantity;
                 }
                 }
             }
             }
+        }
 
 
-            if(isNew){
-                this.orders.push(orders[i]);
+        const keys = Object.keys(ingredients);
+        for(let i = 0; i < keys.length; i++){
+            for(let j = 0; j < this._ingredients.length; j++){
+                if(keys[i] === this._ingredients[j].ingredient.id){
+                    this._ingredients.quantity += ingredients[keys[i]];
+                }
             }
             }
         }
         }
 
 
-        controller.updateData("order");
-        controller.closeSidebar();
+        this._modules.home.isPopulated = false;
+        this._modules.ingredients.isPopulated = false;
+        this._modules.transactions.isPopulated = false;
+        this._modules.analytics.newData = true;
     }
     }
 
 
-    /*
-    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){
-                if(remove){
-                    this.transactions.splice(i, 1);
-                }
+    get orders(){
+        return this._orders;
+    }
 
 
-                isNew = false;
-                break;
+    addOrder(order, isNew = false){
+        this._orders.push(order);
+
+        if(isNew){
+            for(let i = 0; i < order.ingredients.length; i++){
+                for(let j = 0; j < this._ingredients.length; j++){
+                    if(order.ingredients[i] === this._ingredients[j].ingredient){
+                        this._ingredients[j].quantity += order.ingredients[i].quantity;
+                        break;
+                    }
+                }
             }
             }
         }
         }
 
 
-        if(isNew){
-            this.transactions.push(transaction);
-            this.transactions.sort((a, b) => a.date > b.date ? -1 : 1);
+        this._modules.ingredients.isPopulated = false;
+        this._modules.orders.isPopulated = false;
+    }
+
+    removeOrder(order){
+        const index = this._orders.indexOf(order);
+        if(index === undefined){
+            return false;
         }
         }
 
 
-        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]];
-                    }
+        this._orders.splice(index, 1);
 
 
-                    break;
+        for(let i = 0; i < order.ingredients.length; i++){
+            for(let j = 0; j < this._ingredients.length; j++){
+                if(order.ingredients[i].ingredient === this._ingredients[j].ingredient){
+                    this._ingredients[j].quantity -= order.ingredients[i].quantity;
                 }
                 }
             }
             }
         }
         }
 
 
-        controller.updateData("ingredient");
-        controller.updateData("transaction");
-        controller.closeSidebar();
+        this._modules.ingredients.isPopulated = false;
+        this._modules.orders.isPopulated = false;
     }
     }
 
 
-    revenue(indices){
-        let total = 0;
+    get units(){
+        return this._units;
+    }
 
 
-        for(let i = indices[0]; i <= indices[1]; i++){
-            for(let j = 0; j < this.transactions[i].recipes.length; j++){
+    getRevenue(from, to = new Date()){
+        if(from === 0){
+            from = this._transactions[0].date;
+        }
+        const {start, end} = this.getTransactionIndices(from, to);
+
+        let total = 0;
+        for(let i = start; i <= end; i++){
+            for(let j = 0; j < this._transactions[i].recipes.length; j++){
                 for(let k = 0; k < this.recipes.length; k++){
                 for(let k = 0; k < this.recipes.length; k++){
-                    if(this.transactions[i].recipes[j].recipe === this.recipes[k]){
-                        total += this.transactions[i].recipes[j].quantity * this.recipes[k].price;
+                    if(this._transactions[i].recipes[j].recipe === this.recipes[k]){
+                        total += this._transactions[i].recipes[j].quantity * this.recipes[k].price;
                     }
                     }
                 }
                 }
             }
             }
@@ -220,20 +434,20 @@ class Merchant{
 
 
     /*
     /*
     Gets the quantity of each ingredient sold between two dates (dateRange)
     Gets the quantity of each ingredient sold between two dates (dateRange)
-    Inputs
-    dateRange: list containing a start date and an end date
+    Inputs:
+        dateRange: list containing a start date and an end date
     Return:
     Return:
         [{
         [{
             ingredient: Ingredient object,
             ingredient: Ingredient object,
-            quantity: quantity of ingredient sold
+            quantity: quantity of ingredient sold in default unit
         }]
         }]
     */
     */
-    ingredientsSold(dateRange){
-        if(!dateRange){
-            return false;
+    getIngredientsSold(from = 0, to = new Date()){
+        if(from = 0){
+            from = this._ingredients[0].date;
         }
         }
         
         
-        let recipes = this.recipesSold(dateRange);
+        let recipes = this.getRecipesSold(from, to);
         let ingredientList = [];
         let ingredientList = [];
 
 
         for(let i = 0; i < recipes.length; i++){
         for(let i = 0; i < recipes.length; i++){
@@ -244,7 +458,6 @@ class Merchant{
                     if(ingredientList[k].ingredient === recipes[i].recipe.ingredients[j].ingredient){
                     if(ingredientList[k].ingredient === recipes[i].recipe.ingredients[j].ingredient){
                         exists = true;
                         exists = true;
                         ingredientList[k].quantity += recipes[i].quantity * recipes[i].recipe.ingredients[j].quantity;
                         ingredientList[k].quantity += recipes[i].quantity * recipes[i].recipe.ingredients[j].quantity;
-                        break;
                     }
                     }
                 }
                 }
 
 
@@ -260,14 +473,27 @@ class Merchant{
         return ingredientList;
         return ingredientList;
     }
     }
 
 
-    singleIngredientSold(dateRange, ingredient){
-        let total = 0;
+    /*
+    Gets the quantity of a single ingredient sold between two dates
+    Inputs:
+        ingredient = MerchantIngredient object to find
+        from = start Date
+        to = end Date
+    return: quantity sold in default unit
+    */
+    getSingleIngredientSold(ingredient, from = 0, to = new Date()){
+        if(from === 0){
+            from = this._transactions[0].date;
+        }
 
 
-        for(let i = dateRange[0]; i < dateRange[1]; i++){
-            for(let j = 0; j < this.transactions[i].recipes.length; j++){
-                for(let k = 0; k < this.transactions[i].recipes[j].recipe.ingredients.length; k++){
-                    if(this.transactions[i].recipes[j].recipe.ingredients[k].ingredient === ingredient.ingredient){
-                        total += this.transactions[i].recipes[j].recipe.ingredients[k].quantity;
+        const {start, end} = this.getTransactionIndices(from, to);
+
+        let total = 0;
+        for(let i = start; i < end; i++){
+            for(let j = 0; j < this._transactions[i].recipes.length; j++){
+                for(let k = 0; k < this._transactions[i].recipes[j].recipe.ingredients.length; k++){
+                    if(this._transactions[i].recipes[j].recipe.ingredients[k].ingredient === ingredient.ingredient){
+                        total += this._transactions[i].recipes[j].recipe.ingredients[k].quantity;
                         break;
                         break;
                     }
                     }
                 }
                 }
@@ -287,24 +513,29 @@ class Merchant{
             quantity: quantity of the recipe sold
             quantity: quantity of the recipe sold
         }]
         }]
     */
     */
-    recipesSold(dateRange){
-        let recipeList = [];
+    getRecipesSold(from = 0, to = new Date()){
+        if(from = 0){
+            from = this._transactions[0].date;
+        }
+
+        const {start, end} = this.getTransactionIndices(from, to);
 
 
-        for(let i = dateRange[0]; i <= dateRange[1]; i++){
-            for(let j = 0; j < this.transactions[i].recipes.length; j++){
+        let recipeList = [];
+        for(let i = start; i <= end; i++){
+            for(let j = 0; j < this._transactions[i].recipes.length; j++){
                 let exists = false;
                 let exists = false;
                 for(let k = 0; k < recipeList.length; k++){
                 for(let k = 0; k < recipeList.length; k++){
-                    if(recipeList[k].recipe === this.transactions[i].recipes[j].recipe){
+                    if(recipeList[k].recipe === this._transactions[i].recipes[j].recipe){
                         exists = true;
                         exists = true;
-                        recipeList[k].quantity += this.transactions[i].recipes[j].quantity;
+                        recipeList[k].quantity += this._transactions[i].recipes[j].quantity;
                         break;
                         break;
                     }
                     }
                 }
                 }
 
 
                 if(!exists){
                 if(!exists){
                     recipeList.push({
                     recipeList.push({
-                        recipe: this.transactions[i].recipes[j].recipe,
-                        quantity: this.transactions[i].recipes[j].quantity
+                        recipe: this._transactions[i].recipes[j].recipe,
+                        quantity: this._transactions[i].recipes[j].quantity
                     });
                     });
                 }
                 }
             }
             }
@@ -317,7 +548,7 @@ class Merchant{
     Groups all of the merchant's ingredients by their category
     Groups all of the merchant's ingredients by their category
     Return: [{
     Return: [{
         name: category name,
         name: category name,
-        ingredients: [Ingredient Object]
+        ingredients: [MerchantIngredient Object]
     }]
     }]
     */
     */
     categorizeIngredients(){
     categorizeIngredients(){
@@ -381,16 +612,55 @@ class Merchant{
     getRecipesForIngredient(ingredient){
     getRecipesForIngredient(ingredient){
         let recipes = [];
         let recipes = [];
 
 
-        for(let i = 0; i < this.recipes.length; i++){
-            for(let j = 0; j < this.recipes[i].ingredients.length; j++){
-                if(this.recipes[i].ingredients[j].ingredient === ingredient){
-                    recipes.push(this.recipes[i]);
+        for(let i = 0; i < this._recipes.length; i++){
+            for(let j = 0; j < this._recipes[i].ingredients.length; j++){
+                if(this._recipes[i].ingredients[j].ingredient === ingredient){
+                    recipes.push(this._recipes[i]);
+                    break;
                 }
                 }
             }
             }
         }
         }
 
 
         return recipes;
         return recipes;
     }
     }
+
+    getTransactionIndices(from, to){
+        let start, end;
+        to.setDate(to.getDate() + 1);
+
+        for(let i = this._transactions.length - 1; i >= 0; i--){
+            if(this._transactions[i].date >= from){
+                start = i;
+                break;
+            }
+        }
+        
+        for(let i = 0; i < this._transactions.length; i++){
+            if(this._transactions[i].date < to){
+                end = i;
+                break;
+            }
+        }
+
+        if(start === undefined){
+            return false;
+        }
+
+        //these are switched due to the order of the transactions in the merchant
+        return {start: end, end: start};
+    }
+
+    isSanitaryString(str){
+        let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
+
+        for(let i = 0; i < disallowed.length; i++){
+            if(str.includes(disallowed[i])){
+                return false;
+            }
+        }
+
+        return true;
+    }
 }
 }
 
 
 module.exports = Merchant;
 module.exports = Merchant;

+ 189 - 17
views/dashboardPage/js/Order.js

@@ -1,26 +1,198 @@
+class OrderIngredient{
+    constructor(ingredient, quantity, pricePerUnit){
+        if(quantity < 0){
+            return false;
+        }
+        this._ingredient = ingredient;
+        this._quantity = quantity;
+        this._pricePerUnit = pricePerUnit;
+    }
+
+    get ingredient(){
+        return this._ingredient;
+    }
+
+    get quantity(){
+        if(this._ingredient.specialUnit === "bottle"){
+            return this._quantity / this._ingredient.unitSize;
+        }
+
+        switch(this._ingredient.unit){
+            case "g":return this._quantity;
+            case "kg": return this._quantity / 1000;
+            case "oz": return this._quantity / 28.3495;
+            case "lb": return this._quantity / 453.5924;
+            case "ml": return this._quantity * 1000;
+            case "l": return this._quantity;
+            case "tsp": return this._quantity * 202.8842;
+            case "tbsp": return this._quantity * 67.6278;
+            case "ozfl": return this._quantity * 33.8141;
+            case "cup": return this._quantity * 4.1667;
+            case "pt": return this._quantity * 2.1134;
+            case "qt": return this._quantity * 1.0567;
+            case "gal": return this._quantity / 3.7854;
+            case "mm": return this._quantity * 1000;
+            case "cm": return this._quantity * 100;
+            case "m": return this._quantity;
+            case "in": return this._quantity * 39.3701;
+            case "ft": return this._quantity * 3.2808;
+            default: return this._quantity;
+        }
+    }
+
+    convertToBase(quantity){
+        switch(this._ingredient.unit){
+            case "g": return quantity;
+            case "kg": return quantity / 1000; 
+            case "oz":  return quantity / 28.3495; 
+            case "lb":  return quantity / 453.5924;
+            case "ml": return quantity *= 1000; 
+            case "l": return quantity;
+            case "tsp": return quantity * 202.8842; 
+            case "tbsp": return quantity * 67.6278; 
+            case "ozfl": return quantity * 33.8141; 
+            case "cup": return quantity * 4.1667; 
+            case "pt": return quantity * 2.1134; 
+            case "qt": return quantity * 1.0567; 
+            case "gal": return quantity / 3.7854;
+            case "mm": return quantity * 1000; 
+            case "cm": return quantity * 100; 
+            case "m": return quantity;
+            case "in": return quantity * 39.3701; 
+            case "ft": return quantity * 3.2808;
+            default: return quantity;
+        }
+    }
+
+    get pricePerUnit(){
+        if(this._ingredient.specialUnit === "bottle"){
+            return (this._pricePerUnit * this._ingredient.unitSize) / 100;
+        }
+
+        switch(this._ingredient.unit){
+            case "g": return this._pricePerUnit / 100;
+            case "kg": return (this._pricePerUnit * 1000) / 100; 
+            case "oz": return (this._pricePerUnit * 28.3495) / 100; 
+            case "lb": return (this._pricePerUnit * 453.5924) / 100; 
+            case "ml": return (this._pricePerUnit / 1000) / 100; 
+            case "l": return this._pricePerUnit / 100;
+            case "tsp": return (this._pricePerUnit / 202.8842) / 100; 
+            case "tbsp": return (this._pricePerUnit / 67.6278) / 100; 
+            case "ozfl": return (this._pricePerUnit / 33.8141) / 100; 
+            case "cup": return (this._pricePerUnit / 4.1667) / 100; 
+            case "pt": return (this._pricePerUnit / 2.1134) / 100; 
+            case "qt": return (this._pricePerUnit / 1.0567) / 100; 
+            case "gal": return (this._pricePerUnit * 3.7854) / 100; 
+            case "mm": return (this._pricePerUnit / 1000) / 100; 
+            case "cm": return (this._pricePerUnit / 100) / 100; 
+            case "m": return this._pricePerUnit / 100;
+            case "in": return (this._pricePerUnit / 39.3701) / 100; 
+            case "ft": return (this._pricePerUnit / 3.2808) / 100; 
+        }
+    }
+
+    cost(){
+        return (this._quantity * this._pricePerUnit) / 100;
+    }
+        
+}
+
+/*
+Order Object
+id = id of order in the database
+name = name/id of order, if any
+date = Date Object for when the order was created
+taxes = User entered taxes associated with the order
+fees = User entered fees associated with the order
+ingredients = [{
+    ingredient: Ingredient Object,
+    quantity: quantity of ingredient sold,
+    pricePerUnit: price of purchase (per base unit)
+}]
+parent = the merchant that it belongs to
+*/
 class Order{
 class Order{
     constructor(id, name, date, taxes, fees, ingredients, parent){
     constructor(id, name, date, taxes, fees, ingredients, parent){
-        this.id = id;
-        this.name = name;
-        this.date = new Date(date);
-        this.taxes = taxes;
-        this.fees = fees;
-        this.ingredients = [];
-        this.parent = parent;
+        if(!this.isSanitaryString(name)){
+            return false;
+        }
+        if(taxes < 0){
+            return false;
+        }
+
+        this._id = id;
+        this._name = name;
+        this._date = new Date(date);
+        this._taxes = taxes;
+        this._fees = fees;
+        this._ingredients = [];
+        this._parent = parent;
+
+        if(date > new Date()){
+            return false;
+        }
 
 
         for(let i = 0; i < ingredients.length; i++){
         for(let i = 0; i < ingredients.length; i++){
-            for(let j = 0; j < parent.ingredients.length; j++){
-                if(ingredients[i].ingredient === parent.ingredients[j].ingredient.id){
-                    this.ingredients.push({
-                        ingredient: parent.ingredients[j].ingredient,
-                        quantity: ingredients[i].quantity,
-                        pricePerUnit: ingredients[i].pricePerUnit
-                    });
-
-                    break;
-                }
+            this._ingredients.push(new OrderIngredient(
+                ingredients[i].ingredient,
+                ingredients[i].quantity,
+                ingredients[i].pricePerUnit
+            ));
+        }
+
+        this._parent.modules.ingredients.isPopulated = false;
+    }
+
+    get id(){
+        return this._id;
+    }
+
+    get name(){
+        return this._name;
+    }
+
+    get date(){
+        return this._date;
+    }
+
+    get taxes(){
+        return this._taxes / 100;
+    }
+
+    get fees(){
+        return this._fees / 100;
+    }
+
+    get parent(){
+        return this._parent;
+    }
+
+    get ingredients(){
+        return this._ingredients;
+    }
+
+    getIngredientCost(){
+        let sum = 0;
+        for(let i = 0; i < this._ingredients.length; i++){
+            sum += this._ingredients[i].cost();
+        }
+        return sum;
+    }
+
+    getTotalCost(){
+        return (this.getIngredientCost() + this.taxes + this.fees);
+    }
+
+    isSanitaryString(str){
+        let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
+
+        for(let i = 0; i < disallowed.length; i++){
+            if(str.includes(disallowed[i])){
+                return false;
             }
             }
         }
         }
+
+        return true;
     }
     }
 }
 }
 
 

+ 182 - 13
views/dashboardPage/js/Recipe.js

@@ -1,22 +1,191 @@
+class RecipeIngredient{
+    constructor(ingredient, quantity){
+        if(quantity < 0){
+            banner.createError("QUANTITY CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+        this._ingredient = ingredient;
+        this._quantity = quantity;
+    }
+
+    get ingredient(){
+        return this._ingredient;
+    }
+
+    get quantity(){
+        // if(this._ingredient.specialUnit === "bottle"){
+        //     return this._quantity / this._ingredient.unitSize;
+        // }
+
+        switch(this._ingredient.unit){
+            case "g":return this._quantity;
+            case "kg": return this._quantity / 1000;
+            case "oz": return this._quantity / 28.3495;
+            case "lb": return this._quantity / 453.5924;
+            case "ml": return this._quantity * 1000;
+            case "l": return this._quantity;
+            case "tsp": return this._quantity * 202.8842;
+            case "tbsp": return this._quantity * 67.6278;
+            case "ozfl": return this._quantity * 33.8141;
+            case "cup": return this._quantity * 4.1667;
+            case "pt": return this._quantity * 2.1134;
+            case "qt": return this._quantity * 1.0567;
+            case "gal": return this._quantity / 3.7854;
+            case "mm": return this._quantity * 1000;
+            case "cm": return this._quantity * 100;
+            case "m": return this._quantity;
+            case "in": return this._quantity * 39.3701;
+            case "ft": return this._quantity * 3.2808;
+            default: return this._quantity;
+        }
+    }
+
+    set quantity(quantity){
+        if(quantity < 0){
+            banner.createError("QUANTITY CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+
+        this_quantity = this.convertToBase(quantity);
+    }
+
+    getQuantityDisplay(){
+        if(this._ingredient.specialUnit === "bottle"){
+            
+            return `${this.quantity.toFixed(2)} BOTTLES`;
+        }
+
+        return `${this.quantity.toFixed(2)} ${this._ingredient.unit.toUpperCase()}`;
+    }
+
+    convertToBase(quantity){
+        switch(this._ingredient.unit){
+            case "g": return quantity;
+            case "kg": return quantity * 1000; 
+            case "oz":  return quantity * 28.3495; 
+            case "lb":  return quantity * 453.5924;
+            case "ml": return quantity / 1000; 
+            case "l": return quantity;
+            case "tsp": return quantity / 202.8842; 
+            case "tbsp": return quantity / 67.6278; 
+            case "ozfl": return quantity / 33.8141; 
+            case "cup": return quantity / 4.1667; 
+            case "pt": return quantity / 2.1134; 
+            case "qt": return quantity / 1.0567; 
+            case "gal": return quantity * 3.7854;
+            case "mm": return quantity / 1000; 
+            case "cm": return quantity / 100; 
+            case "m": return quantity;
+            case "in": return quantity / 39.3701; 
+            case "ft": return quantity / 3.2808;
+            default: return quantity;
+        }
+    }
+}
+
+/*
+Recipe Object
+id = database id of recipe
+name = name of recipe
+price = price of recipe in cents
+ingredients = [{
+    ingredient: Ingredient Object,
+    quantity: quantity of the ingredient within the recipe (stored as base unit, i.e grams)
+}]
+parent = merchant that it belongs to
+*/
 class Recipe{
 class Recipe{
     constructor(id, name, price, ingredients, parent){
     constructor(id, name, price, ingredients, parent){
-        this.id = id;
-        this.name = name;
-        this.price = price;
-        this.parent = parent;
-        this.ingredients = [];
+        if(price < 0){
+            banner.createError("PRICE CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+        if(!this.isSanitaryString(name)){
+            banner.createError("NAME CONTAINS ILLEGAL CHARACTERS");
+            return false;
+        }
+        this._id = id;
+        this._name = name;
+        this._price = price;
+        this._parent = parent;
+        this._ingredients = [];
 
 
         for(let i = 0; i < ingredients.length; i++){
         for(let i = 0; i < ingredients.length; i++){
-            for(let j = 0; j < parent.ingredients.length; j++){
-                if(ingredients[i].ingredient === parent.ingredients[j].ingredient.id){
-                    this.ingredients.push({
-                        ingredient: parent.ingredients[j].ingredient,
-                        quantity: ingredients[i].quantity
-                    });
-                    break;
-                }
+            const recipeIngredient = new RecipeIngredient(
+                ingredients[i].ingredient,
+                ingredients[i].quantity
+            );
+
+            this._ingredients.push(recipeIngredient);
+        }
+
+        this._parent.modules.recipeBook.isPopulated = false;
+        this._parent.modules.analytics.isPopulated = false;
+    }
+
+    get id(){
+        return this._id;
+    }
+
+    get name(){
+        return this._name;
+    }
+
+    set name(name){
+        if(!this.isSanitaryString(name)){
+            return false;
+        }
+
+        this._name = name;
+    }
+
+    get price(){
+        return this._price / 100;
+    }
+
+    set price(price){
+        if(price < 0){
+            return false;
+        }
+
+        this._price = price;
+    }
+
+    get parent(){
+        return this._parent;
+    }
+
+    get ingredients(){
+        return this._ingredients;
+    }
+
+    addIngredient(ingredient, quantity){
+        if(quantity < 0){
+            banner.createError("QUANTITY CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+
+        let recipeIngredient = new RecipeIngredient(ingredient, quantity);
+        this._ingredients.push(recipeIngredient);
+
+        this._parent.modules.recipeBook.isPopulated = false;
+        this._parent.modules.analytics.isPopulated = false;
+    }
+
+    removeIngredients(){
+        this._ingredients = [];
+    }
+
+    isSanitaryString(str){
+        let disallowed = ["\\", "<", ">", "$", "{", "}", "(", ")"];
+
+        for(let i = 0; i < disallowed.length; i++){
+            if(str.includes(disallowed[i])){
+                return false;
             }
             }
         }
         }
+
+        return true;
     }
     }
 }
 }
 
 

+ 55 - 8
views/dashboardPage/js/Transaction.js

@@ -1,22 +1,69 @@
+class TransactionRecipe{
+    constructor(recipe, quantity){
+        if(quantity < 0){
+            banner.createError("QUANTITY CANNOT BE A NEGATIVE NUMBER");
+            return false;
+        }
+        if(quantity % 1 !== 0){
+            banner.createError("RECIPES WITHIN A TRANSACTION MUST BE WHOLE NUMBERS");
+            return false;
+        }
+        this._recipe = recipe;
+        this._quantity = quantity;
+    }
+
+    get recipe(){
+        return this._recipe;
+    }
+
+    get quantity(){
+        return this._quantity;
+    }
+}
+
 class Transaction{
 class Transaction{
     constructor(id, date, recipes, parent){
     constructor(id, date, recipes, parent){
-        this.id = id;
-        this.parent = parent;
-        this.date = new Date(date);
-        this.recipes = [];
+        date = new Date(date);
+        if(date > new Date()){
+            banner.createError("DATE CANNOT BE SET TO THE FUTURE");
+            return false;
+        }
+        this._id = id;
+        this._parent = parent;
+        this._date = date;
+        this._recipes = [];
 
 
         for(let i = 0; i < recipes.length; i++){
         for(let i = 0; i < recipes.length; i++){
             for(let j = 0; j < parent.recipes.length; j++){
             for(let j = 0; j < parent.recipes.length; j++){
                 if(recipes[i].recipe === parent.recipes[j].id){
                 if(recipes[i].recipe === parent.recipes[j].id){
-                    this.recipes.push({
-                        recipe: parent.recipes[j],
-                        quantity: recipes[i].quantity
-                    });
+                    const transactionRecipe = new TransactionRecipe(
+                        parent.recipes[j],
+                        recipes[i].quantity
+                    )
+        
+                    this._recipes.push(transactionRecipe);
+
                     break;
                     break;
                 }
                 }
             }
             }
         }
         }
     }
     }
+
+    get id(){
+        return this._id;
+    }
+
+    get parent(){
+        return this._parent;
+    }
+
+    get date(){
+        return this._date;
+    }
+
+    get recipes(){
+        return this._recipes;
+    }
 }
 }
 
 
 module.exports = Transaction;
 module.exports = Transaction;

+ 11 - 9
views/dashboardPage/js/analytics.js

@@ -11,9 +11,7 @@ let analytics = {
         if(this.transactions.length === 0 || this.newData === true){
         if(this.transactions.length === 0 || this.newData === true){
             let startDate = new Date();
             let startDate = new Date();
             startDate.setMonth(startDate.getMonth() - 1);
             startDate.setMonth(startDate.getMonth() - 1);
-            const dateIndices = controller.transactionIndices(merchant.transactions, startDate);
-
-            this.transactions = merchant.transactions.slice(dateIndices[0], dateIndices[1] + 1);
+            this.transactions = merchant.getTransactions(startDate);
         }
         }
 
 
         let slider = document.getElementById("analSlider");
         let slider = document.getElementById("analSlider");
@@ -116,12 +114,12 @@ let analytics = {
         //Create Graph
         //Create Graph
         let quantities = [];
         let quantities = [];
         let dates = [];
         let dates = [];
-        let currentDate = this.transactions[0].date;
+        let currentDate = (this.transactions.length > 0) ? this.transactions[0].date : undefined;
         let currentQuantity = 0;
         let currentQuantity = 0;
 
 
         for(let i = 0; i < this.transactions.length; i++){
         for(let i = 0; i < this.transactions.length; i++){
             if(currentDate.getDate() !== this.transactions[i].date.getDate()){
             if(currentDate.getDate() !== this.transactions[i].date.getDate()){
-                quantities.push(this.ingredient.ingredient.convert(currentQuantity));
+                quantities.push(currentQuantity);
                 dates.push(currentDate);
                 dates.push(currentDate);
                 currentQuantity = 0;
                 currentQuantity = 0;
                 currentDate = this.transactions[i].date;
                 currentDate = this.transactions[i].date;
@@ -134,6 +132,7 @@ let analytics = {
                             const transIngredient = this.transactions[i].recipes[j].recipe.ingredients[l];
                             const transIngredient = this.transactions[i].recipes[j].recipe.ingredients[l];
 
 
                             if(transIngredient.ingredient === this.ingredient.ingredient){
                             if(transIngredient.ingredient === this.ingredient.ingredient){
+
                                 currentQuantity += transIngredient.quantity * this.transactions[i].recipes[j].quantity;
                                 currentQuantity += transIngredient.quantity * this.transactions[i].recipes[j].quantity;
 
 
                                 break;
                                 break;
@@ -144,7 +143,7 @@ let analytics = {
             }
             }
 
 
             if(i === this.transactions.length - 1){
             if(i === this.transactions.length - 1){
-                quantities.push(this.ingredient.ingredient.convert(currentQuantity));
+                quantities.push(currentQuantity);
                 dates.push(currentDate);
                 dates.push(currentDate);
             }
             }
         }
         }
@@ -173,7 +172,7 @@ let analytics = {
         //Create use cards
         //Create use cards
         let sum = 0;
         let sum = 0;
         let max = 0;
         let max = 0;
-        let min = quantities[0];
+        let min = (quantities.length > 0) ? quantities[0] : 0;
         for(let i = 0; i < quantities.length; i++){
         for(let i = 0; i < quantities.length; i++){
             sum += quantities[i];
             sum += quantities[i];
             if(quantities[i] > max){
             if(quantities[i] > max){
@@ -205,8 +204,11 @@ let analytics = {
     recipeDisplay: function(){
     recipeDisplay: function(){
         let quantities = [];
         let quantities = [];
         let dates = [];
         let dates = [];
-        let currentDate = this.transactions[0].date;
+        let currentDate;
         let quantity = 0;
         let quantity = 0;
+        if(this.transactions.length > 0){
+            currentDate = this.transactions[0].date;
+        }
 
 
         for(let i = 0; i < this.transactions.length; i++){
         for(let i = 0; i < this.transactions.length; i++){
             if(currentDate.getDate() !== this.transactions[i].date.getDate()){
             if(currentDate.getDate() !== this.transactions[i].date.getDate()){
@@ -281,7 +283,7 @@ let analytics = {
             },
             },
             body: JSON.stringify(dates)
             body: JSON.stringify(dates)
         })
         })
-            .then((response)=>response.json())
+            .then(response => response.json())
             .then((response)=>{
             .then((response)=>{
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response.data);
                     banner.createError(response.data);

+ 20 - 142
views/dashboardPage/js/dashboard.js

@@ -7,8 +7,10 @@ const transactions = require("./transactions.js");
 
 
 const ingredientDetails = require("./ingredientDetails.js");
 const ingredientDetails = require("./ingredientDetails.js");
 const newIngredient = require("./newIngredient.js");
 const newIngredient = require("./newIngredient.js");
+const editIngredient = require("./editIngredient.js");
 const newOrder = require("./newOrder.js");
 const newOrder = require("./newOrder.js");
 const newRecipe = require("./newRecipe.js");
 const newRecipe = require("./newRecipe.js");
+const editRecipe = require("./editRecipe.js");
 const newTransaction = require("./newTransaction.js");
 const newTransaction = require("./newTransaction.js");
 const orderDetails = require("./orderDetails.js");
 const orderDetails = require("./orderDetails.js");
 const recipeDetails = require("./recipeDetails.js");
 const recipeDetails = require("./recipeDetails.js");
@@ -20,7 +22,17 @@ const Recipe = require("./Recipe.js");
 const Order = require("./Order.js");
 const Order = require("./Order.js");
 const Transaction = require("./Transaction.js");
 const Transaction = require("./Transaction.js");
 
 
-merchant = new Merchant(data.merchant, data.transactions);
+merchant = new Merchant(data.merchant, data.transactions, {
+    home: home,
+    ingredients: ingredients,
+    transactions: transactions,
+    recipeBook: recipeBook,
+    analytics: analytics,
+    orders: orders,
+    Ingredient: Ingredient,
+    Recipe: Recipe,
+    Transaction: Transaction
+});
 
 
 controller = {
 controller = {
     openStrand: function(strand){
     openStrand: function(strand){
@@ -92,17 +104,20 @@ controller = {
 
 
         switch(sidebar){
         switch(sidebar){
             case "ingredientDetails":
             case "ingredientDetails":
-                ingredientDetails.display(data);
-                break;
-            case "addIngredients":
-                addIngredients.display(Merchant);
+                ingredientDetails.display(data, ingredients);
                 break;
                 break;
             case "newIngredient":
             case "newIngredient":
                 newIngredient.display(Ingredient);
                 newIngredient.display(Ingredient);
                 break;
                 break;
+            case "editIngredient":
+                editIngredient.display(data);
+                break;
             case "recipeDetails":
             case "recipeDetails":
                 recipeDetails.display(data);
                 recipeDetails.display(data);
                 break;
                 break;
+            case "editRecipe":
+                editRecipe.display(data);
+                break;
             case "addRecipe":
             case "addRecipe":
                 newRecipe.display(Recipe);
                 newRecipe.display(Recipe);
                 break;
                 break;
@@ -181,143 +196,6 @@ controller = {
         document.getElementById("mobileMenuSelector").onclick = ()=>{this.openMenu()};
         document.getElementById("mobileMenuSelector").onclick = ()=>{this.openMenu()};
     },
     },
 
 
-    convertToMain: function(unit, quantity){
-        let converted = 0;
-    
-        if(merchant.units.mass.includes(unit)){
-            switch(unit){
-                case "g": converted = quantity; break;
-                case "kg": converted = quantity * 1000; break;
-                case "oz": converted = quantity * 28.3495; break;
-                case "lb": converted = quantity * 453.5924; break;
-            }
-        }else if(merchant.units.volume.includes(unit)){
-            switch(unit){
-                case "ml": converted = quantity / 1000; break;
-                case "l": converted = quantity; break;
-                case "tsp": converted = quantity / 202.8842; break;
-                case "tbsp": converted = quantity / 67.6278; break;
-                case "ozfl": converted = quantity / 33.8141; break;
-                case "cup": converted = quantity / 4.1667; break;
-                case "pt": converted = quantity / 2.1134; break;
-                case "qt": converted = quantity / 1.0567; break;
-                case "gal": converted = quantity * 3.7854; break;
-            }
-        }else if(merchant.units.length.includes(unit)){
-            switch(unit){
-                case "mm": converted = quantity / 1000; break;
-                case "cm": converted = quantity / 100; break;
-                case "m": converted = quantity; break;
-                case "in": converted = quantity / 39.3701; break;
-                case "ft": converted = quantity / 3.2808; break;
-            }
-        }else{
-            converted = quantity;
-        }
-    
-        return converted;
-    },
-
-    /*
-    Sets certain strands to repopulate everything the next time it is opened
-    Use for when any data is changed
-    item = whatever is being updated
-    */
-    updateData: function(item){
-        switch(item){
-            case "ingredient":
-                home.isPopulated = false;
-                ingredients.populateByProperty("category");
-                home.isPopulated = false;
-                break;
-            case "recipe":
-                transactions.isPopulated = false;
-                recipeBook.populateRecipes();
-                break;
-            case "order":
-                orders.populate();
-                break;
-            case "transaction":
-                transactions.isPopulated = false;
-                transactions.display(Transaction);
-                analytics.newData = true;
-                break;
-        }
-    },
-
-    /*
-    Gets the indices of two dates from transactions
-    Inputs
-    transactions: transaction list to find indices on
-    from: starting date
-    to: ending date (default to now)
-    Output
-    Array containing starting index and ending index
-    Note: Will return false if it cannot find both necessary dates
-    */
-    transactionIndices(transactions, from, to = new Date()){
-        let indices = [];
-
-        for(let i = 0; i < transactions.length; i++){
-            if(transactions[i].date < to){
-                indices.push(i);
-                break;
-            }
-        }
-
-        for(let i = transactions.length - 1; i >= 0; i--){
-            if(transactions[i].date > from){
-                indices.push(i);
-                break;
-            }
-        }
-
-        if(indices.length < 2){
-            return false;
-        }
-
-        return indices;
-    },
-
-    /*
-    Converts the price of a unit to $/main unit
-    unitType = type of the unit (i.e. mass, volume)
-    unit = exact unit to convert from
-    price = price of the ingredient per unit in cents
-    */
-    convertPrice(unitType, unit, price){
-        if(unitType === "mass"){
-            switch(unit){
-                case "g": break;
-                case "kg": price /= 1000; break;
-                case "oz":  price /= 28.3495; break;
-                case "lb":  price /= 453.5924; break;
-            }
-        }else if(unitType === "volume"){
-            switch(unit){
-                case "ml": price *= 1000; break;
-                case "l": break;
-                case "tsp": price *= 202.8842; break;
-                case "tbsp": price *= 67.6278; break;
-                case "ozfl": price *= 33.8141; break;
-                case "cup": price *= 4.1667; break;
-                case "pt": price *= 2.1134; break;
-                case "qt": price *= 1.0567; break;
-                case "gal": price /= 3.7854; break;
-            }
-        }else if(unitType === "length"){
-            switch(unit){
-                case "mm": price *= 1000; break;
-                case "cm": price *= 100; break;
-                case "m": break;
-                case "in": price *= 39.3701; break;
-                case "ft": price *= 3.2808; break;
-            }
-        }
-
-        return price;
-    },
-
     /*
     /*
     Converts the price of unit back to the price per default unit
     Converts the price of unit back to the price per default unit
     unitType = type of the unit (i.e. mass, volume)
     unitType = type of the unit (i.e. mass, volume)

+ 134 - 0
views/dashboardPage/js/editIngredient.js

@@ -0,0 +1,134 @@
+const Ingredient = require("./Ingredient");
+
+let editIngredient = {
+    display: function(ingredient){
+        let buttonList = document.getElementById("unitButtons");
+        let quantLabel = document.getElementById("editIngQuantityLabel");
+        let specialLabel = document.getElementById("editSpecialLabel");
+
+        //Clear any existing data
+        while(buttonList.children.length > 0){
+            buttonList.removeChild(buttonList.firstChild);
+        }
+
+        //Populate basic fields
+        document.getElementById("editIngTitle").innerText = ingredient.ingredient.name;
+        document.getElementById("editIngName").value = ingredient.ingredient.name;
+        document.getElementById("editIngCategory").value = ingredient.ingredient.category;
+        quantLabel.innerText = `CURRENT STOCK (${ingredient.ingredient.unit.toUpperCase()})`;
+        document.getElementById("editIngSubmit").onclick = ()=>{this.submit(ingredient)};
+
+        //Populate the unit buttons
+        const units = merchant.units[ingredient.ingredient.unitType];
+
+        for(let i = 0; i < units.length; i++){
+            let button = document.createElement("button");
+            button.classList.add("unitButton");
+            button.innerText = units[i].toUpperCase();
+            button.onclick = ()=>{this.changeUnit(button)};
+            buttonList.appendChild(button);
+
+            if(units[i] === ingredient.ingredient.unit){
+                button.classList.add("unitActive");
+            }
+        }
+        
+        //Make any changes for special ingredients
+        if(ingredient.ingredient.specialUnit === "bottle"){
+            quantLabel.innerText = "CURRENT STOCK (BOTTLES):";
+
+            specialLabel.style.display = "flex";
+            specialLabel.innerText = `BOTTLE SIZE (${ingredient.ingredient.unit.toUpperCase()}):`;
+            
+            let sizeInput = document.createElement("input");
+            sizeInput.id = "editIngSpecialSize";
+            sizeInput.type = "number";
+            sizeInput.min = "0";
+            sizeInput.step = "0.01";
+            sizeInput.value = ingredient.ingredient.unitSize.toFixed(2);
+            specialLabel.appendChild(sizeInput);
+        }else{
+            specialLabel.style.display = "none";
+        }
+
+        let quantInput = document.createElement("input");
+        quantInput.id = "editIngQuantity";
+        quantInput.type = "number";
+        quantInput.min = "0";
+        quantInput.step = "0.01";
+        quantInput.value = ingredient.quantity.toFixed(2);
+        quantLabel.appendChild(quantInput);
+    },
+
+    changeUnit(button){
+        let buttons = document.getElementById("unitButtons");
+
+        for(let i = 0; i < buttons.children.length; i++){
+            buttons.children[i].classList.remove("unitActive");
+        }
+
+        button.classList.add("unitActive");
+    },
+
+    submit(ingredient){
+        const quantity = parseFloat(document.getElementById("editIngQuantityLabel").children[0].value);
+
+        let data = {
+            id: ingredient.ingredient.id,
+            name: document.getElementById("editIngName").value,
+            category: document.getElementById("editIngCategory").value
+        }
+
+        //Add data based on unit type
+        if(ingredient.ingredient.specialUnit === "bottle"){
+            let unitSize = ingredient.convertToBase(parseFloat(document.getElementById("editSpecialLabel").children[0].value));
+            data.quantity = quantity * unitSize;
+            data.unitSize = unitSize;
+        }else{
+            data.quantity = ingredient.convertToBase(quantity);
+        }
+
+        //Get the measurement unit
+        let units = document.getElementById("unitButtons");
+        for(let i = 0; i < units.children.length; i++){
+            if(units.children[i].classList.contains("unitActive")){
+                data.unit = units.children[i].innerText.toLowerCase();
+                break;
+            }
+        }
+
+        let loader = document.getElementById("loaderContainer");
+        loader.style.display = "flex";
+
+        fetch("/ingredients/update", {
+            method: "put",
+            headers: {
+                "Content-Type": "application/json;charset=utf-8"
+            },
+            body: JSON.stringify(data)
+        })
+        .then(response => response.json())
+        .then((response)=>{
+            if(typeof(response) === "string"){
+                banner.createError(response);
+            }else{
+                ingredient.ingredient.name = response.ingredient.name;
+                ingredient.ingredient.category = response.ingredient.category;
+                ingredient.ingredient.unitSize = response.ingredient.unitSize;
+                ingredient.ingredient.unit = response.unit;
+
+                merchant.updateIngredient(ingredient, response.quantity);
+                controller.openStrand("ingredients");
+                banner.createNotification("INGREDIENT UPDATED");
+            }
+        })
+        .catch((err)=>{
+            banner.createError("SOMETHING WENT WRONG, PLEASE REFRESH THE PAGE");
+        })
+        .finally(()=>{
+            loader.style.display = "none";
+        });
+    }
+}
+
+module.exports = editIngredient;

+ 123 - 0
views/dashboardPage/js/editRecipe.js

@@ -0,0 +1,123 @@
+let editRecipe = {
+    display: function(recipe){
+        let nameInput = document.getElementById("editRecipeName");
+        if(merchant.pos === "none"){
+            nameInput.value = recipe.name;
+        }else{
+            document.getElementById("editRecipeNoName").innertext = recipe.name;
+            nameInput.parentNode.style.display = "none";
+        }
+
+        //Populate ingredients
+        let ingredientList = document.getElementById("editRecipeIngList");
+
+        while(ingredientList.children.length > 0){
+            ingredientList.removeChild(ingredientList.firstChild);
+        }
+
+        let template = document.getElementById("editRecipeIng").content.children[0];
+        for(let i = 0; i < recipe.ingredients.length; i++){
+            let ingredientDiv = template.cloneNode(true);
+            ingredientDiv.children[0].onclick = ()=>{ingredientDiv.parentNode.removeChild(ingredientDiv)};
+            ingredientDiv.children[1].innerText = recipe.ingredients[i].ingredient.getNameAndUnit();
+            ingredientDiv.children[2].style.display = "none";
+            ingredientDiv.children[3].value = recipe.ingredients[i].quantity;
+            ingredientDiv.ingredient = recipe.ingredients[i];
+            
+            ingredientList.appendChild(ingredientDiv);
+        }
+
+        document.getElementById("addRecIng").onclick = ()=>{this.newIngredient()};
+        document.getElementById("editRecipePrice").value = recipe.price;
+        document.getElementById("editRecipeSubmit").onclick = ()=>{this.submit(recipe)};
+        document.getElementById("editRecipeCancel").onclick = ()=>{controller.openSidebar("recipeDetails", recipe)};
+    },
+
+    newIngredient: function(){
+        let ingredientList = document.getElementById("editRecipeIngList");
+
+        let ingredientDiv = document.getElementById("editRecipeIng").content.children[0].cloneNode(true);
+        ingredientDiv.children[0].onclick = ()=>{ingredientDiv.parentNode.removeChild(ingredientDiv)};
+        ingredientDiv.children[1].style.display = "none";
+        ingredientDiv.children[3].value = "0.00";
+
+        //Populate selector
+        let categories = merchant.categorizeIngredients();
+        for(let i = 0; i < categories.length; i++){
+            let group = document.createElement("optgroup");
+            group.label = categories[i].name;
+
+            for(let j = 0; j < categories[i].ingredients.length; j++){
+                let option = document.createElement("option");
+                option.innerText = categories[i].ingredients[j].ingredient.getNameAndUnit();
+                option.ingredient = categories[i].ingredients[j];
+                group.appendChild(option);
+            }
+            
+            ingredientDiv.children[2].appendChild(group);
+        }
+
+        ingredientList.appendChild(ingredientDiv);
+    },
+
+    submit: function(recipe){
+        let data = {
+            id: recipe.id,
+            name: recipe.name,
+            price: document.getElementById("editRecipePrice").value * 100,
+            ingredients: []
+        }
+
+        if(merchant.pos === "none"){
+            data.name = document.getElementById("editRecipeName").value;
+        }
+
+        let ingredients = document.getElementById("editRecipeIngList").children;
+        for(let i = 0; i < ingredients.length; i++){
+            const quantity = parseFloat(ingredients[i].children[3].value);
+
+            if(ingredients[i].children[1].style.display === "none"){
+                let selector = ingredients[i].children[2];
+                let ingredient = selector.options[selector.selectedIndex].ingredient;
+
+                data.ingredients.push({
+                    ingredient: ingredient.ingredient.id,
+                    quantity: ingredient.convertToBase(quantity)
+                });
+            }else{
+                data.ingredients.push({
+                    ingredient: ingredients[i].ingredient.ingredient.id,
+                    quantity: ingredients[i].ingredient.convertToBase(quantity)
+                });
+            }
+        }
+
+        let loader = document.getElementById("loaderContainer");
+        loader.style.display = "flex";
+
+        fetch("/recipe/update", {
+            method: "put",
+            headers: {
+                "Content-Type": "application/json;charset=utf-8"
+            },
+            body: JSON.stringify(data)
+        })
+            .then(response => response.json())
+            .then((response)=>{
+                if(typeof(response) === "string"){
+                    banner.createError(response);
+                }else{
+                    merchant.updateRecipe(response);
+                    controller.openStrand("recipeBook");
+                }
+            })
+            .catch((err)=>{
+                banner.createError("SOMETHING WENT WRONG, PLEASE REFRESH THE PAGE");
+            })
+            .finally(()=>{
+                loader.style.display = "none";
+            });
+    }
+}
+
+module.exports = editRecipe;

+ 20 - 17
views/dashboardPage/js/home.js

@@ -18,10 +18,10 @@ let home = {
         let firstOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
         let firstOfLastMonth = new Date(today.getFullYear(), today.getMonth() - 1, 1);
         let lastMonthToDay = new Date(new Date().setMonth(today.getMonth() - 1));
         let lastMonthToDay = new Date(new Date().setMonth(today.getMonth() - 1));
 
 
-        let revenueThisMonth = merchant.revenue(controller.transactionIndices(merchant.transactions, firstOfMonth));
-        let revenueLastMonthToDay = merchant.revenue(controller.transactionIndices(merchant.transactions, firstOfLastMonth, lastMonthToDay));
+        const revenueThisMonth = merchant.getRevenue(firstOfMonth);
+        const revenueLastMonthToDay = merchant.getRevenue(firstOfLastMonth, lastMonthToDay);
 
 
-        document.getElementById("revenue").innerText = `$${revenueThisMonth.toLocaleString("en")}`;
+        document.getElementById("revenue").innerText = `$${revenueThisMonth.toFixed(2)}`;
 
 
         let revenueChange = ((revenueThisMonth - revenueLastMonthToDay) / revenueLastMonthToDay) * 100;
         let revenueChange = ((revenueThisMonth - revenueLastMonthToDay) / revenueLastMonthToDay) * 100;
         
         
@@ -39,22 +39,21 @@ let home = {
         let monthAgo = new Date();
         let monthAgo = new Date();
         monthAgo.setMonth(monthAgo.getMonth() - 1);
         monthAgo.setMonth(monthAgo.getMonth() - 1);
         
         
-        let dateIndices = controller.transactionIndices(merchant.transactions, monthAgo);
-
         let revenue = [];
         let revenue = [];
         let dates = [];
         let dates = [];
         let dayRevenue = 0;
         let dayRevenue = 0;
-        let currentDate = merchant.transactions[dateIndices[0]].date;
-        for(let i = dateIndices[0]; i < dateIndices[1]; i++){
-            if(merchant.transactions[i].date.getDate() !== currentDate.getDate()){
+        const transactions = merchant.getTransactions(monthAgo);
+        let currentDate = (transactions.length > 0) ? transactions[0].date : undefined;
+        for(let i = 0; i < transactions.length; i++){
+            if(transactions[i].date.getDate() !== currentDate.getDate()){
                 revenue.push(dayRevenue / 100);
                 revenue.push(dayRevenue / 100);
                 dayRevenue = 0;
                 dayRevenue = 0;
                 dates.push(currentDate);
                 dates.push(currentDate);
-                currentDate = merchant.transactions[i].date;
+                currentDate = transactions[i].date;
             }
             }
 
 
-            for(let j = 0; j < merchant.transactions[i].recipes.length; j++){
-                const recipe = merchant.transactions[i].recipes[j];
+            for(let j = 0; j < transactions[i].recipes.length; j++){
+                const recipe = transactions[i].recipes[j];
 
 
                 dayRevenue += recipe.recipe.price * recipe.quantity;
                 dayRevenue += recipe.recipe.price * recipe.quantity;
             }
             }
@@ -117,10 +116,10 @@ let home = {
                 input.changed = true;
                 input.changed = true;
             };
             };
             if(ingredient.ingredient.specialUnit === "bottle"){
             if(ingredient.ingredient.specialUnit === "bottle"){
-                input.value = (ingredient.quantity / ingredient.ingredient.unitSize).toFixed(2);
+                input.value = ingredient.quantity.toFixed(2);
                 ingredientCheck.children[2].innerText = "BOTTLES";
                 ingredientCheck.children[2].innerText = "BOTTLES";
             }else{
             }else{
-                input.value = ingredient.ingredient.convert(ingredient.quantity).toFixed(2);
+                input.value = ingredient.quantity.toFixed(2);
                 ingredientCheck.children[2].innerText = ingredient.ingredient.unit.toUpperCase();
                 ingredientCheck.children[2].innerText = ingredient.ingredient.unit.toUpperCase();
             }
             }
 
 
@@ -142,7 +141,7 @@ let home = {
         let thisMonth = new Date();
         let thisMonth = new Date();
         thisMonth.setDate(1);
         thisMonth.setDate(1);
 
 
-        let ingredientList = merchant.ingredientsSold(controller.transactionIndices(merchant.transactions, thisMonth));
+        const ingredientList = merchant.getIngredientsSold(thisMonth);
         if(ingredientList !== false){
         if(ingredientList !== false){
             ingredientList.sort((a, b)=>{
             ingredientList.sort((a, b)=>{
                 if(a.quantity < b.quantity){
                 if(a.quantity < b.quantity){
@@ -161,7 +160,7 @@ let home = {
             let count = (ingredientList.length < 5) ? ingredientList.length - 1 : 4;
             let count = (ingredientList.length < 5) ? ingredientList.length - 1 : 4;
             for(let i = count; i >= 0; i--){
             for(let i = count; i >= 0; i--){
                 const ingredientName = ingredientList[i].ingredient.name;
                 const ingredientName = ingredientList[i].ingredient.name;
-                const ingredientQuantity = ingredientList[i].ingredient.convert(ingredientList[i].quantity);
+                const ingredientQuantity = ingredientList[i].quantity;
                 const unitName = ingredientList[i].ingredient.unit;
                 const unitName = ingredientList[i].ingredient.unit;
 
 
                 quantities.push(ingredientList[i].quantity);
                 quantities.push(ingredientList[i].quantity);
@@ -207,6 +206,8 @@ let home = {
         }
         }
     },
     },
 
 
+    //Need to change the updating of ingredients
+    //should update the ingredient directly, then send that.  Maybe...
     submitInventoryCheck: function(){
     submitInventoryCheck: function(){
         let lis = document.querySelectorAll("#inventoryCheckCard li");
         let lis = document.querySelectorAll("#inventoryCheckCard li");
 
 
@@ -255,12 +256,14 @@ let home = {
                 },
                 },
                 body: JSON.stringify(fetchData)
                 body: JSON.stringify(fetchData)
             })
             })
-                .then((response) => response.json())
+                .then(response => response.json())
                 .then((response)=>{
                 .then((response)=>{
                     if(typeof(response) === "string"){
                     if(typeof(response) === "string"){
                         banner.createError(response);
                         banner.createError(response);
                     }else{
                     }else{
-                        merchant.editIngredients(changes);
+                        for(let i = 0; i < changes.length; i++){
+                            merchant.updateIngredient(changes[i].ingredient, changes[i].quantity);
+                        }
                         banner.createNotification("INGREDIENTS UPDATED");
                         banner.createNotification("INGREDIENTS UPDATED");
                     }
                     }
                 })
                 })

+ 19 - 239
views/dashboardPage/js/ingredientDetails.js

@@ -1,60 +1,22 @@
 let ingredientDetails = {
 let ingredientDetails = {
-    ingredient: {},
     dailyUse: 0,
     dailyUse: 0,
 
 
     display: function(ingredient){
     display: function(ingredient){
-        this.ingredient = ingredient;
-
-        if(this.ingredient.ingredient.specialUnit === "bottle"){
-            try{
-                let label = document.getElementById("ingredientUnitSizeLabel");
-                label.parentElement.removeChild(label);
-
-                let border = document.getElementById("bottleBorder");
-                border.parentElement.removeChild(border);
-            }catch(err){}
-        }
-
+        document.getElementById("editIngBtn").onclick = ()=>{controller.openSidebar("editIngredient", ingredient)};
+        document.getElementById("removeIngBtn").onclick = ()=>{this.remove(ingredient)};
         document.getElementById("ingredientDetailsCategory").innerText = ingredient.ingredient.category;
         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;
         document.getElementById("ingredientDetailsName").innerText = ingredient.ingredient.name;
-        
-        let nameInput = document.getElementById("ingredientDetailsNameIn");
-        nameInput.value = "";
-        nameInput.placeholder = ingredient.ingredient.name;
-
-        //Display the stock quantity (and the edit input) based on the unit type
-        let stockInput = document.getElementById("ingredientInput");
-        let stockDisplay = document.getElementById("ingredientStock");
-        stockInput.value = "";
-        if(ingredient.ingredient.specialUnit === "bottle"){
-            let quantity = ingredient.ingredient.convert(ingredient.quantity);
-
-            stockDisplay.innerText = `${quantity.toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
-            stockDisplay.innerText = `${(ingredient.quantity / ingredient.ingredient.unitSize).toFixed(2)} BOTTLES`;
-            stockInput.placeholder = quantity.toFixed(2);
-        }else{
-            stockDisplay.innerText = `${ingredient.ingredient.convert(ingredient.quantity).toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
-            stockInput.placeholder = ingredient.ingredient.convert(ingredient.quantity).toFixed(2);
-        }
+        document.getElementById("ingredientStock").innerText = ingredient.getQuantityDisplay();
 
 
 
 
+        //Calculate and display average daily use
         let quantities = [];
         let quantities = [];
         let now = new Date();
         let now = new Date();
         for(let i = 1; i < 31; i++){
         for(let i = 1; i < 31; i++){
             let endDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i)
             let endDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i)
             let startDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i - 1);
             let startDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() - i - 1);
-            let indices = controller.transactionIndices(merchant.transactions, startDay, endDay);
 
 
-            if(indices === false){
-                quantities.push(0);
-            }else{
-                quantities.push(merchant.singleIngredientSold(indices, ingredient));
-            }
+            quantities.push(merchant.getSingleIngredientSold(ingredient, startDay, endDay));
         }
         }
 
 
         let sum = 0;
         let sum = 0;
@@ -63,8 +25,14 @@ let ingredientDetails = {
         }
         }
 
 
         let dailyUse = sum / quantities.length;
         let dailyUse = sum / quantities.length;
-        document.getElementById("dailyUse").innerText = `${ingredient.ingredient.convert(dailyUse).toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
+        const dailyUseDiv = document.getElementById("dailyUse");
+        if(ingredient.ingredient.specialUnit === "bottle"){
+            dailyUseDiv.innerText = `${dailyUse.toFixed(2)} BOTTLES`;
+        }else{
+            dailyUseDiv.innerText = `${dailyUse.toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
+        }
 
 
+        //Show recipes that this ingredient is a part of
         let ul = document.getElementById("ingredientRecipeList");
         let ul = document.getElementById("ingredientRecipeList");
         let recipes = merchant.getRecipesForIngredient(ingredient.ingredient);
         let recipes = merchant.getRecipesForIngredient(ingredient.ingredient);
         while(ul.children.length > 0){
         while(ul.children.length > 0){
@@ -79,48 +47,12 @@ let ingredientDetails = {
             }
             }
             ul.appendChild(li);
             ul.appendChild(li);
         }
         }
-
-        let ingredientButtons = document.getElementById("ingredientButtons");
-        let units = [];
-        if(this.ingredient.ingredient.unitType !== "other"){
-            units = merchant.units[this.ingredient.ingredient.unitType];
-        }
-        while(ingredientButtons.children.length > 0){
-            ingredientButtons.removeChild(ingredientButtons.firstChild);
-        }
-        for(let i = 0; i < units.length; i++){
-            let button = document.createElement("button");
-            button.classList.add("unitButton");
-            button.innerText = units[i].toUpperCase();
-            button.onclick = ()=>{this.changeUnit(button, units[i])};
-            ingredientButtons.appendChild(button);
-
-            if(units[i] === this.ingredient.ingredient.unit){
-                button.classList.add("unitActive");
-            }
-        }
-
-        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(){
+    remove: function(ingredient){
         for(let i = 0; i < merchant.recipes.length; i++){
         for(let i = 0; i < merchant.recipes.length; i++){
             for(let j = 0; j < merchant.recipes[i].ingredients.length; j++){
             for(let j = 0; j < merchant.recipes[i].ingredients.length; j++){
-                if(this.ingredient.ingredient === merchant.recipes[i].ingredients[j].ingredient){
+                if(ingredient.ingredient === merchant.recipes[i].ingredients[j].ingredient){
                     banner.createError("MUST REMOVE INGREDIENT FROM ALL RECIPES BEFORE REMOVING FROM INVENTORY");
                     banner.createError("MUST REMOVE INGREDIENT FROM ALL RECIPES BEFORE REMOVING FROM INVENTORY");
                     return;
                     return;
                 }
                 }
@@ -130,176 +62,24 @@ let ingredientDetails = {
         let loader = document.getElementById("loaderContainer");
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
         loader.style.display = "flex";
 
 
-        fetch(`/ingredients/remove/${this.ingredient.ingredient.id}`, {
-            method: "DELETE",
+        fetch(`/ingredients/remove/${ingredient.ingredient.id}`, {
+            method: "delete",
         })
         })
             .then((response) => response.json())
             .then((response) => response.json())
             .then((response)=>{
             .then((response)=>{
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
+                    merchant.removeIngredient(ingredient);
+                    
+                    controller.openStrand("ingredients");
                     banner.createNotification("INGREDIENT REMOVED");
                     banner.createNotification("INGREDIENT REMOVED");
-                    merchant.editIngredients([this.ingredient], true);
                 }
                 }
             })
             })
             .catch((err)=>{})
             .catch((err)=>{})
             .finally(()=>{
             .finally(()=>{
                 loader.style.display = "none";
                 loader.style.display = "none";
             });
             });
-    },
-
-    edit: function(){
-        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";
-        }
-
-        if(this.ingredient.ingredient.specialUnit === "bottle"){
-            const mainDiv = document.getElementById("ingredientDetails");
-            const displayUnits = document.getElementById("displayUnitLabel");
-
-            let label = document.createElement("label");
-            label.innerText = `BOTTLE SIZE (${this.ingredient.ingredient.unit.toUpperCase()})`;
-            label.id = "ingredientUnitSizeLabel";
-            mainDiv.insertBefore(label, displayUnits);
-
-            const convQuant = this.ingredient.ingredient.convert(this.ingredient.ingredient.unitSize);
-
-            let input = document.createElement("input");
-            input.type = "number";
-            input.value = convQuant.toFixed(2);
-            input.id = "ingredientUnitSizeIn";
-            input.min = "0";
-            input.step = "0.01";
-            label.appendChild(input);
-
-            let border = document.createElement("div");
-            border.classList.add("lineBorder");
-            border.id="bottleBorder";
-            mainDiv.insertBefore(border, displayUnits);
-        }
-    },
-
-    editSubmit: function(){
-        //Update the ingredient unit depending on the type of unit
-        let ingredientButtons = document.querySelectorAll(".unitButton");
-        for(let i = 0; i < ingredientButtons.length; i++){
-            if(ingredientButtons[i].classList.contains("unitActive")){
-                const unit = ingredientButtons[i].innerText.toLowerCase();
-                this.ingredient.ingredient.unit = unit;
-
-                break;
-            }
-        }
-
-        //Update the ingredient quantity depending on the type of unit
-        const quantityElem = document.getElementById("ingredientInput");
-        if(quantityElem.value !== ""){
-            if(this.ingredient.ingredient.specialUnit === "bottle"){
-                let quantInMain = controller.convertToMain(
-                    this.ingredient.ingredient.unit,
-                    quantityElem.value * this.ingredient.ingredient.unitSize
-                );
-
-                this.ingredient.quantity = quantInMain / this.ingredient.ingredient.unitSize;
-            }else{
-                this.ingredient.quantity = controller.convertToMain(
-                    this.ingredient.ingredient.unit,
-                    Number(quantityElem.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 = {
-            id: this.ingredient.ingredient.id,
-            name: this.ingredient.ingredient.name,
-            quantity: this.ingredient.quantity,
-            category: this.ingredient.ingredient.category,
-            defaultUnit: this.ingredient.ingredient.unit
-        };
-
-        if(this.ingredient.ingredient.specialUnit === "bottle"){
-            const unitSize = document.getElementById("ingredientUnitSizeIn").value;
-            this.ingredient.ingredient.unitSize = controller.convertToMain(this.ingredient.ingredient.unit, unitSize);
-            data.unitSize = this.ingredient.ingredient.unitSize;
-        }
-
-        let loader = document.getElementById("loaderContainer");
-        loader.style.display = "flex";
-
-        fetch("/ingredients/update", {
-            method: "PUT",
-            headers: {
-                "Content-Type": "application/json;charset=utf-8"
-            },
-            body: JSON.stringify(data)
-        })
-            .then((response) => response.json())
-            .then((response)=>{
-                if(typeof(response) === "string"){
-                    banner.createError(response);
-                }else{
-                    merchant.editIngredients([this.ingredient]);
-
-                    this.display(this.ingredient);
-
-                    banner.createNotification("INGREDIENT UPDATED");
-                }
-            })
-            .catch((err)=>{
-                banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
-            })
-            .finally(()=>{
-                loader.style.display = "none";
-            });
-    },
-
-    changeUnit: function(newActive, unit){
-        let ingredientButtons = document.querySelectorAll(".unitButton");
-        for(let i = 0; i < ingredientButtons.length; i++){
-            ingredientButtons[i].classList.remove("unitActive");
-        }
-
-        newActive.classList.add("unitActive");
-    },
-
-    changeUnitDefault: function(){
-        let loader = document.getElementById("loaderContainer");
-        loader.style.display = "flex";
-
-        let id = this.ingredient.ingredient.id;
-        let unit = this.ingredient.ingredient.unit;
-        fetch(`/merchant/ingredients/update/${id}/${unit}`, {
-            method: "put",
-            headers: {
-                "Content-Type": "application/json;charset=utf-8"
-            },
-        })
-            .then((response)=>{
-                if(typeof(response) === "string"){
-                    banner.createError(response);
-                }else{
-                    banner.createNotification("INGREDIENT DEFAULT UNIT UPDATED");
-                }
-            })
-            .catch((err)=>{
-                banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
-            })
-            .finally(()=>{
-                loader.style.display = "none";
-            });
     }
     }
 }
 }
 
 

+ 6 - 4
views/dashboardPage/js/ingredients.js

@@ -1,15 +1,17 @@
+const { populate } = require("./orders");
+
 let ingredients = {
 let ingredients = {
     isPopulated: false,
     isPopulated: false,
     ingredients: [],
     ingredients: [],
 
 
     display: function(){
     display: function(){
         if(!this.isPopulated){
         if(!this.isPopulated){
-            this.populateByProperty("category");
-
             document.getElementById("ingredientSearch").oninput = ()=>{this.search()};
             document.getElementById("ingredientSearch").oninput = ()=>{this.search()};
             document.getElementById("ingredientClearButton").onclick = ()=>{this.clearSorting()};
             document.getElementById("ingredientClearButton").onclick = ()=>{this.clearSorting()};
             document.getElementById("ingredientSelect").onchange = ()=>{this.sort()};
             document.getElementById("ingredientSelect").onchange = ()=>{this.sort()};
 
 
+            this.populateByProperty("category");
+
             this.isPopulated = true;
             this.isPopulated = true;
         }
         }
     },
     },
@@ -52,9 +54,9 @@ let ingredients = {
 
 
                 
                 
                 if(ingredient.ingredient.specialUnit === "bottle"){
                 if(ingredient.ingredient.specialUnit === "bottle"){
-                    ingredientDiv.children[2].innerText = `${(ingredient.quantity / ingredient.ingredient.unitSize).toFixed(2)} BOTTLES`
+                    ingredientDiv.children[2].innerText = `${ingredient.quantity.toFixed(2)} BOTTLES`
                 }else{
                 }else{
-                    ingredientDiv.children[2].innerText = `${ingredient.ingredient.convert(ingredient.quantity).toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
+                    ingredientDiv.children[2].innerText = `${ingredient.quantity.toFixed(2)} ${ingredient.ingredient.unit.toUpperCase()}`;
                 }
                 }
 
 
                 categoryDiv.children[1].appendChild(ingredientDiv);
                 categoryDiv.children[1].appendChild(ingredientDiv);

+ 25 - 23
views/dashboardPage/js/newIngredient.js

@@ -1,3 +1,5 @@
+const ingredients = require("./ingredients");
+
 let newIngredient = {
 let newIngredient = {
     display: function(Ingredient){
     display: function(Ingredient){
         const selector = document.getElementById("unitSelector");
         const selector = document.getElementById("unitSelector");
@@ -25,7 +27,7 @@ let newIngredient = {
     submit: function(Ingredient){
     submit: function(Ingredient){
         let unitSelector = document.getElementById("unitSelector");
         let unitSelector = document.getElementById("unitSelector");
         let options = document.querySelectorAll("#unitSelector option");
         let options = document.querySelectorAll("#unitSelector option");
-        const quantityValue = document.getElementById("newIngQuantity").value;
+        const quantityValue = parseFloat(document.getElementById("newIngQuantity").value);
 
 
         let unit = unitSelector.value;
         let unit = unitSelector.value;
 
 
@@ -33,22 +35,19 @@ let newIngredient = {
             ingredient: {
             ingredient: {
                 name: document.getElementById("newIngName").value,
                 name: document.getElementById("newIngName").value,
                 category: document.getElementById("newIngCategory").value,
                 category: document.getElementById("newIngCategory").value,
-                unitType: options[unitSelector.selectedIndex].getAttribute("type"),
+                unitType: options[unitSelector.selectedIndex].getAttribute("type")
             },
             },
-            quantity: controller.convertToMain(unit, quantityValue),
+            quantity: quantityValue,
             defaultUnit: unit
             defaultUnit: unit
         }
         }
 
 
         //Change the ingredient if it is a special unit type (ie "bottle")
         //Change the ingredient if it is a special unit type (ie "bottle")
         if(unit === "bottle"){
         if(unit === "bottle"){
-            const bottleUnit = document.getElementById("bottleUnits").value;
-            const bottleSize = controller.convertToMain(bottleUnit, document.getElementById("bottleSize").value);
-
             newIngredient.ingredient.unitType = "volume";
             newIngredient.ingredient.unitType = "volume";
-            newIngredient.ingredient.unitSize = bottleSize;
-            newIngredient.defaultUnit = bottleUnit;
+            newIngredient.ingredient.unitSize = document.getElementById("bottleSize").value;
+            newIngredient.defaultUnit = document.getElementById("bottleUnits").value;
             newIngredient.ingredient.specialUnit = unit;
             newIngredient.ingredient.specialUnit = unit;
-            newIngredient.quantity = quantityValue * bottleSize;
+            newIngredient.quantity = quantityValue;
         }
         }
     
     
         let loader = document.getElementById("loaderContainer");
         let loader = document.getElementById("loaderContainer");
@@ -66,19 +65,20 @@ let newIngredient = {
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
-                    merchant.editIngredients([{
-                        ingredient: new Ingredient(
-                            response.ingredient._id,
-                            response.ingredient.name,
-                            response.ingredient.category,
-                            response.ingredient.unitType,
-                            response.defaultUnit,
-                            merchant,
-                            response.ingredient.specialUnit,
-                            response.ingredient.unitSize
-                        ),
-                        quantity: response.quantity
-                    }]);
+                    const ingredient = new Ingredient(
+                        response.ingredient._id,
+                        response.ingredient.name,
+                        response.ingredient.category,
+                        response.ingredient.unitType,
+                        response.defaultUnit,
+                        merchant,
+                        response.ingredient.specialUnit,
+                        response.ingredient.unitSize
+                    )
+
+                    merchant.addIngredient(ingredient, response.quantity);
+                    ingredients.display();
+                    controller.closeSidebar();
 
 
                     banner.createNotification("INGREDIENT CREATED");
                     banner.createNotification("INGREDIENT CREATED");
                 }
                 }
@@ -89,7 +89,9 @@ let newIngredient = {
             .finally(()=>{
             .finally(()=>{
                 loader.style.display = "none";
                 loader.style.display = "none";
             });
             });
-    }
+    },
+
+
 }
 }
 
 
 module.exports = newIngredient;
 module.exports = newIngredient;

+ 57 - 16
views/dashboardPage/js/newOrder.js

@@ -17,7 +17,7 @@ let newOrder = {
             let ingredient = document.createElement("button");
             let ingredient = document.createElement("button");
             ingredient.classList = "newOrderIngredient";
             ingredient.classList = "newOrderIngredient";
             ingredient.innerText = merchant.ingredients[i].ingredient.name;
             ingredient.innerText = merchant.ingredients[i].ingredient.name;
-            ingredient.onclick = ()=>{this.addIngredient(merchant.ingredients[i].ingredient, ingredient)};
+            ingredient.onclick = ()=>{this.addIngredient(merchant.ingredients[i], ingredient)};
             ingredientList.appendChild(ingredient);
             ingredientList.appendChild(ingredient);
         }
         }
 
 
@@ -32,10 +32,10 @@ let newOrder = {
         div.children[0].children[1].onclick = ()=>{this.removeIngredient(div, element)};
         div.children[0].children[1].onclick = ()=>{this.removeIngredient(div, element)};
 
 
         //Display units depending on the whether it is a special unit
         //Display units depending on the whether it is a special unit
-        if(ingredient.specialUnit === "bottle"){
-            div.children[0].children[0].innerText = `${ingredient.name} (BOTTLES)`;
+        if(ingredient.ingredient.specialUnit === "bottle"){
+            div.children[0].children[0].innerText = `${ingredient.ingredient.name} (BOTTLES)`;
         }else{
         }else{
-            div.children[0].children[0].innerText = `${ingredient.name} (${ingredient.unit.toUpperCase()})`;
+            div.children[0].children[0].innerText = `${ingredient.ingredient.name} (${ingredient.ingredient.unit.toUpperCase()})`;
         }
         }
 
 
         document.getElementById("selectedIngredientList").appendChild(div);
         document.getElementById("selectedIngredientList").appendChild(div);
@@ -78,19 +78,17 @@ let newOrder = {
                 banner.createError("QUANTITY AND PRICE MUST BE NON-NEGATIVE NUMBERS");
                 banner.createError("QUANTITY AND PRICE MUST BE NON-NEGATIVE NUMBERS");
             }
             }
 
 
-            if(ingredients[i].ingredient.specialUnit === "bottle"){
-                const ppu = controller.convertPrice("volume", ingredients[i].ingredient.unit, (price * 100) / (ingredients[i].ingredient.convert(ingredients[i].ingredient.unitSize)));
-
+            if(ingredients[i].ingredient.ingredient.specialUnit === "bottle"){
                 data.ingredients.push({
                 data.ingredients.push({
-                    ingredient: ingredients[i].ingredient.id,
-                    quantity: quantity * ingredients[i].ingredient.unitSize,
-                    pricePerUnit: ppu,
+                    ingredient: ingredients[i].ingredient.ingredient.id,
+                    quantity: quantity * ingredients[i].ingredient.ingredient.unitSize,
+                    pricePerUnit: this.convertPrice(ingredients[i].ingredient.ingredient, price * 100)
                 });
                 });
             }else{
             }else{
                 data.ingredients.push({
                 data.ingredients.push({
-                    ingredient: ingredients[i].ingredient.id,
-                    quantity: controller.convertToMain(ingredients[i].ingredient.unit, quantity),
-                    pricePerUnit: controller.convertPrice(ingredients[i].ingredient.unitType, ingredients[i].ingredient.unit, price * 100)
+                    ingredient: ingredients[i].ingredient.ingredient.id,
+                    quantity: ingredients[i].ingredient.convertToBase(quantity),
+                    pricePerUnit: this.convertPrice(ingredients[i].ingredient.ingredient, price * 100)
                 });
                 });
             }
             }
         }
         }
@@ -110,18 +108,34 @@ let newOrder = {
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
+                    let ingredients = [];
+                    for(let i = 0; i < response.ingredients.length; i++){
+                        for(let j = 0; j < merchant.ingredients.length; j++){
+                            if(merchant.ingredients[j].ingredient.id === response.ingredients[i].ingredient){
+                                ingredients.push({
+                                    ingredient: merchant.ingredients[j].ingredient,
+                                    quantity: response.ingredients[i].quantity,
+                                    pricePerUnit: response.ingredients[j].pricePerUnit
+                                });
+
+                                break;
+                            }
+                        }
+                    }
+
                     let order = new Order(
                     let order = new Order(
                         response._id,
                         response._id,
                         response.name,
                         response.name,
                         response.date,
                         response.date,
                         response.taxes,
                         response.taxes,
                         response.fees,
                         response.fees,
-                        response.ingredients,
+                        ingredients,
                         merchant
                         merchant
                     );
                     );
 
 
-                    merchant.editOrders([order]);
-                    merchant.editIngredients(order.ingredients, false, true);
+                    merchant.addOrder(order, true);
+                    
+                    controller.openStrand("orders");
                     banner.createNotification("NEW ORDER CREATED");
                     banner.createNotification("NEW ORDER CREATED");
                 }
                 }
             })
             })
@@ -131,6 +145,33 @@ let newOrder = {
             .finally(()=>{
             .finally(()=>{
                 loader.style.display = "none";
                 loader.style.display = "none";
             });
             });
+    },
+
+    convertPrice: function(ingredient, price){
+        if(ingredient.specialUnit === "bottle"){
+            return price / ingredient.unitSize;
+        }
+
+        switch(ingredient.unit){
+            case "g": return price;
+            case "kg": return price / 1000; 
+            case "oz": return price / 28.3495; 
+            case "lb": return price / 453.5924; 
+            case "ml": return price * 1000; 
+            case "l": return price;
+            case "tsp": return price * 202.8842; 
+            case "tbsp": return price * 67.6278; 
+            case "ozfl": return price * 33.8141; 
+            case "cup": return price * 4.1667; 
+            case "pt": return price * 2.1134; 
+            case "qt": return price * 1.0567; 
+            case "gal": return price / 3.7854; 
+            case "mm": return price * 1000; 
+            case "cm": return price * 100; 
+            case "m": return price;
+            case "in": return price * 39.3701; 
+            case "ft": return price * 3.2808; 
+        }
     }
     }
 }
 }
 
 

+ 21 - 7
views/dashboardPage/js/newRecipe.js

@@ -65,7 +65,7 @@ let newRecipe = {
                 if(merchant.ingredients[j].ingredient.id === inputs[i].children[1].children[0].value){
                 if(merchant.ingredients[j].ingredient.id === inputs[i].children[1].children[0].value){
                     newRecipe.ingredients.push({
                     newRecipe.ingredients.push({
                         ingredient: inputs[i].children[1].children[0].value,
                         ingredient: inputs[i].children[1].children[0].value,
-                        quantity: controller.convertToMain(merchant.ingredients[j].ingredient.unit, inputs[i].children[2].children[0].value)
+                        quantity: merchant.ingredients[j].convertToBase(inputs[i].children[2].children[0].value)
                     });
                     });
 
 
                     break;
                     break;
@@ -88,16 +88,30 @@ let newRecipe = {
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
-                    let recipe = new Recipe(
+                    let ingredients = [];
+                    for(let i = 0; i < response.ingredients.length; i++){
+                        for(let j = 0; j < merchant.ingredients.length; j++){
+                            if(merchant.ingredients[j].ingredient.id === response.ingredients[i].ingredient){
+                                ingredients.push({
+                                    ingredient: merchant.ingredients[j].ingredient,
+                                    quantity: response.ingredients[i].quantity
+                                });
+
+                                break;
+                            }
+                        }
+                    }
+
+                    merchant.addRecipe(new Recipe(
                         response._id,
                         response._id,
                         response.name,
                         response.name,
                         response.price,
                         response.price,
-                        response.ingredients,
-                        merchant,
-                    );
-                    
-                    merchant.editRecipes([recipe]);
+                        ingredients,
+                        merchant
+                    ));
+
                     banner.createNotification("RECIPE CREATED");
                     banner.createNotification("RECIPE CREATED");
+                    controller.openStrand("recipeBook");
                 }
                 }
             })
             })
             .catch((err)=>{
             .catch((err)=>{

+ 6 - 13
views/dashboardPage/js/newTransaction.js

@@ -41,16 +41,6 @@ let newTransaction = {
                     recipe: recipe.id,
                     recipe: recipe.id,
                     quantity: quantity
                     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){
             }else if(quantity < 0){
                 banner.createError("CANNOT HAVE NEGATIVE VALUES");
                 banner.createError("CANNOT HAVE NEGATIVE VALUES");
                 return;
                 return;
@@ -73,14 +63,17 @@ let newTransaction = {
                     if(typeof(response) === "string"){
                     if(typeof(response) === "string"){
                         banner.createError(response);
                         banner.createError(response);
                     }else{
                     }else{
-                        let transaction = new Transaction(
+                        const transaction = new Transaction(
                             response._id,
                             response._id,
                             response.date,
                             response.date,
                             response.recipes,
                             response.recipes,
                             merchant
                             merchant
                         );
                         );
-                        merchant.editTransactions(transaction, data.ingredientUpdates);
-                        banner.createNotification("NEW TRANSACTION CREATED, INGREDIENTS UPDATED ACCORDINGLY");
+
+                        merchant.addTransaction(transaction);
+
+                        controller.openStrand("transactions");
+                        banner.createNotification("TRANSACTION CREATED");
                     }
                     }
                 })
                 })
                 .catch((err)=>{
                 .catch((err)=>{

+ 9 - 22
views/dashboardPage/js/orderDetails.js

@@ -4,8 +4,8 @@ let orderDetails = {
 
 
         document.getElementById("orderDetailName").innerText = order.name;
         document.getElementById("orderDetailName").innerText = order.name;
         document.getElementById("orderDetailDate").innerText = order.date.toLocaleDateString("en-US");
         document.getElementById("orderDetailDate").innerText = order.date.toLocaleDateString("en-US");
-        document.getElementById("orderDetailTax").innerText = `$${(order.taxes / 100).toFixed(2)}`;
-        document.getElementById("orderDetailFee").innerText = `$${(order.fees / 100).toFixed(2)}`;
+        document.getElementById("orderDetailTax").innerText = `$${order.taxes.toFixed(2)}`;
+        document.getElementById("orderDetailFee").innerText = `$${order.fees.toFixed(2)}`;
 
 
         let ingredientList = document.getElementById("orderIngredients");
         let ingredientList = document.getElementById("orderIngredients");
         while(ingredientList.children.length > 0){
         while(ingredientList.children.length > 0){
@@ -13,35 +13,25 @@ let orderDetails = {
         }
         }
 
 
         let template = document.getElementById("orderIngredient").content.children[0];
         let template = document.getElementById("orderIngredient").content.children[0];
-        let grandTotal = 0;
         for(let i = 0; i < order.ingredients.length; i++){
         for(let i = 0; i < order.ingredients.length; i++){
             let ingredientDiv = template.cloneNode(true);
             let ingredientDiv = template.cloneNode(true);
-            let price = order.ingredients[i].pricePerUnit * order.ingredients[i].quantity;
-            grandTotal += price;
-
             const ingredient = order.ingredients[i].ingredient;
             const ingredient = order.ingredients[i].ingredient;
             
             
             ingredientDiv.children[0].innerText = order.ingredients[i].ingredient.name;
             ingredientDiv.children[0].innerText = order.ingredients[i].ingredient.name;
-            ingredientDiv.children[2].innerText = `$${(price / 100).toFixed(2)}`;
+            ingredientDiv.children[2].innerText = `$${order.ingredients[i].cost().toFixed(2)}`;
             
             
             const ingredientDisplay = ingredientDiv.children[1];
             const ingredientDisplay = ingredientDiv.children[1];
             if(ingredient.specialUnit === "bottle"){
             if(ingredient.specialUnit === "bottle"){
-                const quantSold = order.ingredients[i].quantity / ingredient.unitSize;
-                const ppu = (order.ingredients[i].pricePerUnit * order.ingredients[i].quantity) / quantSold;
-
-                ingredientDisplay.innerText = `${quantSold.toFixed(0)} bottles x $${(ppu / 100).toFixed(2)}`;
+                ingredientDisplay.innerText = `${order.ingredients[i].quantity.toFixed(2)} bottles x $${order.ingredients.pricePerUnit.toFixed(2)}`;
             }else{
             }else{
-                const convertedQuantity = ingredient.convert(order.ingredients[i].quantity);
-                const convertedPrice = controller.reconvertPrice(order.ingredients[i].ingredient.unitType, order.ingredients[i].ingredient.unit, order.ingredients[i].pricePerUnit);
-
-                ingredientDisplay.innerText = `${convertedQuantity.toFixed(2)} ${ingredient.unit.toUpperCase()} x $${(convertedPrice / 100).toFixed(2)}`;
+                ingredientDisplay.innerText = `${order.ingredients[i].quantity.toFixed(2)} ${ingredient.unit.toUpperCase()} X $${order.ingredients[i].pricePerUnit.toFixed(2)}`;
             }
             }
 
 
             ingredientList.appendChild(ingredientDiv);
             ingredientList.appendChild(ingredientDiv);
         }
         }
 
 
-        document.getElementById("orderDetailTotal").innerText = `$${(grandTotal / 100).toFixed(2)}`;
-        document.querySelector("#orderTotalPrice p").innerText = `$${((grandTotal + order.taxes + order.fees) / 100).toFixed(2)}`;
+        document.getElementById("orderDetailTotal").innerText = `$${order.getIngredientCost().toFixed(2)}`;
+        document.querySelector("#orderTotalPrice p").innerText = `$${order.getTotalCost().toFixed(2)}`;
     },
     },
 
 
     remove: function(order){
     remove: function(order){
@@ -59,12 +49,9 @@ let orderDetails = {
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
-                    for(let i = 0; i < order.ingredients.length; i++){
-                        order.ingredients[i].quantity = -order.ingredients[i].quantity;
-                    }
+                    merchant.removeOrder(order);
 
 
-                    merchant.editOrders([order], true);
-                    merchant.editIngredients(order.ingredients, false, true);
+                    controller.openStrand("orders");
                     banner.createNotification("ORDER REMOVED");
                     banner.createNotification("ORDER REMOVED");
                 }
                 }
             })
             })

+ 27 - 14
views/dashboardPage/js/orders.js

@@ -1,4 +1,5 @@
 let orders = {
 let orders = {
+    isPopulated: false,
     isFetched: false,
     isFetched: false,
 
 
     display: async function(Order){
     display: async function(Order){
@@ -17,23 +18,37 @@ let orders = {
                     if(typeof(response) === "string"){
                     if(typeof(response) === "string"){
                         banner.createError(response);
                         banner.createError(response);
                     }else{
                     }else{
-                        let newOrders = [];
                         for(let i = 0; i < response.length; i++){
                         for(let i = 0; i < response.length; i++){
-                            newOrders.push(new Order(
+                            let ingredients = [];
+                            for(let j = 0; j < response[i].ingredients.length; j++){
+                                const orderIngredient = response[i].ingredients[j];
+                                for(let k = 0; k < merchant.ingredients.length; k++){
+                                    if(merchant.ingredients[k].ingredient.id === orderIngredient.ingredient){
+                                        ingredients.push({
+                                            ingredient: merchant.ingredients[k].ingredient,
+                                            quantity: orderIngredient.quantity,
+                                            pricePerUnit: orderIngredient.pricePerUnit
+                                        });
+                                    }
+                                }
+                            }
+
+                            merchant.addOrder(new Order(
                                 response[i]._id,
                                 response[i]._id,
                                 response[i].name,
                                 response[i].name,
                                 response[i].date,
                                 response[i].date,
                                 response[i].taxes,
                                 response[i].taxes,
                                 response[i].fees,
                                 response[i].fees,
-                                response[i].ingredients,
+                                ingredients,
                                 merchant
                                 merchant
                             ));
                             ));
                         }
                         }
-                        merchant.editOrders(newOrders);
 
 
                         document.getElementById("orderSubmitForm").onsubmit = ()=>{this.submitFilter(Order)};
                         document.getElementById("orderSubmitForm").onsubmit = ()=>{this.submitFilter(Order)};
-
                         this.isFetched = true;
                         this.isFetched = true;
+                        
+                        this.populate();
+                        this.isPopulated = true;
                     }
                     }
                 })
                 })
                 .catch((err)=>{
                 .catch((err)=>{
@@ -43,6 +58,11 @@ let orders = {
                     loader.style.display = "none";
                     loader.style.display = "none";
                 });
                 });
         }
         }
+
+        if(!this.isPopulated){
+            this.populate();
+            this.isPopulated = true;
+        }
     },
     },
 
 
     populate: function(){
     populate: function(){
@@ -78,18 +98,11 @@ let orders = {
 
 
         for(let i = 0; i < merchant.orders.length; i++){
         for(let i = 0; i < merchant.orders.length; i++){
             let row = template.cloneNode(true);
             let row = template.cloneNode(true);
-            let totalCost = 0;
-            
-            for(let j = 0; j < merchant.orders[i].ingredients.length; j++){
-                const ingredient = merchant.orders[i].ingredients[j];
-                totalCost += ingredient.pricePerUnit * ingredient.quantity;
-            }
 
 
             row.children[0].innerText = merchant.orders[i].name;
             row.children[0].innerText = merchant.orders[i].name;
             row.children[1].innerText = `${merchant.orders[i].ingredients.length} ingredients`;
             row.children[1].innerText = `${merchant.orders[i].ingredients.length} ingredients`;
             row.children[2].innerText = new Date(merchant.orders[i].date).toLocaleDateString("en-US");
             row.children[2].innerText = new Date(merchant.orders[i].date).toLocaleDateString("en-US");
-            row.children[3].innerText = `$${((totalCost / 100) + (merchant.orders[i].taxes / 100) + (merchant.orders[i].fees / 100)).toFixed(2)}`;
-            row.order = merchant.orders[i];
+            row.children[3].innerText = `$${merchant.orders[i].getTotalCost().toFixed(2)}`;
             row.onclick = ()=>{controller.openSidebar("orderDetails", merchant.orders[i])};
             row.onclick = ()=>{controller.openSidebar("orderDetails", merchant.orders[i])};
             listDiv.appendChild(row);
             listDiv.appendChild(row);
         }
         }
@@ -158,7 +171,7 @@ let orders = {
 
 
                         let cost = 0;
                         let cost = 0;
                         for(let j = 0; j < order.ingredients.length; j++){
                         for(let j = 0; j < order.ingredients.length; j++){
-                            cost += (order.ingredients[j].price / 100) * order.ingredients[j].quantity;
+                            cost += order.ingredients[j].price * order.ingredients[j].quantity;
                         }
                         }
 
 
                         orderDiv.children[0].innerText = order.name;
                         orderDiv.children[0].innerText = order.name;

+ 16 - 17
views/dashboardPage/js/recipeBook.js

@@ -12,6 +12,8 @@ let recipeBook = {
             document.getElementById("recipeSearch").oninput = ()=>{this.search()};
             document.getElementById("recipeSearch").oninput = ()=>{this.search()};
             document.getElementById("recipeClearButton").onclick = ()=>{this.clearSorting()};
             document.getElementById("recipeClearButton").onclick = ()=>{this.clearSorting()};
 
 
+            this.populateRecipes();
+
             this.isPopulated = true;
             this.isPopulated = true;
         }
         }
     },
     },
@@ -32,7 +34,7 @@ let recipeBook = {
             recipeList.appendChild(recipeDiv);
             recipeList.appendChild(recipeDiv);
 
 
             recipeDiv.children[0].innerText = merchant.recipes[i].name;
             recipeDiv.children[0].innerText = merchant.recipes[i].name;
-            recipeDiv.children[1].innerText = `$${(merchant.recipes[i].price / 100).toFixed(2)}`;
+            recipeDiv.children[1].innerText = `$${merchant.recipes[i].price.toFixed(2)}`;
 
 
             this.recipeDivList.push(recipeDiv);
             this.recipeDivList.push(recipeDiv);
         }
         }
@@ -82,31 +84,28 @@ let recipeBook = {
         })
         })
             .then(response => response.json())
             .then(response => response.json())
             .then((response)=>{
             .then((response)=>{
-                let newRecipes = [];
                 for(let i = 0; i < response.new.length; i++){
                 for(let i = 0; i < response.new.length; i++){
-                    newRecipes.push(new Recipe(
+                    const recipe = new Recipe(
                         response.new[i]._id,
                         response.new[i]._id,
                         response.new[i].name,
                         response.new[i].name,
                         response.new[i].price,
                         response.new[i].price,
                         merchant,
                         merchant,
                         []
                         []
-                    ));
-                }
-                if(newRecipes.length > 0){
-                    merchant.editRecipes(newRecipes);
+                    );
+
+                    merchant.addRecipe(recipe);
                 }
                 }
 
 
-                let removeRecipes = [];
                 for(let i = 0; i < response.removed.length; i++){
                 for(let i = 0; i < response.removed.length; i++){
-                    for(let j = 0; j < merchant.recipes.length; j++){
-                        if(response.removed[i]._id === merchant.recipes[j].id){
-                            removeRecipes.push(merchant.recipes[j], true);
-                            break;
-                        }
-                    }
-                }
-                if(removeRecipes.length > 0){
-                    merchant.editRecipes(removeRecipes, true);
+                    const recipe = new Recipe(
+                        response.removed[i]._id,
+                        response.removed[i].name,
+                        response.removed[i].price,
+                        merchant,
+                        []
+                    );
+
+                    merchant.removeRecipe(recipe);
                 }
                 }
             })
             })
             .catch((err)=>{
             .catch((err)=>{

+ 20 - 124
views/dashboardPage/js/recipeDetails.js

@@ -1,129 +1,43 @@
 let recipeDetails = {
 let recipeDetails = {
-    recipe: {},
-
     display: function(recipe){
     display: function(recipe){
-        this.recipe = recipe;
+        document.getElementById("editRecipeBtn").onclick = ()=>{controller.openSidebar("editRecipe", recipe)};
+        document.getElementById("removeRecipeBtn").onclick = ()=>{this.remove(recipe)};
+        document.getElementById("recipeName").innerText = recipe.name;
 
 
-        document.getElementById("recipeName").style.display = "block";
-        document.getElementById("recipeNameIn").style.display = "none";
-        document.querySelector("#recipeDetails h1").innerText = recipe.name;
+        //ingredient list
+        let ingredientsDiv = document.getElementById("recipeIngredientList");
 
 
-        let ingredientList = document.getElementById("recipeIngredientList");
-        while(ingredientList.children.length > 0){
-            ingredientList.removeChild(ingredientList.firstChild);
+        while(ingredientsDiv.children.length > 0){
+            ingredientsDiv.removeChild(ingredientsDiv.firstChild);
         }
         }
 
 
         let template = document.getElementById("recipeIngredient").content.children[0];
         let template = document.getElementById("recipeIngredient").content.children[0];
         for(let i = 0; i < recipe.ingredients.length; i++){
         for(let i = 0; i < recipe.ingredients.length; i++){
-            ingredientDiv = template.cloneNode(true);
-
-            ingredientDiv.children[0].innerText = recipe.ingredients[i].ingredient.name;
-            ingredientDiv.children[2].innerText = `${recipe.ingredients[i].ingredient.convert(recipe.ingredients[i].quantity).toFixed(2)} ${recipe.ingredients[i].ingredient.unit}`;
-            ingredientDiv.ingredient = recipe.ingredients[i].ingredient;
-            ingredientDiv.name = recipe.ingredients[i].ingredient.name;
-
-            ingredientList.appendChild(ingredientDiv);
+            let recipeDiv = template.cloneNode(true);
+            recipeDiv.children[0].innerText = recipe.ingredients[i].ingredient.name;
+            recipeDiv.children[1].innerText = `${recipe.ingredients[i].getQuantityDisplay()}`;
+            ingredientsDiv.appendChild(recipeDiv);
         }
         }
 
 
-        document.getElementById("addRecIng").style.display = "none";
-
-        let price = document.getElementById("recipePrice");
-        price.children[1].style.display = "block";
-        price.children[2].style.display = "none";
-        price.children[1].innerText = `$${(recipe.price / 100).toFixed(2)}`;
-
-        document.getElementById("recipeUpdate").style.display = "none";
-
-        document.getElementById("editRecipeBtn").onclick = ()=>{this.edit()};
-        if(merchant.pos === "none"){
-            document.getElementById("removeRecipeBtn").onclick = ()=>{this.remove()};
-        }
-        document.getElementById("addRecIng").onclick = ()=>{this.displayAddIngredient()};
-        document.getElementById("recipeUpdate").onclick = ()=>{this.update()};
+        document.getElementById("recipePrice").children[1].innerText = `$${recipe.price.toFixed(2)}`;
     },
     },
 
 
-    edit: function(){
-        let ingredientDivs = document.getElementById("recipeIngredientList");
-
-        if(merchant.pos === "none"){
-            let name = document.getElementById("recipeName");
-            let nameIn = document.getElementById("recipeNameIn");
-            name.style.display = "none";
-            nameIn.style.display = "block";
-            nameIn.value = this.recipe.name;
-
-            let price = document.getElementById("recipePrice");
-            price.children[1].style.display = "none";
-            price.children[2].style.display = "block";
-            price.children[2].value = parseFloat((this.recipe.price / 100).toFixed(2));
-        }
-
-        for(let i = 0; i < ingredientDivs.children.length; i++){
-            let div = ingredientDivs.children[i];
-
-            div.children[2].innerText = this.recipe.ingredients[i].ingredient.unit;
-            div.children[1].style.display = "block";
-            div.children[1].value = this.recipe.ingredients[i].ingredient.convert(this.recipe.ingredients[i].quantity).toFixed(2);
-            div.children[3].style.display = "block";
-            div.children[3].onclick = ()=>{div.parentElement.removeChild(div)};
-        }
-
-        document.getElementById("addRecIng").style.display = "flex";
-        document.getElementById("recipeUpdate").style.display = "flex";
-    },
-
-    update: function(){
-        this.recipe.name = document.getElementById("recipeNameIn").value || this.recipe.name;
-        this.recipe.price = Math.round((document.getElementById("recipePrice").children[2].value * 100)) || this.recipe.price;
-        this.recipe.ingredients = [];
-
-        let divs = document.getElementById("recipeIngredientList").children;
-        for(let i = 0; i < divs.length; i++){
-            if(divs[i].name === "new"){
-                let select = divs[i].children[0];
-                this.recipe.ingredients.push({
-                    ingredient: select.options[select.selectedIndex].ingredient,
-                    quantity: controller.convertToMain(select.options[select.selectedIndex].ingredient.unit, divs[i].children[1].value)
-                });
-            }else{
-                this.recipe.ingredients.push({
-                    ingredient: divs[i].ingredient,
-                    quantity: controller.convertToMain(divs[i].ingredient.unit, divs[i].children[1].value)
-                });
-            }
-        }
-
-        let data = {
-            id: this.recipe.id,
-            name: this.recipe.name,
-            price: this.recipe.price,
-            ingredients: []
-        }
-
-        for(let i = 0; i < this.recipe.ingredients.length; i++){
-            data.ingredients.push({
-                ingredient: this.recipe.ingredients[i].ingredient.id,
-                quantity: this.recipe.ingredients[i].quantity
-            });
-        }
-
+    remove: function(recipe){
         let loader = document.getElementById("loaderContainer");
         let loader = document.getElementById("loaderContainer");
         loader.style.display = "flex";
         loader.style.display = "flex";
 
 
-        fetch("/recipe/update", {
-            method: "PUT",
-            headers: {
-                "Content-Type": "application/json;charset=utf-8"
-            },
-            body: JSON.stringify(data)
+        fetch(`/recipe/remove/${recipe.id}`, {
+            method: "delete"
         })
         })
             .then((response) => response.json())
             .then((response) => response.json())
             .then((response)=>{
             .then((response)=>{
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
-                    window.merchant.editRecipes([this.recipe]);
-                    banner.createNotification("RECIPE UPDATE");
+                    merchant.removeRecipe(recipe);
+
+                    banner.createNotification("RECIPE REMOVED");
+                    controller.openStrand("recipeBook");
                 }
                 }
             })
             })
             .catch((err)=>{
             .catch((err)=>{
@@ -134,30 +48,12 @@ let recipeDetails = {
             });
             });
     },
     },
 
 
-    remove: function(){
-        fetch(`/merchant/recipes/remove/${this.recipe.id}`, {
-            method: "DELETE"
-        })
-            .then((response) => response.json())
-            .then((response)=>{
-                if(typeof(response) === "string"){
-                    banner.createError(response);
-                }else{
-                    merchant.editRecipes([this.recipe], true);
-                    banner.createNotification("RECIPE REMOVED");
-                }
-            })
-            .catch((err)=>{
-                banner.createError("SOMETHING WENT WRONG. PLEASE REFRESH THE PAGE");
-            });
-    },
-
     displayAddIngredient: function(){
     displayAddIngredient: function(){
         let template = document.getElementById("addRecIngredient").content.children[0].cloneNode(true);
         let template = document.getElementById("addRecIngredient").content.children[0].cloneNode(true);
         template.name = "new";
         template.name = "new";
         document.getElementById("recipeIngredientList").appendChild(template);
         document.getElementById("recipeIngredientList").appendChild(template);
 
 
-        let categories = window.merchant.categorizeIngredients();
+        let categories = merchant.categorizeIngredients();
 
 
         for(let i = 0; i < categories.length; i++){
         for(let i = 0; i < categories.length; i++){
             let optGroup = document.createElement("optgroup");
             let optGroup = document.createElement("optgroup");

+ 5 - 13
views/dashboardPage/js/transactionDetails.js

@@ -18,8 +18,8 @@ let transactionDetails = {
             let price = transaction.recipes[i].quantity * transaction.recipes[i].recipe.price;
             let price = transaction.recipes[i].quantity * transaction.recipes[i].recipe.price;
 
 
             recipe.children[0].innerText = transaction.recipes[i].recipe.name;
             recipe.children[0].innerText = transaction.recipes[i].recipe.name;
-            recipe.children[1].innerText = `${transaction.recipes[i].quantity} x $${parseFloat(transaction.recipes[i].recipe.price / 100).toFixed(2)}`;
-            recipe.children[2].innerText = `$${(price / 100).toFixed(2)}`;
+            recipe.children[1].innerText = `${transaction.recipes[i].quantity} x $${transaction.recipes[i].recipe.price.toFixed(2)}`;
+            recipe.children[2].innerText = `$${price.toFixed(2)}`;
             recipeList.appendChild(recipe);
             recipeList.appendChild(recipe);
 
 
             totalRecipes += transaction.recipes[i].quantity;
             totalRecipes += transaction.recipes[i].quantity;
@@ -33,7 +33,7 @@ let transactionDetails = {
         document.getElementById("transactionDate").innerText = dateString;
         document.getElementById("transactionDate").innerText = dateString;
         document.getElementById("transactionTime").innerText = transaction.date.toLocaleTimeString();
         document.getElementById("transactionTime").innerText = transaction.date.toLocaleTimeString();
         document.getElementById("totalRecipes").innerText = `${totalRecipes} recipes`;
         document.getElementById("totalRecipes").innerText = `${totalRecipes} recipes`;
-        document.getElementById("totalPrice").innerText = `$${(totalPrice / 100).toFixed(2)}`;
+        document.getElementById("totalPrice").innerText = `$${totalPrice.toFixed(2)}`;
 
 
         if(merchant.pos === "none"){
         if(merchant.pos === "none"){
             document.getElementById("removeTransBtn").onclick = ()=>{this.remove()};
             document.getElementById("removeTransBtn").onclick = ()=>{this.remove()};
@@ -55,17 +55,9 @@ let transactionDetails = {
                 if(typeof(response) === "string"){
                 if(typeof(response) === "string"){
                     banner.createError(response);
                     banner.createError(response);
                 }else{
                 }else{
-                    let ingredients = {};
-                    for(let i = 0; i < this.transaction.recipes.length; i++){
-                        let recipe = this.transaction.recipes[i];
-                        for(let j = 0; j < recipe.recipe.ingredients.length; j++){
-                            ingredient = recipe.recipe.ingredients[j];
+                    merchant.removeTransaction(this.transaction);
 
 
-                            ingredients[ingredient.ingredient.id] = ingredient.quantity * recipe.quantity;
-                        }
-                    }
-
-                    merchant.editTransactions(this.transaction, ingredients, true);
+                    controller.openStrand("transactions");
                     banner.createNotification("TRANSACTION REMOVED");
                     banner.createNotification("TRANSACTION REMOVED");
                 }
                 }
             })
             })

+ 8 - 7
views/dashboardPage/js/transactions.js

@@ -43,9 +43,10 @@ let transactions = {
             }
             }
 
 
             let i = 0
             let i = 0
-            while(i < merchant.transactions.length && i < 100){
+            const transactions = merchant.getTransactions();
+            while(i < transactions.length && i < 100){
                 let transactionDiv = template.cloneNode(true);
                 let transactionDiv = template.cloneNode(true);
-                let transaction = merchant.transactions[i];
+                let transaction = transactions[i];
 
 
                 transactionDiv.onclick = ()=>{controller.openSidebar("transactionDetails", transaction)};
                 transactionDiv.onclick = ()=>{controller.openSidebar("transactionDetails", transaction)};
                 transactionsList.appendChild(transactionDiv);
                 transactionsList.appendChild(transactionDiv);
@@ -53,14 +54,14 @@ let transactions = {
                 let totalRecipes = 0;
                 let totalRecipes = 0;
                 let totalPrice = 0;
                 let totalPrice = 0;
 
 
-                for(let j = 0; j < merchant.transactions[i].recipes.length; j++){
-                    totalRecipes += merchant.transactions[i].recipes[j].quantity;
-                    totalPrice += merchant.transactions[i].recipes[j].recipe.price * merchant.transactions[i].recipes[j].quantity;
+                for(let j = 0; j < transactions[i].recipes.length; j++){
+                    totalRecipes += transactions[i].recipes[j].quantity;
+                    totalPrice += transactions[i].recipes[j].recipe.price * transactions[i].recipes[j].quantity;
                 }
                 }
 
 
-                transactionDiv.children[0].innerText = `${merchant.transactions[i].date.toLocaleDateString()} ${merchant.transactions[i].date.toLocaleTimeString()}`;
+                transactionDiv.children[0].innerText = `${transactions[i].date.toLocaleDateString()} ${transactions[i].date.toLocaleTimeString()}`;
                 transactionDiv.children[1].innerText = `${totalRecipes} recipes sold`;
                 transactionDiv.children[1].innerText = `${totalRecipes} recipes sold`;
-                transactionDiv.children[2].innerText = `$${(totalPrice / 100).toFixed(2)}`;
+                transactionDiv.children[2].innerText = `$${totalPrice.toFixed(2)}`;
 
 
                 i++;
                 i++;
             }
             }

+ 34 - 0
views/dashboardPage/sidebars/editIngredient.ejs

@@ -0,0 +1,34 @@
+<div id="editIngredient">
+    <div class="sidebarIconButtons mobileHide">
+        <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>
+
+    <h1 id="editIngTitle"></h1>
+
+    <label>NAME:
+        <input id="editIngName" type="text">
+    </label>
+
+    <label>CATEGORY:
+        <input id="editIngCategory" type="text">
+    </label>
+
+    <label id="editIngQuantityLabel"></label>
+
+    <label id="editSpecialLabel"></label>
+
+    <div class="lineBorder"></div>
+
+    <h3>MEASUREMENT UNIT</h3>
+
+    <div id="unitButtons"></div>
+
+    <div class="lineBorder"></div>
+
+    <button id="editIngSubmit" class="button">SUBMIT</button>
+</div>

+ 58 - 0
views/dashboardPage/sidebars/editRecipe.ejs

@@ -0,0 +1,58 @@
+<div id="editRecipe">
+    <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>
+
+    <label>NAME:
+        <input id="editRecipeName" type="text">
+    </label>
+    
+    <h1 id="editRecipeNoName"></h1>
+
+    <h3>INGREDIENTS</h3>
+
+    <div id="editRecipeIngList"></div>
+
+    <button id="addRecIng" class="iconButton">
+        <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+            <circle cx="12" cy="12" r="10"></circle>
+            <line x1="12" y1="8" x2="12" y2="16"></line>
+            <line x1="8" y1="12" x2="16" y2="12"></line>
+        </svg>
+    </button>
+
+    <div class="lineBorder"></div>
+
+    <h3>PRICE</h3>
+
+    <input id="editRecipePrice" type="number" min="0" step="0.01">
+
+    <div class="lineBorder"></div>
+
+    <div class="buttonBox">
+        <button id="editRecipeSubmit" class="button">UPDATE</button>
+        <button id="editRecipeCancel" class="button">CANCEL</button>
+    </div>
+
+    <template id="editRecipeIng">
+        <div class="editRecipeIng">
+            <button class="iconButton">
+                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
+                    <polyline points="3 6 5 6 21 6"></polyline>
+                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
+                </svg>
+            </button>
+
+            <p></p>
+
+            <select></select>
+
+            <input type="number" min="0" step="0.01">
+        </div>
+    </template>
+</div>

+ 7 - 23
views/dashboardPage/sidebars/ingredientDetails.ejs

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

+ 1 - 28
views/dashboardPage/sidebars/recipeDetails.ejs

@@ -26,46 +26,19 @@
 
 
     <h1 id="recipeName"></h1>
     <h1 id="recipeName"></h1>
     
     
-    <input id="recipeNameIn" type="text" style="display: none;">
-
     <div id="recipeIngredientList"></div>
     <div id="recipeIngredientList"></div>
 
 
-    <button id="addRecIng" class="iconButton" style="display: none;">
-        <svg width="30" height="30" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-            <circle cx="12" cy="12" r="10"></circle>
-            <line x1="12" y1="8" x2="12" y2="16"></line>
-            <line x1="8" y1="12" x2="16" y2="12"></line>
-        </svg>
-    </button>
-
     <div class="lineBorder"></div>
     <div class="lineBorder"></div>
 
 
     <div id="recipePrice">
     <div id="recipePrice">
-        <h3>Price</h3>
+        <h3>PRICE</h3>
         <p></p>
         <p></p>
-        <input type="number" min="0" step="0.01" style="display: none;">
     </div>
     </div>
 
 
-    <button id="recipeUpdate" class="button" style="display: none;">Update</button>
-
     <template id="recipeIngredient">
     <template id="recipeIngredient">
         <div class="recipeIngredient">
         <div class="recipeIngredient">
             <p class="recipeIngredientElement"></p>
             <p class="recipeIngredientElement"></p>
-            <input class="recipeIngredientElement"type="number" min="0" step="0.01" style="display: none;">
             <p class="recipeIngredientElement"></p>
             <p class="recipeIngredientElement"></p>
-            <button class="iconButton" style="display: none;">
-                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
-                    <polyline points="3 6 5 6 21 6"></polyline>
-                    <path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path>
-                </svg>
-            </button>
-        </div>
-    </template>
-
-    <template id="addRecIngredient">
-        <div class="addRecIngredient">
-            <select></select>
-            <input type="number" min="0" step="0.01">
         </div>
         </div>
     </template>
     </template>
 </div>
 </div>

+ 54 - 0
views/dashboardPage/sidebars/sidebars.css

@@ -302,6 +302,27 @@ Ingredient Details
         margin-top: 50px;
         margin-top: 50px;
     }
     }
 
 
+/*
+EDIT INGREDIENT
+*/
+#editIngredient{
+    flex-direction: column;
+    align-items: center;
+    width: 100%;
+}
+
+    #editIngredient label{
+        display: flex;
+        flex-direction: column;
+        align-items: center;
+    }
+
+    .unitbuttons{
+        width: 100%;
+        display: flex;
+        justify-content: space-around;
+    }
+
 /* 
 /* 
 Recipe Details 
 Recipe Details 
 */
 */
@@ -362,6 +383,7 @@ Recipe Details
             max-width: 25%;
             max-width: 25%;
             margin-left: 3px;
             margin-left: 3px;
         }
         }
+
 /*
 /*
 Add Recipe
 Add Recipe
 */
 */
@@ -436,6 +458,38 @@ Add Recipe
     #addRecipe button:last-of-type{
     #addRecipe button:last-of-type{
         margin-top: auto;
         margin-top: auto;
     }
     }
+/*
+EDIT RECIPE
+*/
+#editRecipe{
+    display: flex;
+    flex-direction: column;
+    align-items: center;
+    width: 100%;
+}
+
+    #editRecipeIngList{
+        width: 100%;
+        max-height: 75%;
+        overflow-y: auto;
+    }
+
+        .editRecipeIng{
+            background: rgb(0, 27, 45);
+            color: white;
+            width: 90%;
+            border-radius: 5px;
+            text-align: center;
+            padding: 5px;
+            margin: 5px auto;
+            position: relative;
+        }
+
+            .editRecipeIng button{
+                color: white;
+                position: absolute;
+                right: 5px;
+            }
 
 
 /* New Order */
 /* New Order */
 #newOrderIngredientList{
 #newOrderIngredientList{