analytics.js 11 KB

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