merchantData.js 19 KB

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