merchantData.js 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. const Merchant = require("../models/merchant");
  2. const InventoryAdjustment = require("../models/inventoryAdjustment");
  3. const helper = require("./helper.js");
  4. const verifyEmail = require("../emails/verifyEmail.js");
  5. const bcrypt = require("bcryptjs");
  6. const mailgun = require("mailgun-js")({apiKey: process.env.MG_SUBLINE_APIKEY, domain: "mail.thesubline.net"});
  7. module.exports = {
  8. /*
  9. POST - Create a new merchant with no POS system
  10. req.body = {
  11. name: retaurant name,
  12. email: registration email,
  13. password: password,
  14. confirmPassword: confirmation password
  15. }
  16. Redirects to /dashboard
  17. */
  18. createMerchantNone: async function(req, res){
  19. if(req.body.password.length < 10){
  20. req.session.error = "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  21. return res.redirect("/register");
  22. }
  23. if(req.body.password !== req.body.confirmPassword){
  24. req.session.error = "PASSWORDS DO NOT MATCH";
  25. return res.redirect("/register");
  26. }
  27. const merchantFind = await Merchant.findOne({email: req.body.email.toLowerCase()});
  28. if(merchantFind !== null){
  29. req.session.error = "USER WITH THIS EMAIL ADDRESS ALREADY EXISTS";
  30. return res.redirect("/register");
  31. }
  32. let salt = bcrypt.genSaltSync(10);
  33. let hash = bcrypt.hashSync(req.body.password, salt);
  34. let expirationDate = new Date();
  35. expirationDate.setDate(expirationDate.getDate() + 90);
  36. let merchant = new Merchant({
  37. name: req.body.name,
  38. email: req.body.email.toLowerCase(),
  39. password: hash,
  40. pos: "none",
  41. lastUpdatedTime: Date.now(),
  42. createdAt: Date.now(),
  43. status: ["unverified"],
  44. inventory: [],
  45. recipes: [],
  46. verifyId: helper.generateId(15),
  47. session: {
  48. sessionId: helper.generateId(25),
  49. expiration: expirationDate
  50. }
  51. });
  52. merchant.save()
  53. .then((merchant)=>{
  54. return res.redirect(`/verify/email/${merchant._id}`);
  55. })
  56. .catch((err)=>{
  57. if(typeof(err) === "string"){
  58. req.session.error = err;
  59. }else if(err.name === "ValidationError"){
  60. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  61. }else{
  62. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  63. }
  64. return res.redirect("/");
  65. });
  66. },
  67. /*
  68. POST - Update the quantity for a merchant inventory item
  69. req.body = [{
  70. id: id of ingredient to update,
  71. quantity: change in quantity
  72. }]
  73. */
  74. updateIngredientQuantities: function(req, res){
  75. let adjustments = [];
  76. let changedIngredients = [];
  77. res.locals.merchant
  78. .populate("inventory.ingredient")
  79. .execPopulate()
  80. .then((merchant)=>{
  81. for(let i = 0; i < req.body.length; i++){
  82. let updateIngredient;
  83. for(let j = 0; j < merchant.inventory.length; j++){
  84. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  85. updateIngredient = merchant.inventory[j];
  86. break;
  87. }
  88. }
  89. adjustments.push(new InventoryAdjustment({
  90. date: Date.now(),
  91. merchant: req.session.user,
  92. ingredient: req.body[i].id,
  93. quantity: req.body[i].quantity - updateIngredient.quantity,
  94. }));
  95. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  96. changedIngredients.push(updateIngredient);
  97. }
  98. return merchant.save();
  99. })
  100. .then((newMerchant)=>{
  101. res.json(changedIngredients);
  102. InventoryAdjustment.create(adjustments).catch(()=>{});
  103. return;
  104. })
  105. .catch((err)=>{
  106. if(typeof(err) === "string"){
  107. return res.json(err);
  108. }
  109. if(err.name === "ValidationError"){
  110. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  111. }
  112. return res.json("ERROR: UNABLE TO UPDATE DATA");
  113. });
  114. },
  115. /*
  116. POST - Changes the users password
  117. req.body = {
  118. pass: new password,
  119. confirmPass: new password confirmation,
  120. hash: hashed version of old password
  121. }
  122. */
  123. updatePassword: function(req, res){
  124. Merchant.findOne({password: req.body.hash})
  125. .then((merchant)=>{
  126. if(merchant){
  127. if(req.body.pass.length < 10){
  128. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  129. }
  130. if(req.body.pass !== req.body.confirmPass){
  131. throw "PASSWORDS DO NOT MATCH";
  132. }
  133. let salt = bcrypt.genSaltSync(10);
  134. let hash = bcrypt.hashSync(req.body.pass, salt);
  135. merchant.password = hash;
  136. return merchant.save();
  137. }else{
  138. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  139. return res.redirect("/");
  140. }
  141. })
  142. .then((merchant)=>{
  143. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  144. return res.redirect("/login");
  145. })
  146. .catch((err)=>{
  147. if(typeof(err) === "string"){
  148. return res.json(err);
  149. }
  150. if(err.name === "ValidationError"){
  151. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  152. }
  153. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  154. });
  155. },
  156. /*
  157. PUT: Update merchant data
  158. req.body = {
  159. email: String (merchant email address)
  160. },
  161. response = Merchant
  162. */
  163. updateData: function(req, res){
  164. if(req.body.email !== res.locals.merchant.email){
  165. res.locals.merchant.email = req.body.email;
  166. res.locals.merchant.status.push("unverified");
  167. const mailgunData = {
  168. from: "The Subline <clientsupport@thesubline.net>",
  169. to: res.locals.merchant.email,
  170. subject: "Email Verification",
  171. html: verifyEmail({
  172. name: res.locals.merchant.name,
  173. link: `${process.env.SITE}/verify/${res.locals.merchant._id}/${res.locals.merchant.verifyId}`
  174. })
  175. };
  176. mailgun.messages().send(mailgunData, (err, body)=>{console.log(err)});
  177. }
  178. res.locals.merchant.save()
  179. .then((merchant)=>{
  180. return res.json(merchant);
  181. })
  182. .catch((err)=>{
  183. if(err.name === "ValidationError"){
  184. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  185. }
  186. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  187. });
  188. }
  189. }