analytics.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. if(this.ingredient.specialUnit === "bottle"){
  129. yaxis = `QUANTITY (${this.ingredient.specialUnit.toUpperCase()})`
  130. }
  131. const layout = {
  132. title: this.ingredient.name.toUpperCase(),
  133. xaxis: {title: "DATE"},
  134. yaxis: {title: yaxis}
  135. }
  136. Plotly.newPlot("itemUseGraph", [trace], layout);
  137. //Create min/max/avg
  138. //Current ingredient is stored on the "analMinUse" element
  139. let min = quantities[0];
  140. let max = quantities[0];
  141. let sum = 0;
  142. for(let i = 0; i < quantities.length; i++){
  143. if(quantities[i] < min){
  144. min = quantities[i];
  145. }
  146. if(quantities[i] > max){
  147. max = quantities[i];
  148. }
  149. sum += quantities[i];
  150. }
  151. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  152. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  153. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  154. //Create weekday averages
  155. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  156. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  157. for(let i = 0; i < quantities.length; i++){
  158. dayUse[dates[i].getDay()] += quantities[i];
  159. dayCount[dates[i].getDay()]++;
  160. }
  161. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  162. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  163. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  164. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  165. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  166. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  167. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  168. },
  169. displayRecipe: function(){
  170. if(this.recipe === undefined || this.transactionsByDate.length === 0){
  171. return;
  172. }
  173. //break down data into dates and quantities
  174. let dates = [];
  175. let quantities = [];
  176. for(let i = 0; i < this.transactionsByDate.length; i++){
  177. dates.push(this.transactionsByDate[i].date);
  178. let sum = 0;
  179. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  180. const transaction = this.transactionsByDate[i].transactions[j];
  181. for(let k = 0; k < transaction.recipes.length; k++){
  182. if(transaction.recipes[k].recipe === this.recipe){
  183. sum += transaction.recipes[k].quantity;
  184. }
  185. }
  186. }
  187. quantities.push(sum);
  188. }
  189. //create and display the graph
  190. const trace = {
  191. x: dates,
  192. y: quantities,
  193. mode: "lines+markers",
  194. line: {
  195. color: "rgb(255, 99, 107)"
  196. }
  197. }
  198. const layout = {
  199. title: this.recipe.name.toUpperCase(),
  200. xaxis: {title: "DATE"},
  201. yaxis: {title: "QUANTITY"}
  202. }
  203. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  204. //Display the boxes at the bottom
  205. //Current recipe is stored on the "recipeAvgUse" element
  206. let avg = 0;
  207. for(let i = 0; i < quantities.length; i++){
  208. avg += quantities[i];
  209. }
  210. avg = avg / quantities.length;
  211. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  212. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  213. },
  214. switchDisplay: function(){
  215. const checkbox = document.getElementById("analSlider");
  216. let ingredient = document.getElementById("analIngredientContent");
  217. let recipe = document.getElementById("analRecipeContent");
  218. if(checkbox.checked === true){
  219. ingredient.style.display = "none";
  220. recipe.style.display = "flex";
  221. this.displayRecipe();
  222. }else{
  223. ingredient.style.display = "flex";
  224. recipe.style.display = "none";
  225. this.displayIngredient();
  226. }
  227. },
  228. newDates: async function(Transaction){
  229. const from = document.getElementById("analStartDate").valueAsDate;
  230. const to = document.getElementById("analEndDate").valueAsDate;
  231. from.setHours(0, 0, 0, 0);
  232. to.setDate(to.getDate() + 1);
  233. to.setHours(0, 0, 0, 0);
  234. await this.getData(from, to, Transaction);
  235. if(document.getElementById("analSlider").checked === true){
  236. this.displayRecipe();
  237. }else{
  238. this.displayIngredient();
  239. }
  240. }
  241. }
  242. module.exports = analytics;