analytics.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  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. let 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) min = quantities[i];
  173. if(quantities[i] > max) max = quantities[i];
  174. sum += quantities[i];
  175. }
  176. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  177. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  178. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  179. //Create weekday averages
  180. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  181. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  182. for(let i = 0; i < quantities.length; i++){
  183. dayUse[dates[i].getDay()] += quantities[i];
  184. dayCount[dates[i].getDay()]++;
  185. }
  186. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  187. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  188. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  189. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  190. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  191. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  192. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  193. },
  194. displayCategory: function(){
  195. if(this.category === undefined) this.category = merchant.categorizeIngredients()[0];
  196. let dates = [];
  197. let quantities = [];
  198. for(let i = 0; i < this.transactionsByDate.length; i++){
  199. dates.push(this.transactionsByDate[i].date);
  200. let total = 0;
  201. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  202. let transaction = this.transactionsByDate[i].transactions[j];
  203. for(let k = 0; k < this.category.ingredients.length; k++){
  204. total += transaction.getIngredientQuantity(this.category.ingredients[k].ingredient);
  205. }
  206. }
  207. quantities.push(total);
  208. }
  209. let trace = {
  210. x: dates,
  211. y: quantities,
  212. mode: "lines+markers",
  213. line: {
  214. color: "rgb(255, 99, 107)"
  215. }
  216. };
  217. let layout = {
  218. title: this.category.name,
  219. xaxis: {title: "DATE"},
  220. yaxis: {title: "COST ($)"},
  221. margin: {
  222. l: 40,
  223. r: 10,
  224. b: 20,
  225. t: 30
  226. },
  227. paper_bgcolor: "white"
  228. }
  229. Plotly.newPlot("analCategoriesGraph", [trace], layout);
  230. },
  231. displayRecipe: function(){
  232. if(this.recipe === undefined || this.transactionsByDate.length === 0) return;
  233. //break down data into dates and quantities
  234. let dates = [];
  235. let quantities = [];
  236. for(let i = 0; i < this.transactionsByDate.length; i++){
  237. dates.push(this.transactionsByDate[i].date);
  238. let sum = 0;
  239. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  240. const transaction = this.transactionsByDate[i].transactions[j];
  241. for(let k = 0; k < transaction.recipes.length; k++){
  242. if(transaction.recipes[k].recipe === this.recipe){
  243. sum += transaction.recipes[k].quantity;
  244. }
  245. }
  246. }
  247. quantities.push(sum);
  248. }
  249. //create and display the graph
  250. const trace = {
  251. x: dates,
  252. y: quantities,
  253. mode: "lines+markers",
  254. line: {
  255. color: "rgb(255, 99, 107)"
  256. }
  257. }
  258. const layout = {
  259. title: this.recipe.name.toUpperCase(),
  260. xaxis: {title: "DATE"},
  261. yaxis: {title: "QUANTITY"},
  262. margin: {
  263. l: 40,
  264. r: 10,
  265. b: 20,
  266. t: 30
  267. },
  268. paper_bgcolor: "rgba(0, 0, 0, 0)"
  269. }
  270. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  271. //Display the boxes at the bottom
  272. //Current recipe is stored on the "recipeAvgUse" element
  273. let avg = 0;
  274. for(let i = 0; i < quantities.length; i++){
  275. avg += quantities[i];
  276. }
  277. avg = avg / quantities.length;
  278. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  279. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  280. },
  281. newDates: async function(){
  282. const from = document.getElementById("analStartDate").valueAsDate;
  283. const to = document.getElementById("analEndDate").valueAsDate;
  284. from.setHours(0, 0, 0, 0);
  285. to.setDate(to.getDate() + 1);
  286. to.setHours(0, 0, 0, 0);
  287. await this.getData(from, to);
  288. let analTabs = document.getElementById("analTabs");
  289. for(let i = 0; i < analTabs.children.length; i++){
  290. if(analTabs.children[i].classList.contains("active")){
  291. switch(analTabs.children[i].innerText.toLowerCase()){
  292. case "ingredients":
  293. this.displayIngredient();
  294. break;
  295. case "categories":
  296. this.displayCategory();
  297. break;
  298. case "recipes":
  299. this.displayRecipe();
  300. break;
  301. }
  302. }
  303. }
  304. },
  305. tab: function(tab){
  306. let analTabs = document.getElementById("analTabs");
  307. let ingredientContent = document.getElementById("analIngredientContent");
  308. let categoryContent = document.getElementById("analCategoryContent");
  309. let recipeContent = document.getElementById("analRecipeContent");
  310. for(let i = 0; i < analTabs.children.length; i++){
  311. analTabs.children[i].classList.remove("active");
  312. }
  313. tab.classList.add("active");
  314. ingredientContent.style.display = "none";
  315. categoryContent.style.display = "none";
  316. recipeContent.style.display = "none";
  317. switch(tab.innerText.toLowerCase()){
  318. case "ingredients":
  319. ingredientContent.style.display = "flex";
  320. this.displayIngredient();
  321. break;
  322. case "categories":
  323. categoryContent.style.display = "flex";
  324. this.displayCategory();
  325. break;
  326. case "recipes":
  327. recipeContent.style.display = "flex";
  328. this.displayRecipe();
  329. break;
  330. }
  331. }
  332. }
  333. module.exports = analytics;