analytics.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345
  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 ingredientTab = document.getElementById("analIngredientsTab");
  11. let recipeTab = document.getElementById("analRecipesTab");
  12. let categoryTab = document.getElementById("analCategoriesTab");
  13. ingredientTab.onclick = ()=>{this.tab(ingredientTab)};
  14. categoryTab.onclick = ()=>{this.tab(categoryTab)};
  15. recipeTab.onclick = ()=>{this.tab(recipeTab)};
  16. let to = new Date();
  17. let from = new Date(to.getFullYear(), to.getMonth() - 1, to.getDate());
  18. document.getElementById("analStartDate").valueAsDate = from;
  19. document.getElementById("analEndDate").valueAsDate = to;
  20. document.getElementById("analDateBtn").onclick = ()=>{this.newDates()};
  21. this.populateButtons();
  22. if(merchant.inventory.length > 0) this.ingredient = merchant.inventory[0].ingredient;
  23. if(merchant.recipes.length > 0) this.recipe = merchant.recipes[0];
  24. this.newDates();
  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.inventory.length; i++){
  35. let button = document.createElement("button");
  36. button.innerText = merchant.inventory[i].ingredient.name;
  37. button.classList.add("choosable");
  38. button.onclick = ()=>{
  39. this.ingredient = merchant.inventory[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){
  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"
  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) return;
  116. //break down data into dates and quantities
  117. let dates = [];
  118. let quantities = [];
  119. for(let i = 0; i < this.transactionsByDate.length; i++){
  120. dates.push(this.transactionsByDate[i].date);
  121. let sum = 0;
  122. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  123. let transaction = this.transactionsByDate[i].transactions[j];
  124. sum += transaction.getIngredientQuantity(this.ingredient);
  125. }
  126. quantities.push(sum);
  127. }
  128. //create and display the graph
  129. let trace = {
  130. x: dates,
  131. y: quantities,
  132. mode: "lines+markers",
  133. line: {
  134. color: "rgb(255, 99, 107)"
  135. }
  136. }
  137. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  138. const layout = {
  139. title: this.ingredient.name.toUpperCase(),
  140. xaxis: {title: "DATE"},
  141. yaxis: {title: yaxis},
  142. margin: {
  143. l: 40,
  144. r: 10,
  145. b: 20,
  146. t: 30
  147. },
  148. paper_bgcolor: "rgba(0, 0, 0, 0)"
  149. }
  150. Plotly.newPlot("itemUseGraph", [trace], layout);
  151. //Create min/max/avg
  152. //Current ingredient is stored on the "analMinUse" element
  153. let min = quantities[0];
  154. let max = quantities[0];
  155. let sum = 0;
  156. for(let i = 0; i < quantities.length; i++){
  157. if(quantities[i] < min){
  158. min = quantities[i];
  159. }
  160. if(quantities[i] > max){
  161. max = quantities[i];
  162. }
  163. sum += quantities[i];
  164. }
  165. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  166. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  167. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  168. //Create weekday averages
  169. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  170. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  171. for(let i = 0; i < quantities.length; i++){
  172. dayUse[dates[i].getDay()] += quantities[i];
  173. dayCount[dates[i].getDay()]++;
  174. }
  175. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  176. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  177. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  178. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  179. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  180. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  181. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  182. },
  183. displayCategory: function(){
  184. console.log("howdy");
  185. },
  186. displayRecipe: function(){
  187. if(this.recipe === undefined || this.transactionsByDate.length === 0) return;
  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. newDates: async function(){
  237. const from = document.getElementById("analStartDate").valueAsDate;
  238. const to = document.getElementById("analEndDate").valueAsDate;
  239. from.setHours(0, 0, 0, 0);
  240. to.setDate(to.getDate() + 1);
  241. to.setHours(0, 0, 0, 0);
  242. await this.getData(from, to);
  243. let analTabs = document.getElementById("analTabs");
  244. for(let i = 0; i < analTabs.children.length; i++){
  245. if(analTabs.children[i].classList.contains("active")){
  246. switch(analTabs.children[i].innerText.toLowerCase()){
  247. case "ingredients":
  248. this.displayIngredient();
  249. break;
  250. case "categories":
  251. this.displayCategory();
  252. break;
  253. case "recipes":
  254. this.displayRecipe();
  255. break;
  256. }
  257. }
  258. }
  259. },
  260. tab: function(tab){
  261. let analTabs = document.getElementById("analTabs");
  262. let ingredientContent = document.getElementById("analIngredientContent");
  263. let categoryContent = document.getElementById("analCategoryContent");
  264. let recipeContent = document.getElementById("analRecipeContent");
  265. for(let i = 0; i < analTabs.children.length; i++){
  266. analTabs.children[i].classList.remove("active");
  267. }
  268. tab.classList.add("active");
  269. ingredientContent.style.display = "none";
  270. categoryContent.style.display = "none";
  271. recipeContent.style.display = "none";
  272. switch(tab.innerText.toLowerCase()){
  273. case "ingredients":
  274. this.displayIngredient();
  275. ingredientContent.style.display = "flex";
  276. break;
  277. case "categories":
  278. this.displayCategory();
  279. categoryContent.style.display = "flex";
  280. break;
  281. case "recipes":
  282. recipeContent.style.display = "flex";
  283. this.displayRecipe();
  284. break;
  285. }
  286. }
  287. }
  288. module.exports = analytics;