merchantData.js 19 KB

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