analytics.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  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 data = {
  60. from: from,
  61. to: to,
  62. recipes: []
  63. }
  64. let loader = document.getElementById("loaderContainer");
  65. loader.style.display = "flex";
  66. return fetch("/transaction", {
  67. method: "post",
  68. headers: {
  69. "Content-Type": "application/json;charset=utf-8"
  70. },
  71. body: JSON.stringify(data)
  72. })
  73. .then(response => response.json())
  74. .then((response)=>{
  75. if(typeof(response) === "string"){
  76. controller.createBanner(response, "error");
  77. }else{
  78. this.transactionsByDate = [];
  79. response.reverse();
  80. let startOfDay = new Date(from.getTime());
  81. startOfDay.setHours(0, 0, 0, 0);
  82. let endOfDay = new Date(from.getTime());
  83. endOfDay.setDate(endOfDay.getDate() + 1);
  84. endOfDay.setHours(0, 0, 0, 0);
  85. let transactionIndex = 0;
  86. while(startOfDay <= to){
  87. let currentTransactions = [];
  88. while(transactionIndex < response.length && new Date(response[transactionIndex].date) < endOfDay){
  89. currentTransactions.push(new Transaction(
  90. response[transactionIndex]._id,
  91. response[transactionIndex].date,
  92. response[transactionIndex].recipes,
  93. merchant
  94. ));
  95. transactionIndex++;
  96. }
  97. let thing = {
  98. date: new Date(startOfDay.getTime()),
  99. transactions: currentTransactions
  100. };
  101. this.transactionsByDate.push(thing);
  102. startOfDay.setDate(startOfDay.getDate() + 1);
  103. endOfDay.setDate(endOfDay.getDate() + 1);
  104. }
  105. }
  106. })
  107. .catch((err)=>{
  108. controller.createBanner("UNABLE TO UPDATE THE PAGE", "error");
  109. })
  110. .finally(()=>{
  111. loader.style.display = "none";
  112. });
  113. },
  114. displayIngredient: function(){
  115. if(this.ingredient === undefined || this.transactionsByDate.length === 0){
  116. return;
  117. }
  118. //break down data into dates and quantities
  119. let dates = [];
  120. let quantities = [];
  121. for(let i = 0; i < this.transactionsByDate.length; i++){
  122. dates.push(this.transactionsByDate[i].date);
  123. let sum = 0;
  124. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  125. let transaction = this.transactionsByDate[i].transactions[j];
  126. sum += transaction.getIngredientQuantity(this.ingredient);
  127. }
  128. quantities.push(sum);
  129. }
  130. //create and display the graph
  131. let trace = {
  132. x: dates,
  133. y: quantities,
  134. mode: "lines+markers",
  135. line: {
  136. color: "rgb(255, 99, 107)"
  137. }
  138. }
  139. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  140. const layout = {
  141. title: this.ingredient.name.toUpperCase(),
  142. xaxis: {title: "DATE"},
  143. yaxis: {title: yaxis}
  144. }
  145. Plotly.newPlot("itemUseGraph", [trace], layout);
  146. //Create min/max/avg
  147. //Current ingredient is stored on the "analMinUse" element
  148. let min = quantities[0];
  149. let max = quantities[0];
  150. let sum = 0;
  151. for(let i = 0; i < quantities.length; i++){
  152. if(quantities[i] < min){
  153. min = quantities[i];
  154. }
  155. if(quantities[i] > max){
  156. max = quantities[i];
  157. }
  158. sum += quantities[i];
  159. }
  160. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  161. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  162. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  163. //Create weekday averages
  164. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  165. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  166. for(let i = 0; i < quantities.length; i++){
  167. dayUse[dates[i].getDay()] += quantities[i];
  168. dayCount[dates[i].getDay()]++;
  169. }
  170. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  171. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  172. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  173. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  174. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  175. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  176. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  177. },
  178. displayRecipe: function(){
  179. if(this.recipe === undefined || this.transactionsByDate.length === 0){
  180. return;
  181. }
  182. //break down data into dates and quantities
  183. let dates = [];
  184. let quantities = [];
  185. for(let i = 0; i < this.transactionsByDate.length; i++){
  186. dates.push(this.transactionsByDate[i].date);
  187. let sum = 0;
  188. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  189. const transaction = this.transactionsByDate[i].transactions[j];
  190. for(let k = 0; k < transaction.recipes.length; k++){
  191. if(transaction.recipes[k].recipe === this.recipe){
  192. sum += transaction.recipes[k].quantity;
  193. }
  194. }
  195. }
  196. quantities.push(sum);
  197. }
  198. //create and display the graph
  199. const trace = {
  200. x: dates,
  201. y: quantities,
  202. mode: "lines+markers",
  203. line: {
  204. color: "rgb(255, 99, 107)"
  205. }
  206. }
  207. const layout = {
  208. title: this.recipe.name.toUpperCase(),
  209. xaxis: {title: "DATE"},
  210. yaxis: {title: "QUANTITY"}
  211. }
  212. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  213. //Display the boxes at the bottom
  214. //Current recipe is stored on the "recipeAvgUse" element
  215. let avg = 0;
  216. for(let i = 0; i < quantities.length; i++){
  217. avg += quantities[i];
  218. }
  219. avg = avg / quantities.length;
  220. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  221. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  222. },
  223. switchDisplay: function(){
  224. const checkbox = document.getElementById("analSlider");
  225. let ingredient = document.getElementById("analIngredientContent");
  226. let recipe = document.getElementById("analRecipeContent");
  227. if(checkbox.checked === true){
  228. ingredient.style.display = "none";
  229. recipe.style.display = "flex";
  230. this.displayRecipe();
  231. }else{
  232. ingredient.style.display = "flex";
  233. recipe.style.display = "none";
  234. this.displayIngredient();
  235. }
  236. },
  237. newDates: async function(Transaction){
  238. const from = document.getElementById("analStartDate").valueAsDate;
  239. const to = document.getElementById("analEndDate").valueAsDate;
  240. from.setHours(0, 0, 0, 0);
  241. to.setDate(to.getDate() + 1);
  242. to.setHours(0, 0, 0, 0);
  243. await this.getData(from, to, Transaction);
  244. if(document.getElementById("analSlider").checked === true){
  245. this.displayRecipe();
  246. }else{
  247. this.displayIngredient();
  248. }
  249. }
  250. }
  251. module.exports = analytics;