otherData.js 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. let transaction = new NonPosTransaction({
  12. date: Date.now(),
  13. author: "None",
  14. merchant: req.session.user,
  15. recipes: req.body
  16. });
  17. //Calculate all ingredients used, store to list
  18. Merchant.findOne({_id: req.session.user})
  19. .populate("recipes")
  20. .then((merchant)=>{
  21. for(let reqRecipe of req.body){
  22. let merchRecipe = merchant.recipes.find(r => r._id.toString() === reqRecipe.id);
  23. for(let recipeIngredient of merchRecipe.ingredients){
  24. let merchInvIngredient = merchant.inventory.find(i => i.ingredient.toString() === recipeIngredient.ingredient.toString());
  25. merchInvIngredient.quantity -= recipeIngredient.quantity * reqRecipe.quantity;
  26. }
  27. }
  28. merchant.save()
  29. .then((merchant)=>{
  30. res.json(merchant.inventory);
  31. })
  32. .catch((err)=>{
  33. console.log(err);
  34. return res.render("error");
  35. });
  36. })
  37. .catch((err)=>{
  38. console.log(err);
  39. return res.render("error");
  40. });
  41. transaction.save()
  42. .then((transaction)=>{
  43. return;
  44. })
  45. .catch((err)=>{
  46. console.log(err);
  47. return res.render("error");
  48. });
  49. },
  50. //POST - logs the user in
  51. //Inputs:
  52. // req.body.email
  53. // req.body.password
  54. //Redirects to "/inventory" on success
  55. login: function(req, res){
  56. Merchant.findOne({email: req.body.email.toLowerCase()})
  57. .then((merchant)=>{
  58. if(merchant){
  59. bcrypt.compare(req.body.password, merchant.password, (err, result)=>{
  60. if(result){
  61. req.session.user = merchant._id;
  62. return res.redirect("/inventory");
  63. }
  64. });
  65. }else{
  66. req.session.error = {
  67. type: "login",
  68. message: "Invalid email or password"
  69. }
  70. return res.redirect("/");
  71. }
  72. })
  73. .catch((err)=>{
  74. console.log(err);
  75. return res.redirect("/");
  76. });
  77. },
  78. //GET - logs the user out
  79. //Redirects to "/"
  80. logout: function(req, res){
  81. req.session.user = undefined;
  82. return res.redirect("/");
  83. }
  84. }