merchantData.js 18 KB

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