squareData.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. const Owner = require("../models/owner.js");
  2. const Merchant = require("../models/merchant.js");
  3. const Recipe = require("../models/recipe.js");
  4. const helper = require("./helper.js");
  5. const axios = require("axios");
  6. const bcrypt = require("bcryptjs");
  7. module.exports = {
  8. /*POST - Redirects user to Square OAuth and saves input data
  9. req.body = {
  10. name: String,
  11. email: String,
  12. password: String,
  13. confirmPassword: String
  14. }
  15. */
  16. redirect: async function(req, res){
  17. if(req.body.password !== req.body.confirmPassword){
  18. req.session.error = "YOUR PASSWORDS DO NOT MATCH";
  19. return res.redirect("/");
  20. }
  21. let email = req.body.email.toLowerCase();
  22. let potentialOwner = await Owner.findOne({email: email})
  23. if(potentialOwner !== null){
  24. req.session.error = "USER WITH THIS EMAIL ADDRESS ALREADY EXISTS";
  25. return res.redirect("/login");
  26. }
  27. let expirationDate = new Date();
  28. expirationDate.setDate(expirationDate.getDate() + 90);
  29. let salt = bcrypt.genSaltSync(10);
  30. let hash = bcrypt.hashSync(req.body.password, salt);
  31. let owner = new Owner({
  32. email: email,
  33. name: req.body.name,
  34. password: hash,
  35. square: {},
  36. createdAt: new Date(),
  37. status: ["unverified"],
  38. session: {
  39. sessionId: helper.generateId(25),
  40. expiration: expirationDate
  41. },
  42. merchants: []
  43. });
  44. let merchant = new Merchant({
  45. owner: owner._id,
  46. name: req.body.name,
  47. pos: "square",
  48. inventory: [],
  49. recipes: [],
  50. square: {},
  51. createdAt: new Date()
  52. });
  53. owner.merchants.push(merchant._id);
  54. Promise.all([owner.save(), merchant.save()])
  55. .then((response)=>{
  56. req.session.owner = response[0].session.sessionId;
  57. 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`);
  58. })
  59. .catch((err)=>{
  60. console.log(err);
  61. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  62. return res.redirect("/");
  63. });
  64. },
  65. //GET: Gathers all data from square to create our merchant
  66. //Redirects to the dashboard
  67. createMerchant: function(req, res){
  68. let code = req.url.slice(req.url.indexOf("code=") + 5, req.url.indexOf("&"));
  69. let url = `${process.env.SQUARE_ADDRESS}/oauth2/token`;
  70. let data = {
  71. client_id: process.env.SUBLINE_SQUARE_APPID,
  72. client_secret: process.env.SUBLINE_SQUARE_APPSECRET,
  73. grant_type: "authorization_code",
  74. code: code,
  75. }
  76. let merchant = {};
  77. let owner = Owner.findOne({"session.sessionId": req.session.owner}).populate("merchants");
  78. let squareMerchant = axios.post(url, data);
  79. Promise.all([owner, squareMerchant])
  80. .then((response)=>{
  81. if(response[0] === null) throw "ERROR: UNABLE TO CREATE ACCOUNT";
  82. owner = response[0];
  83. merchant = response[0].merchants[0];
  84. owner.square = {
  85. id: response[1].data.merchant_id,
  86. expires: new Date(response[1].data.expires_at),
  87. refreshToken: response[1].data.refresh_token,
  88. accessToken: response[1].data.access_token
  89. };
  90. return axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${owner.square.id}`, {
  91. headers: {Authorization: `Bearer ${owner.square.accessToken}`}
  92. });
  93. })
  94. .then((response)=>{
  95. merchant.locationId = response.data.merchant.main_location_id;
  96. owner.name = response.data.merchant.business_name;
  97. let items = axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  98. object_types: ["ITEM"]
  99. }, {
  100. headers: {
  101. Authorization: `Bearer ${owner.square.accessToken}`
  102. }
  103. });
  104. let location = axios.get(`${process.env.SQUARE_ADDRESS}/v2/locations/${merchant.locationId}`, {
  105. headers: {
  106. Authorization: `Bearer ${owner.square.accessToken}`
  107. }
  108. });
  109. return Promise.all([items, location]);
  110. })
  111. .then((response)=>{
  112. if(owner.email === response[1].data.location.business_email) merchant.status = [];
  113. merchant.name = response[1].data.location.name;
  114. let recipes = helper.createRecipesFromSquare(response[0].data.objects, merchant._id);
  115. merchant.recipes = recipes;
  116. return Promise.all([Recipe.create(recipes), owner.save(), merchant.save()]);
  117. })
  118. .then((response)=>{
  119. req.session.owner = response[1].session.sessionId;
  120. req.session.merchant = merchant._id;
  121. res.redirect("/dashboard");
  122. helper.getAllMerchantTransactions(merchant, owner.square.accessToken);
  123. })
  124. .catch((err)=>{
  125. if(typeof(err) === "string"){
  126. req.session.error = err;
  127. }else if(err.name === "ValidationError"){
  128. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  129. }else{
  130. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  131. }
  132. Merchant.deleteOne({_id: merchant._id});
  133. Owner.deleteOne({_id: owner._id});
  134. return res.redirect("/");
  135. });
  136. },
  137. updateRecipes: function(req, res){
  138. let merchantRecipes = [];
  139. let newRecipes = [];
  140. let populate = res.locals.merchant.populate("recipes").execPopulate();
  141. let squareRecipes = axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search-catalog-items`, {
  142. enabled_location_ids: [res.locals.merchant.locationId]
  143. }, {
  144. headers: {
  145. Authorization: `Bearer ${res.locals.owner.square.accessToken}`
  146. }
  147. });
  148. Promise.all([populate, squareRecipes])
  149. .then((response)=>{
  150. merchantRecipes = res.locals.merchant.recipes.slice();
  151. for(let i = 0; i < response[1].data.items.length; i++){
  152. let itemData = response[1].data.items[i].item_data;
  153. for(let j = 0; j < itemData.variations.length; j++){
  154. let isFound = false;
  155. for(let k = 0; k < merchantRecipes.length; k++){
  156. if(itemData.variations[j].id === merchantRecipes[k].posId){
  157. merchantRecipes.splice(k, 1);
  158. k--;
  159. isFound = true;
  160. break;
  161. }
  162. }
  163. if(!isFound){
  164. let priceMoney = itemData.variations[j].item_variation_data.price_money;
  165. let price = (priceMoney === undefined) ? 0 : priceMoney.amount;
  166. let newRecipe = new Recipe({
  167. posId: itemData.variations[j].id,
  168. merchant: res.locals.merchant._id,
  169. name: "",
  170. price: price,
  171. ingredients: []
  172. });
  173. if(itemData.variations.length > 1){
  174. newRecipe.name = `${itemData.name} '${itemData.variations[j].item_variation_data.name}'`;
  175. }else{
  176. newRecipe.name = itemData.name;
  177. }
  178. newRecipes.push(newRecipe);
  179. res.locals.merchant.recipes.push(newRecipe);
  180. }
  181. }
  182. }
  183. let ids = [];
  184. for(let i = 0; i < merchantRecipes.length; i++){
  185. ids.push(merchantRecipes[i]._id);
  186. for(let j = 0; j < res.locals.merchant.recipes.length; j++){
  187. if(merchantRecipes[i]._id.toString() === res.locals.merchant.recipes[j]._id.toString()){
  188. res.locals.merchant.recipes.splice(j, 1);
  189. j--;
  190. break;
  191. }
  192. }
  193. }
  194. if(newRecipes.length > 0) Recipe.create(newRecipes);
  195. if(merchantRecipes.length > 0) Recipe.deleteMany({_id: {$in: ids}});
  196. return res.locals.merchant.save();
  197. })
  198. .then((merchant)=>{
  199. return res.json({new: newRecipes, removed: merchantRecipes});
  200. })
  201. .catch((err)=>{
  202. if(typeof(err) === "string") return res.json(err);
  203. if(err.name === "ValidationError") return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  204. return res.json("ERROR: UNABLE TO RETRIEVE RECIPE DATA FROM SQUARE");
  205. });
  206. },
  207. /*
  208. GET: add another merchant to an owner with another square location
  209. response = [{
  210. name: String,
  211. id: String
  212. }]
  213. */
  214. getLocations: function(req, res){
  215. let ownerLocation = res.locals.owner.populate("merchants", "locationId").execPopulate();
  216. let locations = axios.get(`${process.env.SQUARE_ADDRESS}/v2/locations`, {
  217. headers: {
  218. "Authorization": `Bearer ${res.locals.owner.square.accessToken}`,
  219. "Content-Type": "application/json"
  220. }
  221. });
  222. Promise.all([ownerLocation, locations])
  223. .then((response)=>{
  224. let checkLocations = [];
  225. let locations = [];
  226. for(let i = 0; i < res.locals.owner.merchants.length; i++){
  227. checkLocations.push(res.locals.owner.merchants[i].locationId);
  228. }
  229. for(let i = 0; i < response[1].data.locations.length; i++){
  230. if(checkLocations.includes(response[1].data.locations[i].id) === false){
  231. locations.push({
  232. name: response[1].data.locations[i].name,
  233. id: response[1].data.locations[i].id
  234. });
  235. }
  236. }
  237. return res.json(locations);
  238. })
  239. .catch((err)=>{
  240. return res.json("ERROR: UNABLE TO RETRIEVE LOCATION DATA FROM SQUARE");
  241. });
  242. },
  243. /*
  244. GET: create new merchant from square location and add to owner
  245. req.params.location = location.id
  246. response = [Owner, Merchant]
  247. */
  248. addMerchant: function(req, res){
  249. let merchant = new Merchant({
  250. owner: res.locals.owner._id,
  251. pos: "square",
  252. locationId: req.params.location,
  253. createdAt: new Date(),
  254. inventory: [],
  255. recipes: []
  256. });
  257. res.locals.owner.merchants.push(merchant._id);
  258. let location = axios.get(`${process.env.SQUARE_ADDRESS}/v2/locations/${req.params.location}`, {
  259. headers: {
  260. "Authorization": `Bearer ${res.locals.owner.square.accessToken}`,
  261. "Content-Type": "application/json"
  262. }
  263. });
  264. let recipes = axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  265. object_types: ["ITEM"]
  266. }, {
  267. headers: {
  268. "Authorization": `Bearer ${res.locals.owner.square.accessToken}`,
  269. "Content-Type": "application/json"
  270. }
  271. });
  272. Promise.all([location, recipes])
  273. .then((response)=>{
  274. merchant.name = response[0].data.location.name;
  275. let recipes = helper.createRecipesFromSquare(response[1].data.objects, merchant._id);
  276. merchant.recipes = recipes;
  277. let populateOwner = res.locals.owner.populate("merchants", "name").execPopulate();
  278. return Promise.all([Recipe.create(recipes), res.locals.owner.save(), merchant.save(), populateOwner]);
  279. })
  280. .then((response)=>{
  281. req.session.merchant = merchant._id;
  282. res.json([{
  283. _id: res.locals.owner._id,
  284. email: res.locals.owner.email,
  285. merchants: res.locals.owner.merchants,
  286. name: res.locals.owner.name
  287. }, merchant]);
  288. helper.getAllMerchantTransactions(merchant, res.locals.owner.square.accessToken);
  289. })
  290. .catch((err)=>{
  291. if(err.name === "ValidationError") return req.session.err = err.errors[Object.keys(err.errors)[0]].properties.message;
  292. return res.json("ERROR: UNABLE TO CREATE NEW MERCHANT");
  293. });
  294. }
  295. }