squareData.js 14 KB

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