otherData.js 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. const bcrypt = require("bcryptjs");
  2. const NonPosTransaction = require("../models/nonPosTransaction");
  3. const Merchant = require("../models/merchant");
  4. module.exports = {
  5. //POST - Update non-pos merchant inventory and create a transaction
  6. //Inputs:
  7. // recipesSold: list of recipes sold and how much (recipe._id and quantity)
  8. //Returns:
  9. // merchant.inventory: entire merchant inventory after being updated
  10. createTransaction: function(req, res){
  11. if(!req.session.user){
  12. return res.render("error");
  13. }
  14. let transaction = new NonPosTransaction({
  15. date: Date.now(),
  16. author: "None",
  17. merchant: req.session.user,
  18. recipes: req.body
  19. });
  20. //Calculate all ingredients used, store to list
  21. Merchant.findOne({_id: req.session.user})
  22. .populate("recipes")
  23. .then((merchant)=>{
  24. for(let reqRecipe of req.body){
  25. let merchRecipe = merchant.recipes.find(r => r._id.toString() === reqRecipe.id);
  26. for(let recipeIngredient of merchRecipe.ingredients){
  27. let merchInvIngredient = merchant.inventory.find(i => i.ingredient.toString() === recipeIngredient.ingredient.toString());
  28. merchInvIngredient.quantity -= recipeIngredient.quantity * reqRecipe.quantity;
  29. }
  30. }
  31. merchant.save()
  32. .then((merchant)=>{
  33. res.json(merchant.inventory);
  34. })
  35. .catch((err)=>{
  36. console.log(err);
  37. return res.render("error");
  38. });
  39. })
  40. .catch((err)=>{
  41. console.log(err);
  42. return res.render("error");
  43. });
  44. transaction.save()
  45. .then((transaction)=>{
  46. return;
  47. })
  48. .catch((err)=>{
  49. console.log(err);
  50. return res.render("error");
  51. });
  52. },
  53. //POST - logs the user in
  54. //Inputs:
  55. // req.body.email
  56. // req.body.password
  57. //Redirects to "/inventory" on success
  58. login: function(req, res){
  59. Merchant.findOne({email: req.body.email.toLowerCase()})
  60. .then((merchant)=>{
  61. if(merchant){
  62. bcrypt.compare(req.body.password, merchant.password, (err, result)=>{
  63. if(result){
  64. req.session.user = merchant._id;
  65. return res.redirect("/inventory");
  66. }
  67. });
  68. }else{
  69. req.session.error = {
  70. type: "login",
  71. message: "Invalid email or password"
  72. }
  73. return res.redirect("/");
  74. }
  75. })
  76. .catch((err)=>{
  77. console.log(err);
  78. return res.redirect("/");
  79. });
  80. },
  81. //GET - logs the user out
  82. //Redirects to "/"
  83. logout: function(req, res){
  84. req.session.user = undefined;
  85. return res.redirect("/");
  86. }
  87. }