renderer.js 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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. 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(
  50. {_id: req.session.user},
  51. {
  52. name: 1,
  53. pos: 1,
  54. posId: 1,
  55. posAccessToken: 1,
  56. lastUpdatedTime: 1,
  57. inventory: 1,
  58. recipes: 1
  59. }
  60. )
  61. .populate("inventory.ingredient")
  62. .populate("recipes")
  63. .then(async (merchant)=>{
  64. console.log("merchant found");
  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 ber 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. console.log("response after clover stuff");
  148. let date = new Date();
  149. let firstDay = new Date(date.getFullYear(), date.getMonth() - 1, 1);
  150. Transaction.aggregate([
  151. {$match: {
  152. merchant: new ObjectId(req.session.user),
  153. date: {$gte: firstDay},
  154. }},
  155. {$sort: {date: 1}},
  156. {$project: {
  157. date: 1,
  158. recipes: 1
  159. }}
  160. ])
  161. .then((transactions)=>{
  162. console.log("found all transactions");
  163. response[0]._id = undefined;
  164. response[0].posAccessToken = undefined;
  165. response[0].lastUpdatedTime = undefined;
  166. response[0].accountStatus = undefined;
  167. return res.render("dashboardPage/dashboard", {merchant: response[0], transactions: transactions});
  168. })
  169. .catch((err)=>{console.log(err)});
  170. })
  171. .catch((err)=>{
  172. console.log(err);
  173. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  174. return res.redirect("/");
  175. });
  176. },
  177. //GET - Renders the information page
  178. displayLegal: function(req, res){
  179. return res.render("informationPage/information");
  180. },
  181. //GET - Renders the page to reset your password
  182. displayPassReset: function(req, res){
  183. return res.render("passResetPage/passReset");
  184. }
  185. }