analytics.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. const Transaction = require("../classes/Transaction.js");
  2. let analytics = {
  3. isPopulated: false,
  4. ingredient: undefined,
  5. category: undefined,
  6. recipe: undefined,
  7. recipeCategory: undefined,
  8. transactionsByDate: [],
  9. display: function(){
  10. if(!this.isPopulated){
  11. let ingredientTab = document.getElementById("analIngredientsTab");
  12. let recipeTab = document.getElementById("analRecipesTab");
  13. let categoryTab = document.getElementById("analCategoriesTab");
  14. let individualTab = document.getElementById("analIndividualTab");
  15. ingredientTab.onclick = ()=>{this.tab(ingredientTab)};
  16. categoryTab.onclick = ()=>{this.tab(categoryTab)};
  17. recipeTab.onclick = ()=>{this.tab(recipeTab)};
  18. individualTab.onclick = ()=>{this.tab(individualTab)};
  19. let to = new Date();
  20. let from = new Date(to.getFullYear(), to.getMonth() - 1, to.getDate());
  21. document.getElementById("analStartDate").valueAsDate = from;
  22. document.getElementById("analEndDate").valueAsDate = to;
  23. document.getElementById("analDateBtn").onclick = ()=>{this.newDates()};
  24. this.populateButtons();
  25. if(merchant.inventory.length > 0) this.ingredient = merchant.inventory[0].ingredient;
  26. if(merchant.recipes.length > 0) this.recipe = merchant.recipes[0];
  27. this.newDates();
  28. this.isPopulated = true;
  29. }
  30. },
  31. populateButtons: function(){
  32. let ingredientButtons = document.getElementById("analIngredientList");
  33. let categoryButtons = document.getElementById("analCategoriesList");
  34. let recipeButtons = document.getElementById("analRecipeList");
  35. let recipeCategoryButtons = document.getElementById("analCatRecipeList");
  36. while(ingredientButtons.children.length > 0){
  37. ingredientButtons.removeChild(ingredientButtons.firstChild);
  38. }
  39. for(let i = 0; i < merchant.inventory.length; i++){
  40. let button = document.createElement("button");
  41. button.innerText = merchant.inventory[i].ingredient.name;
  42. button.classList.add("choosable");
  43. button.onclick = ()=>{
  44. this.ingredient = merchant.inventory[i].ingredient;
  45. this.displayIngredient();
  46. };
  47. ingredientButtons.appendChild(button);
  48. }
  49. while(categoryButtons.children.length > 0){
  50. categoryButtons.removeChild(categoryButtons.firstChild);
  51. }
  52. let categories = merchant.categorizeIngredients();
  53. for(let i = 0; i < categories.length; i++){
  54. let button = document.createElement("button");
  55. button.innerText = categories[i].name;
  56. button.classList.add("choosable");
  57. button.onclick = ()=>{
  58. this.category = categories[i];
  59. this.displayIngredientCategory();
  60. }
  61. categoryButtons.appendChild(button);
  62. }
  63. while(recipeButtons.children.length > 0){
  64. recipeButtons.removeChild(recipeButtons.firstChild);
  65. }
  66. for(let i = 0; i < merchant.recipes.length; i++){
  67. let button = document.createElement("button");
  68. button.innerText = merchant.recipes[i].name;
  69. button.classList.add("choosable");
  70. button.onclick = ()=>{
  71. this.recipe = merchant.recipes[i];
  72. this.displayRecipe();
  73. };
  74. recipeButtons.appendChild(button);
  75. }
  76. while(recipeCategoryButtons.children.length > 0){
  77. recipeCategoryButtons.removeChild(recipeCategoryButtons.firstChild);
  78. }
  79. let recipeCategories = merchant.categorizeRecipes();
  80. for(let i = 0; i < recipeCategories.length; i++){
  81. let button = document.createElement("button");
  82. button.innerText = (recipeCategories[i].name === "") ? "UNCATEGORIZED" : recipeCategories[i].name;
  83. button.classList.add("choosable");
  84. button.onclick = ()=>{
  85. this.recipeCategory = recipeCategories[i];
  86. this.displayRecipeCategory();
  87. }
  88. recipeCategoryButtons.appendChild(button);
  89. }
  90. },
  91. getData: function(from, to){
  92. let data = {
  93. from: from,
  94. to: to,
  95. recipes: []
  96. }
  97. let loader = document.getElementById("loaderContainer");
  98. loader.style.display = "flex";
  99. return fetch("/transaction", {
  100. method: "post",
  101. headers: {
  102. "Content-Type": "application/json"
  103. },
  104. body: JSON.stringify(data)
  105. })
  106. .then(response => response.json())
  107. .then((response)=>{
  108. if(typeof(response) === "string"){
  109. controller.createBanner(response, "error");
  110. }else{
  111. this.transactionsByDate = [];
  112. response.reverse();
  113. let startOfDay = new Date(from.getTime());
  114. startOfDay.setHours(0, 0, 0, 0);
  115. let endOfDay = new Date(from.getTime());
  116. endOfDay.setDate(endOfDay.getDate() + 1);
  117. endOfDay.setHours(0, 0, 0, 0);
  118. let transactionIndex = 0;
  119. while(startOfDay <= to){
  120. let currentTransactions = [];
  121. while(transactionIndex < response.length && new Date(response[transactionIndex].date) < endOfDay){
  122. currentTransactions.push(new Transaction(
  123. response[transactionIndex]._id,
  124. response[transactionIndex].date,
  125. response[transactionIndex].recipes,
  126. merchant
  127. ));
  128. transactionIndex++;
  129. }
  130. let thing = {
  131. date: new Date(startOfDay.getTime()),
  132. transactions: currentTransactions
  133. };
  134. this.transactionsByDate.push(thing);
  135. startOfDay.setDate(startOfDay.getDate() + 1);
  136. endOfDay.setDate(endOfDay.getDate() + 1);
  137. }
  138. }
  139. })
  140. .catch((err)=>{
  141. controller.createBanner("UNABLE TO UPDATE THE PAGE", "error");
  142. })
  143. .finally(()=>{
  144. loader.style.display = "none";
  145. });
  146. },
  147. displayIngredient: function(){
  148. if(this.ingredient === undefined || this.transactionsByDate.length === 0) return;
  149. //break down data into dates and quantities
  150. let dates = [];
  151. let quantities = [];
  152. for(let i = 0; i < this.transactionsByDate.length; i++){
  153. dates.push(this.transactionsByDate[i].date);
  154. let sum = 0;
  155. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  156. let transaction = this.transactionsByDate[i].transactions[j];
  157. sum += transaction.getIngredientQuantity(this.ingredient);
  158. }
  159. quantities.push(sum);
  160. }
  161. //create and display the graph
  162. let trace = {
  163. x: dates,
  164. y: quantities,
  165. mode: "lines+markers",
  166. line: {
  167. color: "rgb(255, 99, 107)"
  168. }
  169. }
  170. let yaxis = `QUANTITY (${this.ingredient.unit.toUpperCase()})`;
  171. let layout = {
  172. title: this.ingredient.name.toUpperCase(),
  173. xaxis: {title: "DATE"},
  174. yaxis: {title: yaxis},
  175. margin: {
  176. l: 40,
  177. r: 10,
  178. b: 20,
  179. t: 30
  180. },
  181. paper_bgcolor: "rgba(0, 0, 0, 0)"
  182. }
  183. Plotly.newPlot("itemUseGraph", [trace], layout);
  184. //Create min/max/avg
  185. //Current ingredient is stored on the "analMinUse" element
  186. let min = quantities[0];
  187. let max = quantities[0];
  188. let sum = 0;
  189. for(let i = 0; i < quantities.length; i++){
  190. if(quantities[i] < min) min = quantities[i];
  191. if(quantities[i] > max) max = quantities[i];
  192. sum += quantities[i];
  193. }
  194. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  195. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  196. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  197. //Create weekday averages
  198. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  199. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  200. for(let i = 0; i < quantities.length; i++){
  201. dayUse[dates[i].getDay()] += quantities[i];
  202. dayCount[dates[i].getDay()]++;
  203. }
  204. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  205. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  206. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  207. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  208. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  209. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  210. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${this.ingredient.unit.toUpperCase()}`;
  211. },
  212. displayIngredientCategory: function(){
  213. if(this.category === undefined) this.category = merchant.categorizeIngredients()[0];
  214. if(this.category === undefined) return;
  215. let dates = [];
  216. let quantities = [];
  217. for(let i = 0; i < this.transactionsByDate.length; i++){
  218. dates.push(this.transactionsByDate[i].date);
  219. let total = 0;
  220. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  221. let transaction = this.transactionsByDate[i].transactions[j];
  222. for(let k = 0; k < this.category.ingredients.length; k++){
  223. total += transaction.getIngredientQuantity(this.category.ingredients[k].ingredient);
  224. }
  225. }
  226. quantities.push(total);
  227. }
  228. let trace = {
  229. x: dates,
  230. y: quantities,
  231. mode: "lines+markers",
  232. line: {
  233. color: "rgb(255, 99, 107)"
  234. }
  235. };
  236. let layout = {
  237. title: this.category.name,
  238. xaxis: {title: "DATE"},
  239. yaxis: {title: "COST ($)"},
  240. margin: {
  241. l: 40,
  242. r: 10,
  243. b: 20,
  244. t: 30
  245. },
  246. paper_bgcolor: "white"
  247. }
  248. Plotly.newPlot("analCategoriesGraph", [trace], layout);
  249. },
  250. displayRecipe: function(){
  251. if(this.recipe === undefined || this.transactionsByDate.length === 0) return;
  252. //break down data into dates and quantities
  253. let dates = [];
  254. let quantities = [];
  255. for(let i = 0; i < this.transactionsByDate.length; i++){
  256. dates.push(this.transactionsByDate[i].date);
  257. let sum = 0;
  258. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  259. const transaction = this.transactionsByDate[i].transactions[j];
  260. for(let k = 0; k < transaction.recipes.length; k++){
  261. if(transaction.recipes[k].recipe === this.recipe){
  262. sum += transaction.recipes[k].quantity;
  263. }
  264. }
  265. }
  266. quantities.push(sum);
  267. }
  268. //create and display the graph
  269. const trace = {
  270. x: dates,
  271. y: quantities,
  272. mode: "lines+markers",
  273. line: {
  274. color: "rgb(255, 99, 107)"
  275. }
  276. }
  277. const layout = {
  278. title: this.recipe.name.toUpperCase(),
  279. xaxis: {title: "DATE"},
  280. yaxis: {title: "QUANTITY"},
  281. margin: {
  282. l: 40,
  283. r: 10,
  284. b: 20,
  285. t: 30
  286. },
  287. paper_bgcolor: "rgba(0, 0, 0, 0)"
  288. }
  289. Plotly.newPlot("recipeSalesGraph", [trace], layout);
  290. //Display the boxes at the bottom
  291. //Current recipe is stored on the "recipeAvgUse" element
  292. let avg = 0;
  293. for(let i = 0; i < quantities.length; i++){
  294. avg += quantities[i];
  295. }
  296. avg = avg / quantities.length;
  297. document.getElementById("recipeAvgUse").innerText = avg.toFixed(2);
  298. document.getElementById("recipeAvgRevenue").innerText = `$${(avg * this.recipe.price).toFixed(2)}`;
  299. },
  300. displayRecipeCategory: function(){
  301. if(this.recipeCategory === undefined) this.recipeCategory = merchant.categorizeRecipes()[0];
  302. let dates = [];
  303. let quantities = [];
  304. for(let i = 0; i < this.transactionsByDate.length; i++){
  305. dates.push(this.transactionsByDate[i].date);
  306. let total = 0;
  307. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  308. for(let k = 0; k < this.recipeCategory.recipes.length; k++){
  309. total += this.transactionsByDate[i].transactions[j].getRecipeQuantity(this.recipeCategory.recipes[k]);
  310. }
  311. }
  312. quantities.push(total);
  313. }
  314. let trace = {
  315. x: dates,
  316. y: quantities,
  317. mode: "lines+markers",
  318. line: {
  319. color: "rgb(255, 99, 107)"
  320. }
  321. };
  322. let layout = {
  323. title: (this.recipeCategory.name === "") ? "UNCATEGORIZED" : this.recipeCategory.name,
  324. xaxis: {title: "DATE"},
  325. yaxis: {title: "COST ($)"},
  326. margin: {
  327. l: 40,
  328. r: 10,
  329. b: 20,
  330. t: 30
  331. },
  332. paper_bgcolor: "white"
  333. };
  334. Plotly.newPlot("analCatRecipeGraph", [trace], layout);
  335. },
  336. newDates: async function(){
  337. const from = document.getElementById("analStartDate").valueAsDate;
  338. const to = document.getElementById("analEndDate").valueAsDate;
  339. from.setHours(0, 0, 0, 0);
  340. to.setDate(to.getDate() + 1);
  341. to.setHours(0, 0, 0, 0);
  342. await this.getData(from, to);
  343. let analTabs = document.getElementById("analTabs");
  344. for(let i = 0; i < analTabs.children.length; i++){
  345. if(analTabs.children[i].classList.contains("active")){
  346. switch(analTabs.children[i].innerText.toLowerCase()){
  347. case "ingredients":
  348. this.displayIngredient();
  349. break;
  350. case "categories":
  351. this.displayIngredientCategory();
  352. break;
  353. case "recipes":
  354. this.displayRecipe();
  355. break;
  356. }
  357. }
  358. }
  359. },
  360. tab: function(tab){
  361. let upperGroup = document.getElementById("topAnalTabs");
  362. let lowerGroup = document.getElementById("bottomAnalTabs");
  363. let strand = document.getElementById("analyticsStrand");
  364. for(let i = 0; i < tab.parentElement.children.length; i++){
  365. tab.parentElement.children[i].classList.remove("active");
  366. }
  367. tab.classList.add("active");
  368. for(let i = 1; i < strand.children.length; i++){
  369. strand.children[i].style.display = "none";
  370. }
  371. if(upperGroup.children[0].classList.contains("active")){
  372. if(lowerGroup.children[0].classList.contains("active")){
  373. document.getElementById("analIndividualIngredient").style.display = "flex";
  374. this.displayIngredient();
  375. }else{
  376. document.getElementById("analCategoryIngredient").style.display = "flex";
  377. this.displayIngredientCategory();
  378. }
  379. }else{
  380. if(lowerGroup.children[0].classList.contains("active")){
  381. document.getElementById("analIndividualRecipe").style.display = "flex";
  382. this.displayRecipe();
  383. }else{
  384. document.getElementById("analCategoryRecipe").style.display = "flex";
  385. this.displayRecipeCategory();
  386. }
  387. }
  388. }
  389. }
  390. module.exports = analytics;