analytics.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  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, true);
  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 unit = (this.ingredient.unit === "bottle") ? this.ingredient.altUnit : this.ingredient.unit;
  171. let yaxis = `QUANTITY (${unit.toUpperCase()})`;
  172. let layout = {
  173. title: this.ingredient.name.toUpperCase(),
  174. xaxis: {title: "DATE"},
  175. yaxis: {title: yaxis},
  176. margin: {
  177. l: 40,
  178. r: 10,
  179. b: 20,
  180. t: 30
  181. },
  182. paper_bgcolor: "rgba(0, 0, 0, 0)"
  183. }
  184. Plotly.newPlot("itemUseGraph", [trace], layout);
  185. //Create min/max/avg
  186. //Current ingredient is stored on the "analMinUse" element
  187. let min = quantities[0];
  188. let max = quantities[0];
  189. let sum = 0;
  190. for(let i = 0; i < quantities.length; i++){
  191. if(quantities[i] < min) min = quantities[i];
  192. if(quantities[i] > max) max = quantities[i];
  193. sum += quantities[i];
  194. }
  195. document.getElementById("analMinUse").innerText = `${min.toFixed(2)} ${unit.toUpperCase()}`;
  196. document.getElementById("analAvgUse").innerText = `${(sum / quantities.length).toFixed(2)} ${unit.toUpperCase()}`;
  197. document.getElementById("analMaxUse").innerText = `${max.toFixed(2)} ${unit.toUpperCase()}`;
  198. //Create weekday averages
  199. let dayUse = [0, 0, 0, 0, 0, 0, 0];
  200. let dayCount = [0, 0, 0, 0, 0, 0, 0];
  201. for(let i = 0; i < quantities.length; i++){
  202. dayUse[dates[i].getDay()] += quantities[i];
  203. dayCount[dates[i].getDay()]++;
  204. }
  205. document.getElementById("analDayOne").innerText = `${(dayUse[0] / dayCount[0]).toFixed(2)} ${unit.toUpperCase()}`;
  206. document.getElementById("analDayTwo").innerText = `${(dayUse[1] / dayCount[1]).toFixed(2)} ${unit.toUpperCase()}`;
  207. document.getElementById("analDayThree").innerText = `${(dayUse[2] / dayCount[2]).toFixed(2)} ${unit.toUpperCase()}`;
  208. document.getElementById("analDayFour").innerText = `${(dayUse[3] / dayCount[3]).toFixed(2)} ${unit.toUpperCase()}`;
  209. document.getElementById("analDayFive").innerText = `${(dayUse[4] / dayCount[4]).toFixed(2)} ${unit.toUpperCase()}`;
  210. document.getElementById("analDaySix").innerText = `${(dayUse[5] / dayCount[5]).toFixed(2)} ${unit.toUpperCase()}`;
  211. document.getElementById("analDaySeven").innerText = `${(dayUse[6] / dayCount[6]).toFixed(2)} ${unit.toUpperCase()}`;
  212. },
  213. displayIngredientCategory: function(){
  214. if(this.category === undefined) this.category = merchant.categorizeIngredients()[0];
  215. if(this.category === undefined) return;
  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, true);
  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. displayRecipeCategory: function(){
  302. if(this.recipeCategory === undefined) this.recipeCategory = merchant.categorizeRecipes()[0];
  303. let dates = [];
  304. let quantities = [];
  305. for(let i = 0; i < this.transactionsByDate.length; i++){
  306. dates.push(this.transactionsByDate[i].date);
  307. let total = 0;
  308. for(let j = 0; j < this.transactionsByDate[i].transactions.length; j++){
  309. for(let k = 0; k < this.recipeCategory.recipes.length; k++){
  310. total += this.transactionsByDate[i].transactions[j].getRecipeQuantity(this.recipeCategory.recipes[k]);
  311. }
  312. }
  313. quantities.push(total);
  314. }
  315. let trace = {
  316. x: dates,
  317. y: quantities,
  318. mode: "lines+markers",
  319. line: {
  320. color: "rgb(255, 99, 107)"
  321. }
  322. };
  323. let layout = {
  324. title: (this.recipeCategory.name === "") ? "UNCATEGORIZED" : this.recipeCategory.name,
  325. xaxis: {title: "DATE"},
  326. yaxis: {title: "COST ($)"},
  327. margin: {
  328. l: 40,
  329. r: 10,
  330. b: 20,
  331. t: 30
  332. },
  333. paper_bgcolor: "white"
  334. };
  335. Plotly.newPlot("analCatRecipeGraph", [trace], layout);
  336. },
  337. newDates: async function(){
  338. const from = document.getElementById("analStartDate").valueAsDate;
  339. const to = document.getElementById("analEndDate").valueAsDate;
  340. from.setHours(0, 0, 0, 0);
  341. to.setDate(to.getDate() + 1);
  342. to.setHours(0, 0, 0, 0);
  343. await this.getData(from, to);
  344. let analTabs = document.getElementById("analTabs");
  345. if(analTabs.children[0].children[0].classList.contains("active")){
  346. if(analTabs.children[1].children[0].classList.contains("active")){
  347. this.displayIngredient();
  348. }else{this.displayIngredientCategory()};
  349. }else{
  350. if(analTabs.children[1].children[0].classList.contains("active")){
  351. this.displayRecipe();
  352. }else{this.displayRecipeCategory()};
  353. }
  354. },
  355. tab: function(tab){
  356. let upperGroup = document.getElementById("topAnalTabs");
  357. let lowerGroup = document.getElementById("bottomAnalTabs");
  358. let strand = document.getElementById("analyticsStrand");
  359. for(let i = 0; i < tab.parentElement.children.length; i++){
  360. tab.parentElement.children[i].classList.remove("active");
  361. }
  362. tab.classList.add("active");
  363. for(let i = 1; i < strand.children.length; i++){
  364. strand.children[i].style.display = "none";
  365. }
  366. if(upperGroup.children[0].classList.contains("active")){
  367. if(lowerGroup.children[0].classList.contains("active")){
  368. document.getElementById("analIndividualIngredient").style.display = "flex";
  369. this.displayIngredient();
  370. }else{
  371. document.getElementById("analCategoryIngredient").style.display = "flex";
  372. this.displayIngredientCategory();
  373. }
  374. }else{
  375. if(lowerGroup.children[0].classList.contains("active")){
  376. document.getElementById("analIndividualRecipe").style.display = "flex";
  377. this.displayRecipe();
  378. }else{
  379. document.getElementById("analCategoryRecipe").style.display = "flex";
  380. this.displayRecipeCategory();
  381. }
  382. }
  383. }
  384. }
  385. module.exports = analytics;