merchantData.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  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 RecipeChange = require("../models/recipeChange");
  7. module.exports = {
  8. //POST - Create a new merchant with no POS system
  9. //Inputs:
  10. // req.body.name: restaurant name
  11. // req.body.email: registration email
  12. // req.body.password: password
  13. // req.body.confirmPassword: confirmation password
  14. //Redirects to /dashboard
  15. createMerchantNone: function(req, res){
  16. if(req.body.password === req.body.confirmPassword){
  17. var salt = bcrypt.genSaltSync(10);
  18. var hash = bcrypt.hashSync(req.body.password, salt);
  19. let merchant = new Merchant({
  20. name: req.body.name,
  21. email: req.body.email.toLowerCase(),
  22. password: hash,
  23. pos: "none",
  24. lastUpdatedTime: Date.now(),
  25. createdAt: Date.now(),
  26. accountStatus: "valid",
  27. inventory: [],
  28. recipes: []
  29. });
  30. merchant.save()
  31. .then((merchant)=>{
  32. req.session.user = merchant._id;
  33. return res.redirect("/dashboard");
  34. })
  35. .catch((err)=>{
  36. req.session.error = "Error: Unable to create account at this time";
  37. return res.redirect("/");
  38. });
  39. }else{
  40. req.session.error = "Error: Passwords must match";
  41. return res.redirect("/");
  42. }
  43. },
  44. //POST - Creates a Clover merchant from all entered data
  45. //Inputs:
  46. // req.body.data: All data from frontend in form of merchant model
  47. //Redirect to /dashboard
  48. createMerchantClover: async function(req, res){
  49. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}?access_token=${req.session.accessToken}`)
  50. .then((response)=>{
  51. let merchant = new Merchant({
  52. name: response.data.name,
  53. pos: "clover",
  54. posId: req.session.merchantId,
  55. posAccessToken: req.session.accessToken,
  56. lastUpdatedTime: Date.now(),
  57. createdAt: Date.now(),
  58. inventory: [],
  59. recipes: []
  60. });
  61. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}/items?access_token=${req.session.accessToken}`)
  62. .then((response)=>{
  63. let recipes = [];
  64. for(let item of response.data.elements){
  65. let recipe = new Recipe({
  66. posId: item.id,
  67. merchant: merchant,
  68. name: item.name,
  69. price: item.price,
  70. ingredients: []
  71. });
  72. recipes.push(recipe);
  73. merchant.recipes.push(recipe);
  74. }
  75. Recipe.create(recipes)
  76. .then((recipes)=>{
  77. console.log("recipes supposedly created");
  78. })
  79. .catch((err)=>{
  80. req.session.error = "Error: unable to create your recipes from Clover. Try using updating your recipes on the recipe page."
  81. })
  82. merchant.save()
  83. .then((newMerchant)=>{
  84. req.session.accessToken = undefined;
  85. req.session.user = newMerchant._id;
  86. return res.redirect("/dashboard");
  87. })
  88. .catch((err)=>{
  89. req.session.error = "Error: unable to save data from Clover";
  90. return res.redirect("/");
  91. });
  92. })
  93. .catch((err)=>{
  94. req.session.error = "Error: unable to retrieve necessary 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. //GET - Checks clover for new or deleted recipes
  104. //Returns:
  105. // merchant: Full merchant (recipe ingredients populated)
  106. // count: Number of new recipes
  107. updateRecipes: function(req, res){
  108. if(!req.session.user){
  109. req.session.error = "Must be logged in to do that";
  110. return res.redirect("/");
  111. }
  112. Merchant.findOne({_id: req.session.user})
  113. .populate("recipes")
  114. .then((merchant)=>{
  115. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${merchant.posId}/items?access_token=${token}`)
  116. .then((result)=>{
  117. let deletedRecipes = merchant.recipes.slice();
  118. for(let i = 0; i < result.data.elements.length; i++){
  119. for(let j = 0; j < deletedRecipes.length; j++){
  120. if(result.data.elements[i].id === deletedRecipes[j].posId){
  121. result.data.elements.splice(i, 1);
  122. deletedRecipes.splice(j, 1);
  123. i--;
  124. break;
  125. }
  126. }
  127. }
  128. for(let recipe of deletedRecipes){
  129. for(let i = 0; i < merchant.recipes.length; i++){
  130. if(recipe._id === merchant.recipes[i]._id){
  131. merchant.recipes.splice(i, 1);
  132. break;
  133. }
  134. }
  135. }
  136. let newRecipes = []
  137. for(let recipe of result.data.elements){
  138. let newRecipe = new Recipe({
  139. posId: recipe.id,
  140. merchant: merchant._id,
  141. name: recipe.name,
  142. ingredients: []
  143. });
  144. merchant.recipes.push(newRecipe);
  145. newRecipes.push(newRecipe);
  146. }
  147. Recipe.create(newRecipes)
  148. .catch((err)=>{
  149. return res.json("Error: unable to create recipes");
  150. });
  151. merchant.save()
  152. .then((newMerchant)=>{
  153. newMerchant.populate(["recipes.ingredients.ingredient", "inventory.ingredient"]).execPopulate()
  154. .then((newestMerchant)=>{
  155. merchant.password = undefined;
  156. return res.json(newestMerchant);
  157. })
  158. .catch((err)=>{
  159. return res.json("Error: unable to retrieve user data");
  160. });
  161. })
  162. .catch((err)=>{
  163. return res.json("Error: unable to retrieve user data");
  164. });
  165. })
  166. .catch((err)=>{
  167. return res.json("Error: unable to retrieve data from Clover");
  168. });
  169. })
  170. .catch((err)=>{
  171. return res.json("Error: unable to retrieve user data");
  172. });
  173. },
  174. //POST - removes a single recipe
  175. //Inputs:
  176. // req.body: the id of the recipe to be removed
  177. removeRecipe: function(req, res){
  178. if(!req.session.user){
  179. req.session.error = "Must be logged in to do that";
  180. return res.redirect("/");
  181. }
  182. Merchant.findOne({_id: req.session.user})
  183. .then((merchant)=>{
  184. if(merchant.pos === "clover"){
  185. return res.json("Error: you must edit your recipes inside Clover");
  186. }
  187. for(let i = 0; i < merchant.recipes.length; i++){
  188. if(merchant.recipes[i].toString() === req.body.id){
  189. merchant.recipes.splice(i, 1);
  190. break;
  191. }
  192. }
  193. merchant.save()
  194. .then((updatedMerchant)=>{
  195. return res.json({});
  196. })
  197. .catch((err)=>{
  198. return res.json("Error: unable to save data")
  199. })
  200. })
  201. .catch((err)=>{
  202. return res.json("Error: unable to retrieve merchant data");
  203. });
  204. },
  205. //POST - Adds an ingredient to merchant's inventory
  206. //Inputs:
  207. // req.body: array of objects containing ingredient id and quantity
  208. //Returns:
  209. // entire inventory of merchant
  210. addMerchantIngredient: function(req, res){
  211. if(!req.session.user){
  212. req.session.error = "Must be logged in to do that";
  213. return res.redirect("/");
  214. }
  215. Merchant.findOne({_id: req.session.user})
  216. .then((merchant)=>{
  217. for(let ingredient of req.body){
  218. for(let item of merchant.inventory){
  219. if(item.ingredient.toString() === ingredient.id){
  220. return res.json("Error: Duplicate ingredient detected");
  221. }
  222. }
  223. merchant.inventory.push({
  224. ingredient: ingredient.id,
  225. quantity: ingredient.quantity
  226. });
  227. }
  228. merchant.save()
  229. .then((newMerchant)=>{
  230. newMerchant.populate("inventory.ingredient", (err)=>{
  231. if(err){
  232. return res.json("Warning: refresh page to view updates");
  233. }else{
  234. return res.json(newMerchant.inventory);
  235. }
  236. });
  237. })
  238. .catch((err)=>{
  239. return res.json("Error: unable to save new ingredient");
  240. });
  241. })
  242. .catch((err)=>{
  243. return res.json("Error: unable to retrieve user data");
  244. });
  245. },
  246. //POST - Removes an ingredient from the merchant's inventory
  247. //Inputs:
  248. // ingredientId: id of ingredient to remove
  249. //Returns: Nothing
  250. removeMerchantIngredient: function(req, res){
  251. if(!req.session.user){
  252. req.session.error = "Must be logged in to do that";
  253. return res.redirect("/");
  254. }
  255. Merchant.findOne({_id: req.session.user})
  256. .then((merchant)=>{
  257. for(let i = 0; i < merchant.inventory.length; i++){
  258. if(req.body.ingredientId === merchant.inventory[i].ingredient._id.toString()){
  259. merchant.inventory.splice(i, 1);
  260. break;
  261. }
  262. }
  263. merchant.save()
  264. .then((merchant)=>{
  265. return res.json(req.body);
  266. })
  267. .catch((err)=>{
  268. return res.json("Error: unable to save user data");
  269. });
  270. })
  271. .catch((err)=>{
  272. return res.json("Error: unable to retrieve user data");
  273. });
  274. },
  275. //POST - Update the quantity for a merchant inventory item
  276. //Inputs:
  277. // req.body.ingredientId: Id of ingredient to update
  278. // req.body.quantityChange: Amount to change ingredient (not the new value)
  279. //Returns: Nothing
  280. updateMerchantIngredient: function(req, res){
  281. if(!req.session.user){
  282. req.session.error = "Must be logged in to do that";
  283. return res.redirect("/");
  284. }
  285. Merchant.findOne({_id: req.session.user})
  286. .then((merchant)=>{
  287. let updateIngredient = merchant.inventory.find(i => i.ingredient.toString() === req.body.ingredientId);
  288. updateIngredient.quantity = (updateIngredient.quantity + req.body.quantityChange).toFixed(2);
  289. merchant.save()
  290. .then((newMerchant)=>{
  291. res.json({});
  292. })
  293. .catch((err)=>{
  294. return res.json("Error: your data could not be saved");
  295. })
  296. })
  297. .catch((err)=>{
  298. return res.json("Error: your data could not be retrieved");
  299. });
  300. let invAdj = new InventoryAdjustment({
  301. date: Date.now(),
  302. merchant: req.session.user,
  303. ingredient: req.body.ingredientId,
  304. quantity: req.body.quantityChange
  305. });
  306. invAdj.save().catch((err)=>{});
  307. },
  308. //POST - Adds an ingredient to a recipe
  309. //Inputs:
  310. // req.body.recipeId: Id of recipe to change
  311. // req.body.item: Ingredient to add with a quantity
  312. //Returns:
  313. // recipe: Updated recipe with populated ingredients
  314. addRecipeIngredient: function(req, res){
  315. if(!req.session.user){
  316. req.session.error = "Must be logged in to do that";
  317. return res.redirect("/");
  318. }
  319. Recipe.findOne({_id: req.body.recipeId})
  320. .then((recipe)=>{
  321. recipe.ingredients.push({
  322. ingredient: req.body.item.ingredient,
  323. quantity: req.body.item.quantity
  324. });
  325. recipe.save()
  326. .then((recipe)=>{
  327. recipe.populate("ingredients.ingredient", (err)=>{
  328. if(err){
  329. return res.json("Error: could not retrieve ingredients. Please refresh page to see changes");
  330. }
  331. res.json(recipe);
  332. let rc = new RecipeChange({
  333. recipe: recipe,
  334. ingredient: req.body.item.ingredient,
  335. change: req.body.item.quantity
  336. });
  337. rc.save().catch((err)=>{});
  338. return;
  339. })
  340. })
  341. .catch((err)=>{
  342. return res.json("Error: unable to save recipe data");
  343. });
  344. })
  345. .catch((err)=>{
  346. return res.json("Error: unable to retrieve recipe data");
  347. });
  348. },
  349. //POST - Change quantity of a recipe's ingredient
  350. //Inputs:
  351. // req.body.recipeId: Id of recipe containing the ingredient
  352. // req.body.ingredient: The ingredient to update (_id and quantity)
  353. //Returns: Nothing
  354. updateRecipeIngredient: function(req, res){
  355. if(!req.session.user){
  356. req.session.error = "Must be logged in to do that";
  357. return res.redirect("/");
  358. }
  359. Recipe.findOne({_id: req.body.recipeId})
  360. .then((recipe)=>{
  361. for(let ingredient of recipe.ingredients){
  362. if(ingredient._id.toString() === req.body.ingredient._id){
  363. let change = Number(req.body.ingredient.quantity) - ingredient.quantity;
  364. ingredient.quantity = req.body.ingredient.quantity;
  365. recipe.save()
  366. .then((recipe)=>{
  367. res.json({});
  368. let rc = new RecipeChange({
  369. recipe: recipe,
  370. ingredient: ingredient.ingredient,
  371. change: change
  372. });
  373. rc.save().catch((err)=>{});
  374. return;
  375. })
  376. .catch((err)=>{
  377. return res.json("Error: Could not save recipe data");
  378. });
  379. }
  380. }
  381. })
  382. .catch((err)=>{
  383. return res.json("Error: unable to retrieve recipe data");
  384. });
  385. },
  386. //POST - Remove an ingredient from a recipe
  387. //Inputs:
  388. // req.body.ingredientId: Id of ingredient to be removed
  389. // req.body.recipeId: Id of recipe to remove ingredient from
  390. // req.body.quantity: quantity of recipe ingredient for storing
  391. //Returns: Nothing
  392. removeRecipeIngredient: function(req, res){
  393. if(!req.session.user){
  394. req.session.error = "Must be logged in to do that";
  395. return res.redirect("/");
  396. }
  397. Recipe.findOne({_id: req.body.recipeId})
  398. .then((recipe)=>{
  399. for(let i = 0; i < recipe.ingredients.length; i++){
  400. if(recipe.ingredients[i].ingredient._id.toString() === req.body.ingredientId){
  401. recipe.ingredients.splice(i, 1);
  402. break;
  403. }
  404. }
  405. recipe.save()
  406. .then((recipe)=>{
  407. res.json({});
  408. let rc = new RecipeChange({
  409. recipe: req.body.recipeId,
  410. ingredient: req.body.ingredientId,
  411. change: -req.body.quantity
  412. });
  413. rc.save().catch((err)=>{});
  414. return;
  415. })
  416. .catch((err)=>{
  417. return res.json("Error: unable to save recipe data");
  418. });
  419. })
  420. .catch((err)=>{
  421. return res.json("Error: unable to retrieve recipe data");
  422. });
  423. },
  424. //POST - Update merchant information
  425. //Inputs:
  426. // req.body.name: name update
  427. // req.body.email: email update
  428. //Returns: Nothing
  429. updateMerchant: function(req, res){
  430. if(!req.session.user){
  431. req.session.error = "Must be logged in to do that";
  432. return res.redirect("/");
  433. }
  434. Merchant.findOne({_id: req.session.user})
  435. .then((merchant)=>{
  436. merchant.name = req.body.name;
  437. merchant.email = req.body.email;
  438. merchant.save()
  439. .then((updatedMerchant)=>{
  440. return res.json({});
  441. })
  442. .catch((err)=>{
  443. return res.json("Error: unable to save merchant data");
  444. });
  445. })
  446. .catch((err)=>{
  447. return res.json("Error: unable to retrieve merchant data");
  448. });
  449. },
  450. //POST - Update merchant password
  451. //Inputs:
  452. // req.body.oldPass: current merchant password (supposedly)
  453. // req.body.newPass: replacement password
  454. //Returns: Nothing
  455. updatePassword: function(req, res){
  456. if(!req.session.user){
  457. req.session.error = "Must be logged in to do that";
  458. return res.redirect("/");
  459. }
  460. Merchant.findOne({_id: req.session.user})
  461. .then((merchant)=>{
  462. bcrypt.compare(req.body.oldPass, merchant.password, (err, result)=>{
  463. if(result){
  464. let salt = bcrypt.genSaltSync(10);
  465. let hash = bcrypt.hashSync(req.body.newPass, salt);
  466. merchant.password = hash;
  467. merchant.save()
  468. .then((updatedMerchant)=>{
  469. return res.json({});
  470. })
  471. .catch((err)=>{
  472. return res.json("Error: Unable to save new password");
  473. });
  474. }else{
  475. return res.json("Error: old password does not match current password");
  476. }
  477. });
  478. })
  479. .catch((err)=>{
  480. return res.json("Error: Unable to retrieve merchant data");
  481. });
  482. }
  483. }