merchantData.js 21 KB

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