squareData.js 14 KB

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