squareData.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. const Merchant = require("../models/merchant.js");
  2. const Recipe = require("../models/recipe.js");
  3. const axios = require("axios");
  4. const helper = require("./helper.js");
  5. module.exports = {
  6. //GET - Redirects user to Square OAuth page
  7. redirect: function(req, res){
  8. return res.redirect(`${process.env.SQUARE_ADDRESS}/oauth2/authorize?client_id=${process.env.SUBLINE_SQUARE_APPID}&scope=INVENTORY_READ+ITEMS_READ+MERCHANT_PROFILE_READ+ORDERS_READ+PAYMENTS_READ`);
  9. },
  10. //GET: Used by square. This route is used for the authentication code
  11. //Redirects to either dashboard or new merchant creation
  12. authorize: function(req, res){
  13. const code = req.url.slice(req.url.indexOf("code=") + 5, req.url.indexOf("&"));
  14. const url = `${process.env.SQUARE_ADDRESS}/oauth2/token`;
  15. let data = {
  16. client_id: process.env.SUBLINE_SQUARE_APPID,
  17. client_secret: process.env.SUBLINE_SQUARE_APPSECRET,
  18. grant_type: "authorization_code",
  19. code: code
  20. };
  21. axios.post(url, data)
  22. .then((response)=>{
  23. data = response.data;
  24. return Merchant.findOne({posId: data.merchant_id});
  25. })
  26. .then((merchant)=>{
  27. if(merchant){
  28. merchant.posAccessToken = data.access_token;
  29. return merchant.save()
  30. .then((merchant)=>{
  31. req.session.user = merchant.session.sessionId;
  32. return res.redirect("/dashboard");
  33. })
  34. .catch((err)=>{
  35. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  36. return res.redirect("/");
  37. })
  38. }else{
  39. req.session.merchantId = data.merchant_id;
  40. req.session.accessToken = data.access_token;
  41. return res.redirect("/merchant/create/square");
  42. }
  43. })
  44. .catch((err)=>{
  45. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM SQUARE";
  46. return res.redirect("/");
  47. });
  48. },
  49. //GET: Gathers all data from square to create our merchant
  50. //Redirects to the dashboard
  51. createMerchant: function(req, res){
  52. let merchant = {}
  53. axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
  54. headers: {
  55. Authorization: `Bearer ${req.session.accessToken}`
  56. }
  57. })
  58. .then((response)=>{
  59. req.session.merchantId = undefined;
  60. let expirationDate = new Date();
  61. expirationDate.setDate(expirationDate.getDate() + 90);
  62. merchant = new Merchant({
  63. name: response.data.merchant.business_name,
  64. pos: "square",
  65. posId: response.data.merchant.id,
  66. posAccessToken: req.session.accessToken,
  67. lastUpdatedTime: new Date(),
  68. createdAt: new Date(),
  69. squareLocation: response.data.merchant.main_location_id,
  70. status: [],
  71. inventory: [],
  72. recipes: [],
  73. session: {
  74. sessionId: helper.generateId(25),
  75. expiration: expirationDate
  76. }
  77. });
  78. req.session.accessToken = undefined;
  79. let items = axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  80. object_types: ["ITEM"]
  81. }, {
  82. headers: {
  83. Authorization: `Bearer ${merchant.posAccessToken}`
  84. }
  85. });
  86. let location = axios.get(`${process.env.SQUARE_ADDRESS}/v2/locations/${response.data.merchant.main_location_id}`, {
  87. headers: {
  88. Authorization: `Bearer ${merchant.posAccessToken}`
  89. }
  90. });
  91. return Promise.all([items, location]);
  92. })
  93. .then((response)=>{
  94. merchant.email = response[1].data.location.business_email;
  95. let recipes = [];
  96. for(let i = 0; i < response[0].data.objects.length; i++){
  97. if(response[0].data.objects[i].item_data.variations.length > 1){
  98. for(let j = 0; j < response[0].data.objects[i].item_data.variations.length; j++){
  99. let recipe = new Recipe({
  100. posId: response[0].data.objects[i].item_data.variations[j].id,
  101. merchant: merchant._id,
  102. name: `${response[0].data.objects[i].item_data.name} '${response[0].data.objects[i].item_data.variations[j].item_variation_data.name}'`,
  103. price: response[0].data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
  104. });
  105. recipes.push(recipe);
  106. merchant.recipes.push(recipe);
  107. }
  108. }else{
  109. let recipe = new Recipe({
  110. posId: response[0].data.objects[i].item_data.variations[0].id,
  111. merchant: merchant._id,
  112. name: response[0].data.objects[i].item_data.name,
  113. price: response[0].data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
  114. ingredients: []
  115. });
  116. recipes.push(recipe);
  117. merchant.recipes.push(recipe);
  118. }
  119. }
  120. return Promise.all([Recipe.create(recipes), merchant.save()]);
  121. })
  122. .then((response)=>{
  123. req.session.user = response[1].session.sessionId;
  124. return res.redirect("/dashboard");
  125. })
  126. .catch((err)=>{
  127. if(typeof(err) === "string"){
  128. req.session.error = err;
  129. }else if(err.name === "ValidationError"){
  130. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  131. }else{
  132. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  133. }
  134. return res.redirect("/");
  135. });
  136. },
  137. }