analytics.js 11 KB

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