analytics.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. const Transaction = require("../classes/Transaction.js");
  2. let analytics = {
  3. isPopulated: false,
  4. ingredient: undefined,
  5. category: undefined,
  6. recipe: undefined,
  7. transactionsByDate: [],
  8. display: function(){
  9. if(!this.isPopulated){
  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 categoryButtons = document.getElementById("analCategoriesList");
  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(categoryButtons.children.length > 0){
  46. categoryButtons.removeChild(categoryButtons.firstChild);
  47. }
  48. let categories = merchant.categorizeIngredients();
  49. for(let i = 0; i < categories.length; i++){
  50. let button = document.createElement("button");
  51. button.innerText = categories[i].name;
  52. button.classList.add("choosable");
  53. button.onclick = ()=>{
  54. this.category = categories[i];
  55. this.displayCategory();
  56. }
  57. categoryButtons.appendChild(button);
  58. }
  59. while(recipeButtons.children.length > 0){
  60. recipeButtons.removeChild(recipeButtons.firstChild);
  61. }
  62. for(let i = 0; i < merchant.recipes.length; i++){
  63. let button = document.createElement("button");
  64. button.innerText = merchant.recipes[i].name;
  65. button.classList.add("choosable");
  66. button.onclick = ()=>{
  67. this.recipe = merchant.recipes[i];
  68. this.displayRecipe();
  69. };
  70. recipeButtons.appendChild(button);
  71. }
  72. },
  73. getData: function(from, to){
  74. let data = {
  75. from: from,
  76. to: to,
  77. recipes: []
  78. }
  79. let loader = document.getElementById("loaderContainer");
  80. loader.style.display = "flex";
  81. return fetch("/transaction", {
  82. method: "post",
  83. headers: {
  84. "Content-Type": "application/json"
  85. },
  86. body: JSON.stringify(data)
  87. })
  88. .then(response => response.json())
  89. .then((response)=>{
  90. if(typeof(response) === "string"){
  91. controller.createBanner(response, "error");
  92. }else{
  93. this.transactionsByDate = [];
  94. response.reverse();
  95. let startOfDay = new Date(from.getTime());
  96. startOfDay.setHours(0, 0, 0, 0);
  97. let endOfDay = new Date(from.getTime());
  98. endOfDay.setDate(endOfDay.getDate() + 1);
  99. endOfDay.setHours(0, 0, 0, 0);
  100. let transactionIndex = 0;
  101. while(startOfDay <= to){
  102. let currentTransactions = [];
  103. while(transactionIndex < response.length && new Date(response[transactionIndex].date) < endOfDay){
  104. currentTransactions.push(new Transaction(
  105. response[transactionIndex]._id,
  106. response[transactionIndex].date,
  107. response[transactionIndex].recipes,
  108. merchant
  109. ));
  110. transactionIndex++;
  111. }
  112. let thing = {
  113. date: new Date(startOfDay.getTime()),
  114. transactions: currentTransactions
  115. };
  116. this.transactionsByDate.push(thing);
  117. startOfDay.setDate(startOfDay.getDate() + 1);
  118. endOfDay.setDate(endOfDay.getDate() + 1);
  119. }
  120. }
  121. })
  122. .catch((err)=>{
  123. controller.createBanner("UNABLE TO UPDATE THE PAGE", "error");
  124. })
  125. .finally(()=>{
  126. loader.style.display = "none";
  127. });
  128. },
  129. displayIngredient: function(){
  130. if(this.ingredient === undefined || this.transactionsByDate.length === 0) return;
  131. //break down data into dates and quantities
  132. let dates = [];
  133. let quantities = [];
  134. for(let i = 0; i < this.transactionsByDate.length; i++){
  135. dates.push(this.transactionsByDate[i].date);
  136. let sum = 0;
  137. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  138. let transaction = this.transactionsByDate[i].transactions[j];
  139. sum += transaction.getIngredientQuantity(this.ingredient);
  140. }
  141. quantities.push(sum);
  142. }
  143. //create and display the graph
  144. let trace = {
  145. x: dates,
  146. y: quantities,
  147. mode: "lines+markers",
  148. line: {
  149. color: "rgb(255, 99, 107)"
  150. }
  151. }
  152. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  153. const layout = {
  154. title: this.ingredient.name.toUpperCase(),
  155. xaxis: {title: "DATE"},
  156. yaxis: {title: yaxis},
  157. margin: {
  158. l: 40,
  159. r: 10,
  160. b: 20,
  161. t: 30
  162. },
  163. paper_bgcolor: "rgba(0, 0, 0, 0)"
  164. }
  165. Plotly.newPlot("itemUseGraph", [trace], layout);
  166. //Create min/max/avg
  167. //Current ingredient is stored on the "analMinUse" element
  168. let min = quantities[0];
  169. let max = quantities[0];
  170. let sum = 0;
  171. for(let i = 0; i < quantities.length; i++){
  172. if(quantities[i] < min){
  173. min = quantities[i];
  174. }
  175. if(quantities[i] > max){
  176. max = quantities[i];
  177. }
  178. sum += quantities[i];
  179. }
  180. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  181. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  182. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  183. //Create weekday averages
  184. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  185. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  186. for(let i = 0; i < quantities.length; i++){
  187. dayUse[dates[i].getDay()] += quantities[i];
  188. dayCount[dates[i].getDay()]++;
  189. }
  190. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  191. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  192. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  193. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  194. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  195. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  196. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  197. },
  198. displayCategory: function(){
  199. },
  200. displayRecipe: function(){
  201. if(this.recipe === undefined || this.transactionsByDate.length === 0) return;
  202. //break down data into dates and quantities
  203. let dates = [];
  204. let quantities = [];
  205. for(let i = 0; i < this.transactionsByDate.length; i++){
  206. dates.push(this.transactionsByDate[i].date);
  207. let sum = 0;
  208. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  209. const transaction = this.transactionsByDate[i].transactions[j];
  210. for(let k = 0; k < transaction.recipes.length; k++){
  211. if(transaction.recipes[k].recipe === this.recipe){
  212. sum += transaction.recipes[k].quantity;
  213. }
  214. }
  215. }
  216. quantities.push(sum);
  217. }
  218. //create and display the graph
  219. const trace = {
  220. x: dates,
  221. y: quantities,
  222. mode: "lines+markers",
  223. line: {
  224. color: "rgb(255, 99, 107)"
  225. }
  226. }
  227. const layout = {
  228. title: this.recipe.name.toUpperCase(),
  229. xaxis: {title: "DATE"},
  230. yaxis: {title: "QUANTITY"},
  231. margin: {
  232. l: 40,
  233. r: 10,
  234. b: 20,
  235. t: 30
  236. },
  237. paper_bgcolor: "rgba(0, 0, 0, 0)"
  238. }
  239. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  240. //Display the boxes at the bottom
  241. //Current recipe is stored on the "recipeAvgUse" element
  242. let avg = 0;
  243. for(let i = 0; i < quantities.length; i++){
  244. avg += quantities[i];
  245. }
  246. avg = avg / quantities.length;
  247. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  248. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  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. let analTabs = document.getElementById("analTabs");
  258. for(let i = 0; i < analTabs.children.length; i++){
  259. if(analTabs.children[i].classList.contains("active")){
  260. switch(analTabs.children[i].innerText.toLowerCase()){
  261. case "ingredients":
  262. this.displayIngredient();
  263. break;
  264. case "categories":
  265. this.displayCategory();
  266. break;
  267. case "recipes":
  268. this.displayRecipe();
  269. break;
  270. }
  271. }
  272. }
  273. },
  274. tab: function(tab){
  275. let analTabs = document.getElementById("analTabs");
  276. let ingredientContent = document.getElementById("analIngredientContent");
  277. let categoryContent = document.getElementById("analCategoryContent");
  278. let recipeContent = document.getElementById("analRecipeContent");
  279. for(let i = 0; i < analTabs.children.length; i++){
  280. analTabs.children[i].classList.remove("active");
  281. }
  282. tab.classList.add("active");
  283. ingredientContent.style.display = "none";
  284. categoryContent.style.display = "none";
  285. recipeContent.style.display = "none";
  286. switch(tab.innerText.toLowerCase()){
  287. case "ingredients":
  288. this.displayIngredient();
  289. ingredientContent.style.display = "flex";
  290. break;
  291. case "categories":
  292. this.displayCategory();
  293. categoryContent.style.display = "flex";
  294. break;
  295. case "recipes":
  296. recipeContent.style.display = "flex";
  297. this.displayRecipe();
  298. break;
  299. }
  300. }
  301. }
  302. module.exports = analytics;