merchantData.js 21 KB

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