Ver Fonte

Bug Fix: circular dependency between transactioData and helper when creating new transaction.

Lee Morgan há 5 anos atrás
pai
commit
e1e318ebb4

+ 0 - 27
controllers/helper.js

@@ -184,33 +184,6 @@ module.exports = {
             });
     },
 
-    /*
-    Updates the quanties of ingredients from a list of transactions
-    ingredients = Object. keys = ingredient ids, values = quantity to change (g)
-    user = id of logged in user
-    */
-    updateIngredientQuantities: function(ingredients, user){
-        Merchant.findOne({_id: user})
-            .then((merchant)=>{
-                let keys = Object.keys(ingredients);
-
-                for(let i = 0; i < keys.length; i++){
-                    for(let j = 0; j < merchant.inventory.length; j++){
-                        if(merchant.inventory[j].ingredient._id.toString() === keys[i]){
-                            merchant.inventory[j].quantity -= ingredients[keys[i]];
-
-                            break;
-                        }
-                    }
-                }
-
-                return merchant.save();
-            })
-            .catch((err)=>{
-                return false;
-            });
-    },
-
     convertQuantityToBaseUnit: function(quantity, unit){
         switch(unit){
             case "g":return quantity; 

+ 30 - 24
controllers/transactionData.js

@@ -84,13 +84,35 @@ module.exports = {
             recipes: req.body.recipes
         });
 
-        helper.updateIngredientQuantities(req.body.ingredientUpdates, req.session.user);
+        Merchant.findOne({_id: req.session.user})
+            .then((merchant)=>{
+                let keys = Object.keys(req.body.ingredientUpdates);
+
+                for(let i = 0; i < keys.length; i++){
+                    for(let j = 0; j < merchant.inventory.length; j++){
+                        if(merchant.inventory[j].ingredient._id.toString() === keys[i]){
+                            merchant.inventory[j].quantity -= req.body.ingredientUpdates[keys[i]];
+
+                            break;
+                        }
+                    }
+                }
 
-        newTransaction.save()
+                return merchant.save();
+            })
+            .then((merchant)=>{
+                return new Transaction({
+                    merchant: req.session.user,
+                    date: new Date(req.body.date),
+                    device: "none",
+                    recipes: req.body.recipes
+                }).save();
+            })
             .then((response)=>{
                 return res.json(response);
             })
             .catch((err)=>{
+                console.log(err);
                 if(typeof(err) === "string"){
                     return res.json(err);
                 }
@@ -149,12 +171,16 @@ module.exports = {
                 if(array[1][0] === undefined){
                     transaction.date = new Date();
                 }else{
-                    transaction.date = new Date(array[1][0]);
+                    transaction.date = new Date(array[1][locations.date]);
                 }
                 
                 let ingredients = [];
                 for(let i = 1; i < array.length; i++){
-                    if(array[i][locations.recipes] === undefined || array[i][locations.quantity === 0]){
+                    if(
+                        array[i][locations.recipes] === undefined || 
+                        array[i][locations.quantity] === 0 ||
+                        array[i][locations.quantity] === undefined
+                    ){
                         continue;
                     }
 
@@ -308,7 +334,6 @@ module.exports = {
 
         const from = new Date(req.params.from);
         const to = new Date(req.params.to);
-        to.setDate(to.getDate() + 1);
 
         Transaction.aggregate([
             {$match: {
@@ -318,25 +343,6 @@ module.exports = {
                     $lt: to
                 }
             }},
-            {$group: {
-                _id: {$function: {
-                    body: "function(year, month, date){return `${year}-${month}-${date}`;}",
-                    args: [{$year: "$date"}, {$month: "$date"}, {$dayOfMonth: "$date"}],
-                    lang: "js"
-                }},
-                transactions: {$push: {
-                    _id: "$_id",
-                    recipes: "$recipes"
-                }}
-            }},
-            {$project: {
-                _id: 0,
-                date: {$convert: {
-                    input: "$_id",
-                    to: "date"
-                }},
-                transactions: 1
-            }},
             {$sort: {
                 date: 1
             }}

+ 64 - 28
views/dashboardPage/bundle.js

@@ -784,25 +784,22 @@ class Merchant{
 
     getTransactionIndices(from, to){
         let start, end;
-        console.log(from);
-        console.log(to);
         
-
         for(let i = this._transactions.length - 1; i >= 0; i--){
             if(this._transactions[i].date >= from){
-                start = i;
+                end = i;
                 break;
             }
         }
         
         for(let i = 0; i < this._transactions.length; i++){
             if(this._transactions[i].date < to){
-                end = i;
+                start = i;
                 break;
             }
         }
 
-        if(start === undefined){
+        if(end === undefined){
             return false;
         }
 
@@ -2646,20 +2643,51 @@ module.exports = newTransaction;
 },{}],14:[function(require,module,exports){
 let orderCalculator = {
     display: function(){
+        let calculatorItems = document.getElementById("calculatorItems");
+        let template = document.getElementById("calculatorItem").content.children[0];
         let calculations = this.getDailyAverages();
 
-        // console.log(calculations);
-
+        for(let i = 0; i < calculations.length; i++){
+            let item = template.cloneNode(true);
+            item.children[0].innerText = calculations[i].ingredient.name,
+            item.children[1].innerText = `${calculations[i].output.toFixed(2)} ${calculations[i].ingredient.unit.toUpperCase()}`;
+            calculatorItems.appendChild(item);
+        }
     },
 
     getDailyAverages: function(){
         let now = new Date();
         let yesterday = new Date();
         yesterday.setHours(0, 0, 0, 0);
-        let past = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30);
+        let monthAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30);
+        let weekAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
+    
+        let calculations = [];
+
+        let month = merchant.getIngredientsSold(monthAgo, yesterday);
+        let week = merchant.getIngredientsSold(weekAgo, yesterday);
+
+        let weights = {
+            month: 0.33,
+            week: 0.67
+        }
+
+        for(let i = 0; i < month.length; i++){
+            for(let j = 0; j < week.length; j++){
+                if(month[i].ingredient.id === week[j].ingredient.id){
+                    let monthAverage = (month[i].quantity / 30) * weights.month;
+                    let weekAverage = (week[i].quantity / 7) * weights.week;
+
+                    let calc = {
+                        ingredient: month[i].ingredient,
+                        output: monthAverage + weekAverage
+                    };
+                    calculations.push(calc);
+                }
+            }
+        }
 
-        let ingredients = merchant.getIngredientsSold(past, yesterday);
-        console.log(ingredients);
+        return calculations;
     }
 }
 
@@ -3104,8 +3132,6 @@ let analytics = {
 
             this.populateButtons();
 
-            let hasIngredients
-
             if(merchant.ingredients.length > 0){
                 this.ingredient = merchant.ingredients[0].ingredient;
             }
@@ -3140,7 +3166,7 @@ let analytics = {
             button.classList.add("choosable");
             button.onclick = ()=>{
                 this.recipe = merchant.recipes[i];
-                this.displayRecipe()
+                this.displayRecipe();
             };
             recipeButtons.appendChild(button);
         }
@@ -3158,24 +3184,30 @@ let analytics = {
                 }else{
                     this.transactionsByDate = [];
 
+
+                    let nextDay = new Date(from.getTime());
+                    nextDay.setDate(nextDay.getDate() + 1);
+                    let currentTransactions = [];
                     for(let i = 0; i < response.length; i++){
-                        const date = new Date(response[i].date);
-                        let newDate = {
-                            date: date,
-                            transactions: []
-                        };
-
-                        for(let j = 0; j < response[i].transactions.length; j++){
-                            newDate.transactions.push(new Transaction(
-                                response[i].transactions[j]._id,
-                                date,
-                                response[i].transactions[j].recipes,
+                        response[i].date = new Date(response[i].date);
+                        if(response[i].date >= from && response[i].date < nextDay){
+                            currentTransactions.push(new Transaction(
+                                response[i]._id,
+                                response[i].date,
+                                response[i].recipes,
                                 merchant
                             ));
+                        }else{
+                            this.transactionsByDate.push({
+                                date: new Date(from.getTime()),
+                                transactions: currentTransactions
+                            });
+                            from.setDate(from.getDate() + 1);
+                            nextDay.setDate(nextDay.getDate() + 1);
+                            currentTransactions = [];
                         }
-
-                        this.transactionsByDate.push(newDate);
                     }
+
                 }
             })
             .catch((err)=>{
@@ -3190,6 +3222,7 @@ let analytics = {
         if(this.ingredient === undefined  || this.transactionsByDate.length === 0){
             return;
         }
+
         //break down data into dates and quantities
         let dates = [];
         let quantities = [];
@@ -3262,7 +3295,7 @@ let analytics = {
     },
 
     displayRecipe: function(){
-        if(this.recipes === undefined || this.transactionsByDate.length === 0){
+        if(this.recipe === undefined || this.transactionsByDate.length === 0){
             return;
         }
 
@@ -3336,6 +3369,9 @@ let analytics = {
     newDates: async function(Transaction){
         const from = document.getElementById("analStartDate").valueAsDate;
         const to = document.getElementById("analEndDate").valueAsDate;
+        from.setHours(0, 0, 0, 0);
+        to.setDate(to.getDate() + 1);
+        to.setHours(0, 0, 0, 0);
 
         await this.getData(from, to, Transaction);
 

+ 3 - 6
views/dashboardPage/js/classes/Merchant.js

@@ -657,25 +657,22 @@ class Merchant{
 
     getTransactionIndices(from, to){
         let start, end;
-        console.log(from);
-        console.log(to);
         
-
         for(let i = this._transactions.length - 1; i >= 0; i--){
             if(this._transactions[i].date >= from){
-                start = i;
+                end = i;
                 break;
             }
         }
         
         for(let i = 0; i < this._transactions.length; i++){
             if(this._transactions[i].date < to){
-                end = i;
+                start = i;
                 break;
             }
         }
 
-        if(start === undefined){
+        if(end === undefined){
             return false;
         }
 

+ 36 - 5
views/dashboardPage/js/sidebars/orderCalculator.js

@@ -1,19 +1,50 @@
 let orderCalculator = {
     display: function(){
+        let calculatorItems = document.getElementById("calculatorItems");
+        let template = document.getElementById("calculatorItem").content.children[0];
         let calculations = this.getDailyAverages();
 
-        // console.log(calculations);
-
+        for(let i = 0; i < calculations.length; i++){
+            let item = template.cloneNode(true);
+            item.children[0].innerText = calculations[i].ingredient.name,
+            item.children[1].innerText = `${calculations[i].output.toFixed(2)} ${calculations[i].ingredient.unit.toUpperCase()}`;
+            calculatorItems.appendChild(item);
+        }
     },
 
     getDailyAverages: function(){
         let now = new Date();
         let yesterday = new Date();
         yesterday.setHours(0, 0, 0, 0);
-        let past = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30);
+        let monthAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 30);
+        let weekAgo = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
+    
+        let calculations = [];
+
+        let month = merchant.getIngredientsSold(monthAgo, yesterday);
+        let week = merchant.getIngredientsSold(weekAgo, yesterday);
+
+        let weights = {
+            month: 0.33,
+            week: 0.67
+        }
+
+        for(let i = 0; i < month.length; i++){
+            for(let j = 0; j < week.length; j++){
+                if(month[i].ingredient.id === week[j].ingredient.id){
+                    let monthAverage = (month[i].quantity / 30) * weights.month;
+                    let weekAverage = (week[i].quantity / 7) * weights.week;
+
+                    let calc = {
+                        ingredient: month[i].ingredient,
+                        output: monthAverage + weekAverage
+                    };
+                    calculations.push(calc);
+                }
+            }
+        }
 
-        let ingredients = merchant.getIngredientsSold(past, yesterday);
-        console.log(ingredients);
+        return calculations;
     }
 }
 

+ 25 - 17
views/dashboardPage/js/strands/analytics.js

@@ -20,8 +20,6 @@ let analytics = {
 
             this.populateButtons();
 
-            let hasIngredients
-
             if(merchant.ingredients.length > 0){
                 this.ingredient = merchant.ingredients[0].ingredient;
             }
@@ -56,7 +54,7 @@ let analytics = {
             button.classList.add("choosable");
             button.onclick = ()=>{
                 this.recipe = merchant.recipes[i];
-                this.displayRecipe()
+                this.displayRecipe();
             };
             recipeButtons.appendChild(button);
         }
@@ -74,24 +72,30 @@ let analytics = {
                 }else{
                     this.transactionsByDate = [];
 
+
+                    let nextDay = new Date(from.getTime());
+                    nextDay.setDate(nextDay.getDate() + 1);
+                    let currentTransactions = [];
                     for(let i = 0; i < response.length; i++){
-                        const date = new Date(response[i].date);
-                        let newDate = {
-                            date: date,
-                            transactions: []
-                        };
-
-                        for(let j = 0; j < response[i].transactions.length; j++){
-                            newDate.transactions.push(new Transaction(
-                                response[i].transactions[j]._id,
-                                date,
-                                response[i].transactions[j].recipes,
+                        response[i].date = new Date(response[i].date);
+                        if(response[i].date >= from && response[i].date < nextDay){
+                            currentTransactions.push(new Transaction(
+                                response[i]._id,
+                                response[i].date,
+                                response[i].recipes,
                                 merchant
                             ));
+                        }else{
+                            this.transactionsByDate.push({
+                                date: new Date(from.getTime()),
+                                transactions: currentTransactions
+                            });
+                            from.setDate(from.getDate() + 1);
+                            nextDay.setDate(nextDay.getDate() + 1);
+                            currentTransactions = [];
                         }
-
-                        this.transactionsByDate.push(newDate);
                     }
+
                 }
             })
             .catch((err)=>{
@@ -106,6 +110,7 @@ let analytics = {
         if(this.ingredient === undefined  || this.transactionsByDate.length === 0){
             return;
         }
+
         //break down data into dates and quantities
         let dates = [];
         let quantities = [];
@@ -178,7 +183,7 @@ let analytics = {
     },
 
     displayRecipe: function(){
-        if(this.recipes === undefined || this.transactionsByDate.length === 0){
+        if(this.recipe === undefined || this.transactionsByDate.length === 0){
             return;
         }
 
@@ -252,6 +257,9 @@ let analytics = {
     newDates: async function(Transaction){
         const from = document.getElementById("analStartDate").valueAsDate;
         const to = document.getElementById("analEndDate").valueAsDate;
+        from.setHours(0, 0, 0, 0);
+        to.setDate(to.getDate() + 1);
+        to.setHours(0, 0, 0, 0);
 
         await this.getData(from, to, Transaction);
 

+ 9 - 0
views/dashboardPage/sidebars/orderCalculator.ejs

@@ -9,4 +9,13 @@
     </div>
 
     <h1>ORDER CALCULATOR</h1>
+
+    <div id="calculatorItems"></div>
+
+    <template id="calculatorItem">
+        <div class="calculatorItem">
+            <p></p>
+            <p></p>
+        </div>
+    </template>
 </div>