renderer.js 9.1 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. const helper = require("./helper.js");
  7. module.exports = {
  8. /*
  9. GET - Shows the public landing page
  10. Return = a single error message (only if there is an error)
  11. Renders landingPage
  12. */
  13. landingPage: function(req, res){
  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. let activity = 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 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. }else if(merchant.pos === "square"){
  144. promiseArray = helper.getSquareData(merchant);
  145. }
  146. return Promise.all([merchant.save()].concat(promiseArray));
  147. })
  148. .then((response)=>{
  149. let date = new Date();
  150. let firstDay = new Date(date.getFullYear(), date.getMonth() - 1, 1);
  151. Transaction.aggregate([
  152. {$match: {
  153. merchant: new ObjectId(req.session.user),
  154. date: {$gte: firstDay},
  155. }},
  156. {$sort: {date: 1}},
  157. {$project: {
  158. date: 1,
  159. recipes: 1
  160. }}
  161. ])
  162. .then((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)=>{});
  170. })
  171. .catch((err)=>{
  172. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  173. return res.redirect("/");
  174. });
  175. },
  176. //GET - Renders the information page
  177. displayLegal: function(req, res){
  178. return res.render("informationPage/information");
  179. },
  180. //GET - Renders the page to reset your password
  181. displayPassReset: function(req, res){
  182. return res.render("passResetPage/passReset");
  183. }
  184. }