merchantData.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. const axios = require("axios");
  2. const bcrypt = require("bcryptjs");
  3. const mailgun = require("mailgun-js")({apiKey: process.env.MG_SUBLINE_APIKEY, domain: "mail.thesubline.net"});
  4. const Merchant = require("../models/merchant");
  5. const Recipe = require("../models/recipe");
  6. const InventoryAdjustment = require("../models/inventoryAdjustment");
  7. const Validator = require("./validator.js");
  8. const Helper = require("./helper.js");
  9. const WelcomeEmail = require("../emails/welcomeEmail.js");
  10. module.exports = {
  11. /*
  12. POST - Create a new merchant with no POS system
  13. req.body = {
  14. name: retaurant name,
  15. email: registration email,
  16. password: password,
  17. confirmPassword: confirmation password
  18. }
  19. Redirects to /dashboard
  20. */
  21. createMerchantNone: async function(req, res){
  22. let validation = await Validator.merchant(req.body);
  23. if(validation !== true){
  24. req.session.error = validation;
  25. return res.redirect("/");
  26. }
  27. if(req.body.password === req.body.confirmPassword){
  28. let salt = bcrypt.genSaltSync(10);
  29. let hash = bcrypt.hashSync(req.body.password, salt);
  30. let merchant = new Merchant({
  31. name: req.body.name,
  32. email: req.body.email.toLowerCase(),
  33. password: hash,
  34. pos: "none",
  35. lastUpdatedTime: Date.now(),
  36. createdAt: Date.now(),
  37. status: ["unverified"],
  38. inventory: [],
  39. recipes: [],
  40. verifyId: Helper.generateId(15)
  41. });
  42. merchant.save()
  43. .then((merchant)=>{
  44. req.session.user = merchant._id;
  45. const mail = merchant.email.split("@");
  46. const mailgunData = {
  47. from: "The Subline <clientsupport@thesubline.net>",
  48. to: merchant.email,
  49. subject: "Welcome to The Subline!",
  50. html: WelcomeEmail({
  51. name: merchant.name,
  52. link: `${process.env.SITE}/verify/${merchant.verifyId}/${mail[0]}`
  53. })
  54. }
  55. mailgun.messages().send(mailgunData, (err, body)=>{});
  56. const mailgunList = mailgun.lists("clientsupport@mail.thesubline.com");
  57. const memberData = {
  58. subscribed: true,
  59. address: merchant.email,
  60. name: merchant.name,
  61. vars: {}
  62. }
  63. mailgunList.members().create(memberData, (err, data)=>{});
  64. return res.redirect("/dashboard");
  65. })
  66. .catch((err)=>{
  67. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  68. return res.redirect("/");
  69. });
  70. }else{
  71. req.session.error = "PASSWORDS DO NOT MATCH";
  72. return res.redirect("/");
  73. }
  74. },
  75. /*
  76. POST - Creates new Clover merchant
  77. Redirects to /dashboard
  78. */
  79. createMerchantClover: async function(req, res){
  80. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}?access_token=${req.session.accessToken}`)
  81. .then((response)=>{
  82. let merchant = new Merchant({
  83. name: response.data.name,
  84. pos: "clover",
  85. posId: req.session.merchantId,
  86. posAccessToken: req.session.accessToken,
  87. lastUpdatedTime: Date.now(),
  88. createdAt: Date.now(),
  89. inventory: [],
  90. recipes: []
  91. });
  92. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}/items?access_token=${req.session.accessToken}`)
  93. .then((response)=>{
  94. let recipes = [];
  95. for(let i = 0; i < response.data.elements.length; i++){
  96. let recipe = new Recipe({
  97. posId: response.data.elements[i].id,
  98. merchant: merchant,
  99. name: response.data.elements[i].name,
  100. price: response.data.elements[i].price,
  101. ingredients: []
  102. });
  103. recipes.push(recipe);
  104. merchant.recipes.push(recipe);
  105. }
  106. Recipe.create(recipes)
  107. .catch((err)=>{
  108. req.session.error = "ERROR: UNABLE TO CREATE YOUR RECIPES FROM CLOVER."
  109. })
  110. merchant.save()
  111. .then((newMerchant)=>{
  112. req.session.accessToken = undefined;
  113. req.session.user = newMerchant._id;
  114. return res.redirect("/dashboard");
  115. })
  116. .catch((err)=>{
  117. req.session.error = "ERROR: UNABLE TO SAVE DATA FROM CLOVER";
  118. return res.redirect("/");
  119. });
  120. })
  121. .catch((err)=>{
  122. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  123. return res.redirect("/");
  124. })
  125. })
  126. .catch((err)=>{
  127. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  128. return res.redirect("/");
  129. });
  130. },
  131. createMerchantSquare: function(req, res){
  132. let merchant = {}
  133. axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
  134. headers: {
  135. Authorization: `Bearer ${req.session.accessToken}`
  136. }
  137. })
  138. .then((response)=>{
  139. req.session.merchantId = undefined;
  140. return new Merchant({
  141. name: response.data.merchant.business_name,
  142. pos: "square",
  143. posId: response.data.merchant.id,
  144. posAccessToken: req.session.accessToken,
  145. lastUpdatedTime: new Date(),
  146. createdAt: new Date(),
  147. squareLocation: response.data.merchant.main_location_id,
  148. inventory: [],
  149. recipes: []
  150. });
  151. })
  152. .then((newMerchant)=>{
  153. req.session.accessToken = undefined;
  154. merchant = newMerchant;
  155. return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  156. object_types: ["ITEM"]
  157. }, {
  158. headers: {
  159. Authorization: `Bearer ${merchant.posAccessToken}`
  160. }
  161. });
  162. })
  163. .then((response)=>{
  164. let recipes = [];
  165. for(let i = 0; i < response.data.objects.length; i++){
  166. if(response.data.objects[i].item_data.variations.length > 1){
  167. for(let j = 0; j < response.data.objects[i].item_data.variations.length; j++){
  168. let recipe = new Recipe({
  169. posId: response.data.objects[i].item_data.variations[j].id,
  170. merchant: merchant._id,
  171. name: `${response.data.objects[i].item_data.name} '${response.data.objects[i].item_data.variations[j].item_variation_data.name}'`,
  172. price: response.data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
  173. });
  174. recipes.push(recipe);
  175. merchant.recipes.push(recipe);
  176. }
  177. }else{
  178. let recipe = new Recipe({
  179. posId: response.data.objects[i].item_data.variations[0].id,
  180. merchant: merchant._id,
  181. name: response.data.objects[i].item_data.name,
  182. price: response.data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
  183. ingredients: []
  184. });
  185. recipes.push(recipe);
  186. merchant.recipes.push(recipe);
  187. }
  188. }
  189. return Recipe.create(recipes);
  190. })
  191. .then((recipes)=>{
  192. return merchant.save();
  193. })
  194. .then((merchant)=>{
  195. req.session.user = merchant._id;
  196. return res.redirect("/dashboard");
  197. })
  198. .catch((err)=>{
  199. banner.createError("ERROR: UNABLE TO CREATE NEW USER AT THIS TIME");
  200. });
  201. },
  202. //PUT - Update the default unit for a single ingredient
  203. ingredientDefaultUnit: function(req, res){
  204. if(!req.session.user){
  205. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  206. return res.redirect("/");
  207. }
  208. Merchant.findOne({_id: req.session.user})
  209. .then((merchant)=>{
  210. for(let i = 0; i < merchant.inventory.length; i++){
  211. if(merchant.inventory[i].ingredient.toString() === req.params.id){
  212. merchant.inventory[i].defaultUnit =req.params.unit;
  213. }
  214. }
  215. return merchant.save()
  216. })
  217. .then((merchant)=>{
  218. return res.json({});
  219. })
  220. .catch((err)=>{
  221. return res.json("ERROR: UNABLE TO UPDATE DEFAULT UNIT");
  222. });
  223. },
  224. /*
  225. POST - Update the quantity for a merchant inventory item
  226. req.body = [{
  227. id: id of ingredient to update,
  228. quantity: change in quantity
  229. }]
  230. */
  231. updateMerchantIngredient: function(req, res){
  232. if(!req.session.user){
  233. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  234. return res.redirect("/");
  235. }
  236. for(let i = 0; i < req.body.length; i++){
  237. let validation = Validator.quantity(req.body[i].quantity);
  238. if(validation !== true){
  239. return res.json(validation);
  240. }
  241. }
  242. let adjustments = [];
  243. Merchant.findOne({_id: req.session.user})
  244. .then((merchant)=>{
  245. for(let i = 0; i < req.body.length; i++){
  246. let updateIngredient;
  247. for(let j = 0; j < merchant.inventory.length; j++){
  248. if(merchant.inventory[j].ingredient.toString() === req.body[i].id){
  249. updateIngredient = merchant.inventory[j];
  250. break;
  251. }
  252. }
  253. adjustments.push(new InventoryAdjustment({
  254. date: Date.now(),
  255. merchant: req.session.user,
  256. ingredient: req.body[i].id,
  257. quantity: req.body[i].quantity - updateIngredient.quantity,
  258. }));
  259. updateIngredient.quantity = req.body[i].quantity;
  260. }
  261. return merchant.save();
  262. })
  263. .then((newMerchant)=>{
  264. res.json({});
  265. InventoryAdjustment.create(adjustments).catch(()=>{});
  266. return;
  267. })
  268. .catch((err)=>{
  269. return res.json("ERROR: UNABLE TO UPDATE DATA");
  270. });
  271. },
  272. /*
  273. POST - Changes the users password
  274. req.body = {
  275. pass: new password,
  276. confirmPass: new password confirmation,
  277. hash: hashed version of old password
  278. }
  279. */
  280. updatePassword: function(req, res){
  281. let validation = Validator.password(req.body.pass, req.body.confirmPass);
  282. if(validation !== true){
  283. return res.json(validation);
  284. }
  285. Merchant.findOne({password: req.body.hash})
  286. .then((merchant)=>{
  287. if(merchant){
  288. let salt = bcrypt.genSaltSync(10);
  289. let hash = bcrypt.hashSync(req.body.pass, salt);
  290. merchant.password = hash;
  291. return merchant.save();
  292. }else{
  293. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  294. return res.redirect("/");
  295. }
  296. })
  297. .then((merchant)=>{
  298. req.session.error = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  299. return res.redirect("/");
  300. })
  301. .catch((err)=>{});
  302. }
  303. }