renderer.js 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. const axios = require("axios");
  2. const ObjectId = require("mongoose").Types.ObjectId;
  3. const Merchant = require("../models/merchant.js");
  4. const Transaction = require("../models/transaction.js");
  5. const Activity = require("../models/activity.js");
  6. module.exports = {
  7. /*
  8. GET - Shows the public landing page
  9. Return = a single error message (only if there is an error)
  10. Renders landingPage
  11. */
  12. landingPage: function(req, res){
  13. let activity = new Activity({
  14. ipAddr: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
  15. merchant: req.session.user,
  16. route: "landing",
  17. date: new Date()
  18. })
  19. .save()
  20. .catch(()=>{});
  21. let error = {};
  22. let isLoggedIn = req.session.isLoggedIn || false;
  23. if(req.session.error){
  24. error = req.session.error;
  25. req.session.error = undefined;
  26. }else{
  27. error = null;
  28. }
  29. return res.render("landingPage/landing", {error: error, isLoggedIn: isLoggedIn});
  30. },
  31. /*
  32. GET - Displays the main inventory page for merchants
  33. Returns = the logged in merchant and his/her data
  34. Renders inventoryPage
  35. */
  36. displayDashboard: function(req, res){
  37. if(!req.session.user){
  38. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  39. return res.redirect("/");
  40. }
  41. let activity = new Activity({
  42. ipAddr: req.headers['x-forwarded-for'] || req.connection.remoteAddress,
  43. merchant: req.session.user,
  44. route: "dashboard",
  45. date: new Date()
  46. })
  47. .save()
  48. .catch(()=>{});
  49. Merchant.findOne({_id: req.session.user}, {password: 0, createdAt: 0})
  50. .populate("inventory.ingredient")
  51. .populate("recipes")
  52. .then(async (merchant)=>{
  53. let promiseArray = [];
  54. if(merchant.pos === "clover"){
  55. const subscriptionCheck = axios.get(`${process.env.CLOVER_ADDRESS}/v3/apps/${process.env.SUBLINE_CLOVER_APPID}/merchants/${merchant.posId}/billing_info?access_token=${merchant.posAccessToken}`);
  56. const transactionRetrieval = axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${merchant.posId}/orders?filter=modifiedTime>=${merchant.lastUpdatedTime}&expand=lineItems&expand=payment&access_token=${merchant.posAccessToken}`);
  57. await Promise.all([subscriptionCheck, transactionRetrieval])
  58. .then(async (response)=>{
  59. if(response[0].data.status !== "ACTIVE"){
  60. req.session.error = "SUBSCRIPTION EXPIRED. PLEASE RENEW ON CLOVER";
  61. return res.redirect("/");
  62. }
  63. const updatedTime = Date.now();
  64. //Create Subline transactions from Clover Transactions
  65. let transactions = [];
  66. for(let i = 0; i < response[1].data.elements.length; i++){
  67. let order = response[1].data.elements[i];
  68. if(order.paymentState !== "PAID"){
  69. break;
  70. }
  71. let newTransaction = new Transaction({
  72. merchant: merchant._id,
  73. date: new Date(order.createdTime),
  74. device: order.device.id,
  75. posId: order.id
  76. });
  77. //Go through lineItems from Clover
  78. //Get the appropriate recipe from Subline
  79. //Add it to the transaction or increment if existing
  80. for(let j = 0; j < order.lineItems.elements.length; j++){
  81. let recipe = {}
  82. for(let k = 0; k < merchant.recipes.length; k++){
  83. if(merchant.recipes[k].posId === order.lineItems.elements[j].item.id){
  84. recipe = merchant.recipes[k];
  85. break;
  86. }
  87. }
  88. if(recipe){
  89. let isNewRecipe = true;
  90. for(let k = 0; k < newTransaction.recipes.length; k++){
  91. if(newTransaction.recipes[k].recipe === recipe._id){
  92. newTransaction.recipes[k].quantity++;
  93. isNewRecipe = false;
  94. break;
  95. }
  96. }
  97. if(isNewRecipe){
  98. newTransaction.recipes.push({
  99. recipe: recipe._id,
  100. quantity: 1
  101. });
  102. }
  103. //Subtract ingredients from merchants total for each ingredient in a recipe
  104. for(let k = 0; k < recipe.ingredients.length; k++){
  105. let inventoryIngredient = {};
  106. for(let l = 0; l < merchant.inventory.length; l++){
  107. if(merchant.inventory[l].ingredient._id.toString() === recipe.ingredients[k].ingredient._id.toString()){
  108. inventoryIngredient = merchant.inventory[l];
  109. break;
  110. }
  111. }
  112. inventoryIngredient.quantity = inventoryIngredient.quantity - ingredient.quantity;
  113. }
  114. }
  115. }
  116. transactions.push(newTransaction);
  117. }
  118. merchant.lastUpdatedTime = updatedTime;
  119. //Remove any existing orders so that they can ber replaced
  120. let ids = [];
  121. for(let i = 0; i < transactions.length; i++){
  122. ids.push(transactions[i].posId);
  123. }
  124. Transaction.deleteMany({posId: {$in: ids}});
  125. promiseArray.push(Transaction.create(transactions));
  126. })
  127. .catch((err)=>{
  128. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  129. return res.redirect("/");
  130. });
  131. }
  132. return Promise.all([merchant.save()].concat(promiseArray));
  133. })
  134. .then((response)=>{
  135. let date = new Date();
  136. let firstDay = new Date(date.getFullYear(), date.getMonth() - 1, 1);
  137. Transaction.aggregate([
  138. {$match: {
  139. merchant: new ObjectId(req.session.user),
  140. date: {$gte: firstDay},
  141. }},
  142. {$sort: {date: 1}},
  143. {$project: {
  144. date: 1,
  145. recipes: 1
  146. }}
  147. ])
  148. .then((transactions)=>{
  149. return res.render("dashboardPage/dashboard", {merchant: response[0], transactions: transactions});
  150. })
  151. .catch((err)=>{});
  152. })
  153. .catch((err)=>{
  154. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  155. return res.redirect("/");
  156. });
  157. },
  158. //GET - Renders the information page
  159. displayLegal: function(req, res){
  160. return res.render("informationPage/information");
  161. },
  162. //GET - Renders the page to reset your password
  163. displayPassReset: function(req, res){
  164. return res.render("passResetPage/passReset");
  165. }
  166. }