analytics.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  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.inventory.length > 0){
  20. this.ingredient = merchant.inventory[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.inventory.length; i++){
  36. let button = document.createElement("button");
  37. button.innerText = merchant.inventory[i].ingredient.name;
  38. button.classList.add("choosable");
  39. button.onclick = ()=>{
  40. this.ingredient = merchant.inventory[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) return;
  117. //break down data into dates and quantities
  118. let dates = [];
  119. let quantities = [];
  120. for(let i = 0; i < this.transactionsByDate.length; i++){
  121. dates.push(this.transactionsByDate[i].date);
  122. let sum = 0;
  123. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  124. let transaction = this.transactionsByDate[i].transactions[j];
  125. sum += transaction.getIngredientQuantity(this.ingredient);
  126. }
  127. quantities.push(sum);
  128. }
  129. //create and display the graph
  130. let trace = {
  131. x: dates,
  132. y: quantities,
  133. mode: "lines+markers",
  134. line: {
  135. color: "rgb(255, 99, 107)"
  136. }
  137. }
  138. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  139. const layout = {
  140. title: this.ingredient.name.toUpperCase(),
  141. xaxis: {title: "DATE"},
  142. yaxis: {title: yaxis},
  143. margin: {
  144. l: 40,
  145. r: 10,
  146. b: 20,
  147. t: 30
  148. },
  149. paper_bgcolor: "rgba(0, 0, 0, 0)"
  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. paper_bgcolor: "rgba(0, 0, 0, 0)"
  224. }
  225. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  226. //Display the boxes at the bottom
  227. //Current recipe is stored on the "recipeAvgUse" element
  228. let avg = 0;
  229. for(let i = 0; i < quantities.length; i++){
  230. avg += quantities[i];
  231. }
  232. avg = avg / quantities.length;
  233. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  234. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  235. },
  236. switchDisplay: function(){
  237. const checkbox = document.getElementById("analSlider");
  238. let ingredient = document.getElementById("analIngredientContent");
  239. let recipe = document.getElementById("analRecipeContent");
  240. if(checkbox.checked === true){
  241. ingredient.style.display = "none";
  242. recipe.style.display = "flex";
  243. this.displayRecipe();
  244. }else{
  245. ingredient.style.display = "flex";
  246. recipe.style.display = "none";
  247. this.displayIngredient();
  248. }
  249. },
  250. newDates: async function(){
  251. const from = document.getElementById("analStartDate").valueAsDate;
  252. const to = document.getElementById("analEndDate").valueAsDate;
  253. from.setHours(0, 0, 0, 0);
  254. to.setDate(to.getDate() + 1);
  255. to.setHours(0, 0, 0, 0);
  256. await this.getData(from, to);
  257. if(document.getElementById("analSlider").checked === true){
  258. this.displayRecipe();
  259. }else{
  260. this.displayIngredient();
  261. }
  262. }
  263. }
  264. module.exports = analytics;