merchantData.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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: array of objects containing ingredient id and quantity
  149. //Returns:
  150. // entire inventory of merchant
  151. addMerchantIngredient: function(req, res){
  152. if(!req.session.user){
  153. req.session.error = "Must be logged in to do that";
  154. return res.redirect("/");
  155. }
  156. Merchant.findOne({_id: req.session.user})
  157. .then((merchant)=>{
  158. for(let ingredient of req.body){
  159. for(let item of merchant.inventory){
  160. if(item.ingredient.toString() === ingredient.id){
  161. return res.json("Error: Duplicate ingredient detected");
  162. }
  163. }
  164. merchant.inventory.push({
  165. ingredient: ingredient.id,
  166. quantity: ingredient.quantity
  167. });
  168. }
  169. merchant.save()
  170. .then((newMerchant)=>{
  171. newMerchant.populate("inventory.ingredient", (err)=>{
  172. if(err){
  173. return res.json("Warning: refresh page to view updates");
  174. }else{
  175. return res.json(newMerchant.inventory);
  176. }
  177. });
  178. })
  179. .catch((err)=>{
  180. return res.json("Error: unable to save new ingredient");
  181. });
  182. })
  183. .catch((err)=>{
  184. return res.json("Error: unable to retrieve user data");
  185. });
  186. },
  187. //POST - Removes an ingredient from the merchant's inventory
  188. //Inputs:
  189. // ingredientId: id of ingredient to remove
  190. //Returns: Nothing
  191. removeMerchantIngredient: function(req, res){
  192. if(!req.session.user){
  193. req.session.error = "Must be logged in to do that";
  194. return res.redirect("/");
  195. }
  196. Merchant.findOne({_id: req.session.user})
  197. .then((merchant)=>{
  198. for(let i = 0; i < merchant.inventory.length; i++){
  199. if(req.body.ingredientId === merchant.inventory[i].ingredient._id.toString()){
  200. merchant.inventory.splice(i, 1);
  201. break;
  202. }
  203. }
  204. merchant.save()
  205. .then((merchant)=>{
  206. return res.json(req.body);
  207. })
  208. .catch((err)=>{
  209. return res.json("Error: unable to save user data");
  210. });
  211. })
  212. .catch((err)=>{
  213. return res.json("Error: unable to retrieve user data");
  214. });
  215. },
  216. //POST - Update the quantity for a merchant inventory item
  217. //Inputs:
  218. // req.body.ingredientId: Id of ingredient to update
  219. // req.body.quantityChange: Amount to change ingredient (not the new value)
  220. //Returns: Nothing
  221. updateMerchantIngredient: function(req, res){
  222. if(!req.session.user){
  223. req.session.error = "Must be logged in to do that";
  224. return res.redirect("/");
  225. }
  226. Merchant.findOne({_id: req.session.user})
  227. .then((merchant)=>{
  228. let updateIngredient = merchant.inventory.find(i => i.ingredient.toString() === req.body.ingredientId);
  229. updateIngredient.quantity = (updateIngredient.quantity + req.body.quantityChange).toFixed(2);
  230. merchant.save()
  231. .then((newMerchant)=>{
  232. res.json({});
  233. })
  234. .catch((err)=>{
  235. return res.json("Error: your data could not be saved");
  236. })
  237. })
  238. .catch((err)=>{
  239. return res.json("Error: your data could not be retrieved");
  240. });
  241. let invAdj = new InventoryAdjustment({
  242. date: Date.now(),
  243. merchant: req.session.user,
  244. ingredient: req.body.ingredientId,
  245. quantity: req.body.quantityChange
  246. });
  247. invAdj.save().catch((err)=>{});
  248. },
  249. //POST - Adds an ingredient to a recipe
  250. //Inputs:
  251. // req.body.recipeId: Id of recipe to change
  252. // req.body.item: Ingredient to add with a quantity
  253. //Returns:
  254. // recipe: Updated recipe with populated ingredients
  255. addRecipeIngredient: function(req, res){
  256. if(!req.session.user){
  257. req.session.error = "Must be logged in to do that";
  258. return res.redirect("/");
  259. }
  260. Recipe.findOne({_id: req.body.recipeId})
  261. .then((recipe)=>{
  262. recipe.ingredients.push({
  263. ingredient: req.body.item.ingredient,
  264. quantity: req.body.item.quantity
  265. });
  266. recipe.save()
  267. .then((recipe)=>{
  268. recipe.populate("ingredients.ingredient", (err)=>{
  269. if(err){
  270. return res.json("Error: could not retrieve ingredients. Please refresh page to see changes");
  271. }
  272. res.json(recipe);
  273. let rc = new RecipeChange({
  274. recipe: recipe,
  275. ingredient: req.body.item.ingredient,
  276. change: req.body.item.quantity
  277. });
  278. rc.save().catch((err)=>{});
  279. return;
  280. })
  281. })
  282. .catch((err)=>{
  283. return res.json("Error: unable to save recipe data");
  284. });
  285. })
  286. .catch((err)=>{
  287. return res.json("Error: unable to retrieve recipe data");
  288. });
  289. },
  290. //POST - Change quantity of a recipe's ingredient
  291. //Inputs:
  292. // req.body.recipeId: Id of recipe containing the ingredient
  293. // req.body.ingredient: The ingredient to update (_id and quantity)
  294. //Returns: Nothing
  295. updateRecipeIngredient: function(req, res){
  296. if(!req.session.user){
  297. req.session.error = "Must be logged in to do that";
  298. return res.redirect("/");
  299. }
  300. Recipe.findOne({_id: req.body.recipeId})
  301. .then((recipe)=>{
  302. for(let ingredient of recipe.ingredients){
  303. if(ingredient._id.toString() === req.body.ingredient._id){
  304. let change = Number(req.body.ingredient.quantity) - ingredient.quantity;
  305. ingredient.quantity = req.body.ingredient.quantity;
  306. recipe.save()
  307. .then((recipe)=>{
  308. res.json({});
  309. let rc = new RecipeChange({
  310. recipe: recipe,
  311. ingredient: ingredient.ingredient,
  312. change: change
  313. });
  314. rc.save().catch((err)=>{});
  315. return;
  316. })
  317. .catch((err)=>{
  318. return res.json("Error: Could not save recipe data");
  319. });
  320. }
  321. }
  322. })
  323. .catch((err)=>{
  324. return res.json("Error: unable to retrieve recipe data");
  325. });
  326. },
  327. //POST - Remove an ingredient from a recipe
  328. //Inputs:
  329. // req.body.ingredientId: Id of ingredient to be removed
  330. // req.body.recipeId: Id of recipe to remove ingredient from
  331. // req.body.quantity: quantity of recipe ingredient for storing
  332. //Returns: Nothing
  333. removeRecipeIngredient: function(req, res){
  334. if(!req.session.user){
  335. req.session.error = "Must be logged in to do that";
  336. return res.redirect("/");
  337. }
  338. Recipe.findOne({_id: req.body.recipeId})
  339. .then((recipe)=>{
  340. for(let i = 0; i < recipe.ingredients.length; i++){
  341. if(recipe.ingredients[i].ingredient._id.toString() === req.body.ingredientId){
  342. recipe.ingredients.splice(i, 1);
  343. break;
  344. }
  345. }
  346. recipe.save()
  347. .then((recipe)=>{
  348. res.json({});
  349. let rc = new RecipeChange({
  350. recipe: req.body.recipeId,
  351. ingredient: req.body.ingredientId,
  352. change: -req.body.quantity
  353. });
  354. rc.save().catch((err)=>{});
  355. return;
  356. })
  357. .catch((err)=>{
  358. return res.json("Error: unable to save recipe data");
  359. });
  360. })
  361. .catch((err)=>{
  362. return res.json("Error: unable to retrieve recipe data");
  363. });
  364. },
  365. //POST - Update merchant information
  366. //Inputs:
  367. // req.body.name: name update
  368. // req.body.email: email update
  369. //Returns: Nothing
  370. updateMerchant: function(req, res){
  371. if(!req.session.user){
  372. req.session.error = "Must be logged in to do that";
  373. return res.redirect("/");
  374. }
  375. Merchant.findOne({_id: req.session.user})
  376. .then((merchant)=>{
  377. merchant.name = req.body.name;
  378. merchant.email = req.body.email;
  379. merchant.save()
  380. .then((updatedMerchant)=>{
  381. return res.json({});
  382. })
  383. .catch((err)=>{
  384. return res.json("Error: unable to save merchant data");
  385. });
  386. })
  387. .catch((err)=>{
  388. return res.json("Error: unable to retrieve merchant data");
  389. });
  390. },
  391. //POST - Update merchant password
  392. //Inputs:
  393. // req.body.oldPass: current merchant password (supposedly)
  394. // req.body.newPass: replacement password
  395. //Returns: Nothing
  396. updatePassword: function(req, res){
  397. if(!req.session.user){
  398. req.session.error = "Must be logged in to do that";
  399. return res.redirect("/");
  400. }
  401. Merchant.findOne({_id: req.session.user})
  402. .then((merchant)=>{
  403. bcrypt.compare(req.body.oldPass, merchant.password, (err, result)=>{
  404. if(result){
  405. let salt = bcrypt.genSaltSync(10);
  406. let hash = bcrypt.hashSync(req.body.newPass, salt);
  407. merchant.password = hash;
  408. merchant.save()
  409. .then((updatedMerchant)=>{
  410. return res.json({});
  411. })
  412. .catch((err)=>{
  413. return res.json("Error: Unable to save new password");
  414. });
  415. }else{
  416. return res.json("Error: old password does not match current password");
  417. }
  418. });
  419. })
  420. .catch((err)=>{
  421. return res.json("Error: Unable to retrieve merchant data");
  422. });
  423. }
  424. }