analytics.js 15 KB

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