analytics.js 15 KB

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