analytics.js 11 KB

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