analytics.js 16 KB

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