merchantData.js 12 KB

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