merchantData.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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. module.exports = {
  8. /*
  9. POST - Create a new merchant with no POS system
  10. req.body = {
  11. name: retaurant name,
  12. email: registration email,
  13. password: password,
  14. confirmPassword: confirmation password
  15. }
  16. Redirects to /dashboard
  17. */
  18. createMerchantNone: async function(req, res){
  19. let validation = await Validator.merchant(req.body);
  20. if(validation !== true){
  21. req.session.error = validation;
  22. return res.redirect("/");
  23. }
  24. if(req.body.password === req.body.confirmPassword){
  25. let salt = bcrypt.genSaltSync(10);
  26. let hash = bcrypt.hashSync(req.body.password, salt);
  27. let merchant = new Merchant({
  28. name: req.body.name,
  29. email: req.body.email.toLowerCase(),
  30. password: hash,
  31. pos: "none",
  32. lastUpdatedTime: Date.now(),
  33. createdAt: Date.now(),
  34. accountStatus: "valid",
  35. inventory: [],
  36. recipes: []
  37. });
  38. merchant.save()
  39. .then((merchant)=>{
  40. req.session.user = merchant._id;
  41. return res.redirect("/dashboard");
  42. })
  43. .catch((err)=>{
  44. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  45. return res.redirect("/");
  46. });
  47. }else{
  48. req.session.error = "PASSWORDS DO NOT MATCH";
  49. return res.redirect("/");
  50. }
  51. },
  52. /*
  53. POST - Creates new Clover merchant
  54. Redirects to /dashboard
  55. */
  56. createMerchantClover: async function(req, res){
  57. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}?access_token=${req.session.accessToken}`)
  58. .then((response)=>{
  59. let merchant = new Merchant({
  60. name: response.data.name,
  61. pos: "clover",
  62. posId: req.session.merchantId,
  63. posAccessToken: req.session.accessToken,
  64. lastUpdatedTime: Date.now(),
  65. createdAt: Date.now(),
  66. inventory: [],
  67. recipes: []
  68. });
  69. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}/items?access_token=${req.session.accessToken}`)
  70. .then((response)=>{
  71. let recipes = [];
  72. for(let i = 0; i < response.data.elements.length; i++){
  73. let recipe = new Recipe({
  74. posId: response.data.elements[i].id,
  75. merchant: merchant,
  76. name: response.data.elements[i].name,
  77. price: response.data.elements[i].price,
  78. ingredients: []
  79. });
  80. recipes.push(recipe);
  81. merchant.recipes.push(recipe);
  82. }
  83. Recipe.create(recipes)
  84. .catch((err)=>{
  85. req.session.error = "ERROR: UNABLE TO CREATE YOUR RECIPES FROM CLOVER."
  86. })
  87. merchant.save()
  88. .then((newMerchant)=>{
  89. req.session.accessToken = undefined;
  90. req.session.user = newMerchant._id;
  91. return res.redirect("/dashboard");
  92. })
  93. .catch((err)=>{
  94. req.session.error = "ERROR: UNABLE TO SAVE DATA FROM CLOVER";
  95. return res.redirect("/");
  96. });
  97. })
  98. .catch((err)=>{
  99. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  100. return res.redirect("/");
  101. })
  102. })
  103. .catch((err)=>{
  104. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  105. return res.redirect("/");
  106. });
  107. },
  108. createMerchantSquare: function(req, res){
  109. let merchant = {}
  110. axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
  111. headers: {
  112. Authorization: `Bearer ${req.session.accessToken}`
  113. }
  114. })
  115. .then((response)=>{
  116. req.session.merchantId = undefined;
  117. return new Merchant({
  118. name: response.data.merchant.business_name,
  119. pos: "square",
  120. posId: response.data.merchant.id,
  121. posAccessToken: req.session.accessToken,
  122. lastUpdatedTime: new Date(),
  123. createdAt: new Date(),
  124. squareLocation: response.data.merchant.main_location_id,
  125. inventory: [],
  126. recipes: []
  127. });
  128. })
  129. .then((newMerchant)=>{
  130. req.session.accessToken = undefined;
  131. merchant = newMerchant;
  132. return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  133. object_types: ["ITEM"]
  134. }, {
  135. headers: {
  136. Authorization: `Bearer ${merchant.posAccessToken}`
  137. }
  138. });
  139. })
  140. .then((response)=>{
  141. let recipes = [];
  142. for(let i = 0; i < response.data.objects.length; i++){
  143. if(response.data.objects[i].item_data.variations.length > 1){
  144. for(let j = 0; j < response.data.objects[i].item_data.variations.length; j++){
  145. let recipe = new Recipe({
  146. posId: response.data.objects[i].item_data.variations[j].id,
  147. merchant: merchant._id,
  148. name: `${response.data.objects[i].item_data.name} '${response.data.objects[i].item_data.variations[j].item_variation_data.name}'`,
  149. price: response.data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
  150. });
  151. recipes.push(recipe);
  152. merchant.recipes.push(recipe);
  153. }
  154. }else{
  155. let recipe = new Recipe({
  156. posId: response.data.objects[i].item_data.variations[0].id,
  157. merchant: merchant._id,
  158. name: response.data.objects[i].item_data.name,
  159. price: response.data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
  160. ingredients: []
  161. });
  162. recipes.push(recipe);
  163. merchant.recipes.push(recipe);
  164. }
  165. }
  166. return Recipe.create(recipes);
  167. })
  168. .then((recipes)=>{
  169. return merchant.save();
  170. })
  171. .then((merchant)=>{
  172. req.session.user = merchant._id;
  173. return res.redirect("/dashboard");
  174. })
  175. .catch((err)=>{
  176. banner.createError("ERROR: UNABLE TO CREATE NEW USER AT THIS TIME");
  177. });
  178. },
  179. //DELETE - removes a single recipe from the merchant
  180. removeRecipe: function(req, res){
  181. if(!req.session.user){
  182. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  183. return res.redirect("/");
  184. }
  185. Merchant.findOne({_id: req.session.user})
  186. .then((merchant)=>{
  187. if(merchant.pos === "clover"){
  188. return res.json("YOU MUST EDIT YOUR RECIPES INSIDE CLOVER");
  189. }
  190. for(let i = 0; i < merchant.recipes.length; i++){
  191. if(merchant.recipes[i].toString() === req.params.id){
  192. merchant.recipes.splice(i, 1);
  193. break;
  194. }
  195. }
  196. merchant.save()
  197. .then((updatedMerchant)=>{
  198. return res.json({});
  199. })
  200. .catch((err)=>{
  201. return res.json("ERROR: UNABLE TO SAVE DATA");
  202. })
  203. })
  204. .catch((err)=>{
  205. console.log(err);
  206. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  207. });
  208. },
  209. /*
  210. //POST - Adds an ingredient to merchant's inventory
  211. req.body = [{
  212. id: ingredient id,
  213. quantity: quantity of ingredient for the merchant
  214. defaultUnit: default unit of measurement to display
  215. }]
  216. */
  217. addMerchantIngredient: function(req, res){
  218. if(!req.session.user){
  219. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  220. return res.redirect("/");
  221. }
  222. let validation;
  223. for(let i = 0; i < req.body.length; i++){
  224. validation = Validator.quantity(req.body[i].quantity);
  225. if(validation !== true){
  226. return res.json(validation);
  227. }
  228. }
  229. Merchant.findOne({_id: req.session.user})
  230. .then((merchant)=>{
  231. for(let i = 0; i < req.body.length; i++){
  232. for(let j = 0; j < merchant.inventory.length; j++){
  233. if(merchant.inventory[j].ingredient.toString() === req.body[i].id){
  234. return res.json("ERROR: DUPLICATE INGREDIENT DETECTED");
  235. }
  236. }
  237. merchant.inventory.push({
  238. ingredient: req.body[i].id,
  239. quantity: req.body[i].quantity,
  240. defaultUnit: req.body[i].defaultUnit
  241. });
  242. }
  243. merchant.save()
  244. .then((newMerchant)=>{
  245. return res.json({});
  246. })
  247. .catch((err)=>{
  248. return res.json("ERROR: UNABLE TO SAVE NEW INGREDIENT");
  249. });
  250. })
  251. .catch((err)=>{
  252. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  253. });
  254. },
  255. //POST - Removes an ingredient from the merchant's inventory
  256. removeMerchantIngredient: function(req, res){
  257. if(!req.session.user){
  258. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  259. return res.redirect("/");
  260. }
  261. Merchant.findOne({_id: req.session.user})
  262. .then((merchant)=>{
  263. for(let i = 0; i < merchant.inventory.length; i++){
  264. if(req.params.id === merchant.inventory[i].ingredient._id.toString()){
  265. merchant.inventory.splice(i, 1);
  266. break;
  267. }
  268. }
  269. merchant.save()
  270. .then((merchant)=>{
  271. return res.json({});
  272. })
  273. .catch((err)=>{
  274. return res.json("ERROR: UNABLE TO SAVE USER DATA");
  275. });
  276. })
  277. .catch((err)=>{
  278. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  279. });
  280. },
  281. //PUT - Update the default unit for a single ingredient
  282. ingredientDefaultUnit: function(req, res){
  283. if(!req.session.user){
  284. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  285. return res.redirect("/");
  286. }
  287. Merchant.findOne({_id: req.session.user})
  288. .then((merchant)=>{
  289. for(let i = 0; i < merchant.inventory.length; i++){
  290. if(merchant.inventory[i].ingredient.toString() === req.params.id){
  291. merchant.inventory[i].defaultUnit =req.params.unit;
  292. }
  293. }
  294. return merchant.save()
  295. })
  296. .then((merchant)=>{
  297. return res.json({});
  298. })
  299. .catch((err)=>{
  300. return res.json("ERROR: UNABLE TO UPDATE DEFAULT UNIT");
  301. });
  302. },
  303. /*
  304. POST - Update the quantity for a merchant inventory item
  305. req.body = [{
  306. id: id of ingredient to update,
  307. quantity: change in quantity
  308. }]
  309. */
  310. updateMerchantIngredient: function(req, res){
  311. if(!req.session.user){
  312. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  313. return res.redirect("/");
  314. }
  315. for(let i = 0; i < req.body.length; i++){
  316. let validation = Validator.quantity(req.body[i].quantity);
  317. if(validation !== true){
  318. return res.json(validation);
  319. }
  320. }
  321. let adjustments = [];
  322. Merchant.findOne({_id: req.session.user})
  323. .then((merchant)=>{
  324. for(let i = 0; i < req.body.length; i++){
  325. let updateIngredient;
  326. for(let j = 0; j < merchant.inventory.length; j++){
  327. if(merchant.inventory[j].ingredient.toString() === req.body[i].id){
  328. updateIngredient = merchant.inventory[j];
  329. break;
  330. }
  331. }
  332. adjustments.push(new InventoryAdjustment({
  333. date: Date.now(),
  334. merchant: req.session.user,
  335. ingredient: req.body[i].id,
  336. quantity: req.body[i].quantity - updateIngredient.quantity
  337. }));
  338. updateIngredient.quantity = req.body[i].quantity;
  339. }
  340. merchant.save()
  341. .then((newMerchant)=>{
  342. res.json({});
  343. InventoryAdjustment.create(adjustments).catch(()=>{});
  344. return;
  345. })
  346. .catch((err)=>{
  347. return res.json("ERROR: UNABLE TO SAVE DATA");
  348. })
  349. })
  350. .catch((err)=>{
  351. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  352. });
  353. },
  354. /*
  355. POST - Changes the users password
  356. req.body = {
  357. pass: new password,
  358. confirmPass: new password confirmation,
  359. hash: hashed version of old password
  360. }
  361. */
  362. updatePassword: function(req, res){
  363. let validation = Validator.password(req.body.pass, req.body.confirmPass);
  364. if(validation !== true){
  365. return res.json(validation);
  366. }
  367. Merchant.findOne({password: req.body.hash})
  368. .then((merchant)=>{
  369. if(merchant){
  370. let salt = bcrypt.genSaltSync(10);
  371. let hash = bcrypt.hashSync(req.body.pass, salt);
  372. merchant.password = hash;
  373. return merchant.save();
  374. }else{
  375. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  376. return res.redirect("/");
  377. }
  378. })
  379. .then((merchant)=>{
  380. req.session.error = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  381. return res.redirect("/");
  382. })
  383. .catch((err)=>{});
  384. }
  385. }