renderer.js 9.0 KB

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