analytics.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. let analytics = {
  2. isPopulated: false,
  3. ingredient: undefined,
  4. recipe: undefined,
  5. transactionsByDate: [],
  6. display: function(Transaction){
  7. if(!this.isPopulated){
  8. document.getElementById("analRecipeContent").style.display = "none";
  9. let to = new Date()
  10. let from = new Date(to.getFullYear(), to.getMonth() - 1, to.getDate());
  11. document.getElementById("analStartDate").valueAsDate = from;
  12. document.getElementById("analEndDate").valueAsDate = to;
  13. let analSlider = document.getElementById("analSlider");
  14. analSlider.onclick = ()=>{this.switchDisplay()};
  15. analSlider.checked = false;
  16. document.getElementById("analDateBtn").onclick = ()=>{this.newDates(Transaction)};
  17. this.populateButtons();
  18. if(merchant.ingredients.length > 0){
  19. this.ingredient = merchant.ingredients[0].ingredient;
  20. }
  21. if(merchant.recipes.length > 0){
  22. this.recipe = merchant.recipes[0];
  23. }
  24. this.newDates(Transaction);
  25. this.isPopulated = true;
  26. }
  27. },
  28. populateButtons: function(){
  29. let ingredientButtons = document.getElementById("analIngredientList");
  30. let recipeButtons = document.getElementById("analRecipeList");
  31. while(ingredientButtons.children.length > 0){
  32. ingredientButtons.removeChild(ingredientButtons.firstChild);
  33. }
  34. for(let i = 0; i < merchant.ingredients.length; i++){
  35. let button = document.createElement("button");
  36. button.innerText = merchant.ingredients[i].ingredient.name;
  37. button.classList.add("choosable");
  38. button.onclick = ()=>{
  39. this.ingredient = merchant.ingredients[i].ingredient;
  40. this.displayIngredient();
  41. };
  42. ingredientButtons.appendChild(button);
  43. }
  44. while(recipeButtons.children.length > 0){
  45. recipeButtons.removeChild(recipeButtons.firstChild);
  46. }
  47. for(let i = 0; i < merchant.recipes.length; i++){
  48. let button = document.createElement("button");
  49. button.innerText = merchant.recipes[i].name;
  50. button.classList.add("choosable");
  51. button.onclick = ()=>{
  52. this.recipe = merchant.recipes[i];
  53. this.displayRecipe();
  54. };
  55. recipeButtons.appendChild(button);
  56. }
  57. },
  58. getData: function(from, to, Transaction){
  59. let loader = document.getElementById("loaderContainer");
  60. loader.style.display = "flex";
  61. return fetch(`/transactions/${from.toISOString()}/${to.toISOString()}`)
  62. .then(response => response.json())
  63. .then((response)=>{
  64. if(typeof(response) === "string"){
  65. controller.createBanner(response, "error");
  66. }else{
  67. this.transactionsByDate = [];
  68. let startOfDay = new Date(from.getTime());
  69. startOfDay.setHours(0, 0, 0, 0);
  70. let endOfDay = new Date(from.getTime());
  71. endOfDay.setDate(endOfDay.getDate() + 1);
  72. endOfDay.setHours(0, 0, 0, 0);
  73. let transactionIndex = 0;
  74. while(startOfDay <= to){
  75. let currentTransactions = [];
  76. while(transactionIndex < response.length && new Date(response[transactionIndex].date) < endOfDay){
  77. currentTransactions.push(new Transaction(
  78. response[transactionIndex]._id,
  79. response[transactionIndex].date,
  80. response[transactionIndex].recipes,
  81. merchant
  82. ));
  83. transactionIndex++;
  84. }
  85. let thing = {
  86. date: new Date(startOfDay.getTime()),
  87. transactions: currentTransactions
  88. };
  89. this.transactionsByDate.push(thing);
  90. startOfDay.setDate(startOfDay.getDate() + 1);
  91. endOfDay.setDate(endOfDay.getDate() + 1);
  92. }
  93. }
  94. })
  95. .catch((err)=>{
  96. controller.createBanner("UNABLE TO UPDATE THE PAGE", "error");
  97. })
  98. .finally(()=>{
  99. loader.style.display = "none";
  100. });
  101. },
  102. displayIngredient: function(){
  103. if(this.ingredient === undefined || this.transactionsByDate.length === 0){
  104. return;
  105. }
  106. //break down data into dates and quantities
  107. let dates = [];
  108. let quantities = [];
  109. for(let i = 0; i < this.transactionsByDate.length; i++){
  110. dates.push(this.transactionsByDate[i].date);
  111. let sum = 0;
  112. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  113. let transaction = this.transactionsByDate[i].transactions[j];
  114. sum += transaction.getIngredientQuantity(this.ingredient);
  115. }
  116. quantities.push(sum);
  117. }
  118. //create and display the graph
  119. let trace = {
  120. x: dates,
  121. y: quantities,
  122. mode: "lines+markers",
  123. line: {
  124. color: "rgb(255, 99, 107)"
  125. }
  126. }
  127. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  128. const layout = {
  129. title: this.ingredient.name.toUpperCase(),
  130. xaxis: {title: "DATE"},
  131. yaxis: {title: yaxis}
  132. }
  133. Plotly.newPlot("itemUseGraph", [trace], layout);
  134. //Create min/max/avg
  135. //Current ingredient is stored on the "analMinUse" element
  136. let min = quantities[0];
  137. let max = quantities[0];
  138. let sum = 0;
  139. for(let i = 0; i < quantities.length; i++){
  140. if(quantities[i] < min){
  141. min = quantities[i];
  142. }
  143. if(quantities[i] > max){
  144. max = quantities[i];
  145. }
  146. sum += quantities[i];
  147. }
  148. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  149. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  150. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  151. //Create weekday averages
  152. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  153. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  154. for(let i = 0; i < quantities.length; i++){
  155. dayUse[dates[i].getDay()] += quantities[i];
  156. dayCount[dates[i].getDay()]++;
  157. }
  158. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  159. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  160. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  161. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  162. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  163. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  164. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  165. },
  166. displayRecipe: function(){
  167. if(this.recipe === undefined || this.transactionsByDate.length === 0){
  168. return;
  169. }
  170. //break down data into dates and quantities
  171. let dates = [];
  172. let quantities = [];
  173. for(let i = 0; i < this.transactionsByDate.length; i++){
  174. dates.push(this.transactionsByDate[i].date);
  175. let sum = 0;
  176. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  177. const transaction = this.transactionsByDate[i].transactions[j];
  178. for(let k = 0; k < transaction.recipes.length; k++){
  179. if(transaction.recipes[k].recipe === this.recipe){
  180. sum += transaction.recipes[k].quantity;
  181. }
  182. }
  183. }
  184. quantities.push(sum);
  185. }
  186. //create and display the graph
  187. const trace = {
  188. x: dates,
  189. y: quantities,
  190. mode: "lines+markers",
  191. line: {
  192. color: "rgb(255, 99, 107)"
  193. }
  194. }
  195. const layout = {
  196. title: this.recipe.name.toUpperCase(),
  197. xaxis: {title: "DATE"},
  198. yaxis: {title: "QUANTITY"}
  199. }
  200. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  201. //Display the boxes at the bottom
  202. //Current recipe is stored on the "recipeAvgUse" element
  203. let avg = 0;
  204. for(let i = 0; i < quantities.length; i++){
  205. avg += quantities[i];
  206. }
  207. avg = avg / quantities.length;
  208. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  209. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  210. },
  211. switchDisplay: function(){
  212. const checkbox = document.getElementById("analSlider");
  213. let ingredient = document.getElementById("analIngredientContent");
  214. let recipe = document.getElementById("analRecipeContent");
  215. if(checkbox.checked === true){
  216. ingredient.style.display = "none";
  217. recipe.style.display = "flex";
  218. this.displayRecipe();
  219. }else{
  220. ingredient.style.display = "flex";
  221. recipe.style.display = "none";
  222. this.displayIngredient();
  223. }
  224. },
  225. newDates: async function(Transaction){
  226. const from = document.getElementById("analStartDate").valueAsDate;
  227. const to = document.getElementById("analEndDate").valueAsDate;
  228. from.setHours(0, 0, 0, 0);
  229. to.setDate(to.getDate() + 1);
  230. to.setHours(0, 0, 0, 0);
  231. await this.getData(from, to, Transaction);
  232. if(document.getElementById("analSlider").checked === true){
  233. this.displayRecipe();
  234. }else{
  235. this.displayIngredient();
  236. }
  237. }
  238. }
  239. module.exports = analytics;