merchantData.js 18 KB

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