merchantData.js 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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("/login");
  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. createdAt: Date.now(),
  42. status: ["unverified"],
  43. inventory: [],
  44. recipes: [],
  45. session: {
  46. sessionId: helper.generateId(25),
  47. expiration: expirationDate
  48. }
  49. });
  50. merchant.save()
  51. .then((merchant)=>{
  52. return res.redirect(`/verify/email/${merchant._id}`);
  53. })
  54. .catch((err)=>{
  55. if(typeof(err) === "string"){
  56. req.session.error = err;
  57. }else if(err.name === "ValidationError"){
  58. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  59. }else{
  60. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  61. }
  62. return res.redirect("/");
  63. });
  64. },
  65. /*
  66. POST - Update the quantity for a merchant inventory item
  67. req.body = [{
  68. id: id of ingredient to update,
  69. quantity: change in quantity
  70. }]
  71. */
  72. updateIngredientQuantities: function(req, res){
  73. let adjustments = [];
  74. let changedIngredients = [];
  75. res.locals.merchant
  76. .populate("inventory.ingredient")
  77. .execPopulate()
  78. .then((merchant)=>{
  79. for(let i = 0; i < req.body.length; i++){
  80. let updateIngredient;
  81. for(let j = 0; j < merchant.inventory.length; j++){
  82. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  83. updateIngredient = merchant.inventory[j];
  84. break;
  85. }
  86. }
  87. adjustments.push(new InventoryAdjustment({
  88. date: Date.now(),
  89. merchant: req.session.user,
  90. ingredient: req.body[i].id,
  91. quantity: req.body[i].quantity - updateIngredient.quantity,
  92. }));
  93. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  94. changedIngredients.push(updateIngredient);
  95. }
  96. return merchant.save();
  97. })
  98. .then((newMerchant)=>{
  99. res.json(changedIngredients);
  100. InventoryAdjustment.create(adjustments).catch(()=>{});
  101. return;
  102. })
  103. .catch((err)=>{
  104. if(typeof(err) === "string"){
  105. return res.json(err);
  106. }
  107. if(err.name === "ValidationError"){
  108. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  109. }
  110. return res.json("ERROR: UNABLE TO UPDATE DATA");
  111. });
  112. },
  113. /*
  114. POST - Changes the users password
  115. req.body = {
  116. pass: new password,
  117. confirmPass: new password confirmation,
  118. hash: hashed version of old password
  119. }
  120. */
  121. updatePassword: function(req, res){
  122. Merchant.findOne({password: req.body.hash})
  123. .then((merchant)=>{
  124. if(merchant){
  125. if(req.body.pass.length < 10){
  126. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  127. }
  128. if(req.body.pass !== req.body.confirmPass){
  129. throw "PASSWORDS DO NOT MATCH";
  130. }
  131. let salt = bcrypt.genSaltSync(10);
  132. let hash = bcrypt.hashSync(req.body.pass, salt);
  133. merchant.password = hash;
  134. return merchant.save();
  135. }else{
  136. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA";
  137. return res.redirect("/");
  138. }
  139. })
  140. .then((merchant)=>{
  141. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  142. return res.redirect("/login");
  143. })
  144. .catch((err)=>{
  145. if(typeof(err) === "string"){
  146. return res.json(err);
  147. }
  148. if(err.name === "ValidationError"){
  149. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  150. }
  151. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  152. });
  153. },
  154. /*
  155. PUT: Update merchant data
  156. req.body = {
  157. email: String (merchant email address)
  158. },
  159. response = Merchant
  160. */
  161. updateData: async function(req, res){
  162. if(req.body.email !== res.locals.merchant.email){
  163. let merchantCheck = await Merchant.findOne({email: req.body.email});
  164. if(merchantCheck !== null){
  165. return res.json("USER WITH THIS EMAIL ADDRESS ALREADY EXISTS");
  166. }
  167. res.locals.merchant.email = req.body.email;
  168. res.locals.merchant.status.push("unverified");
  169. const mailgunData = {
  170. from: "The Subline <clientsupport@thesubline.net>",
  171. to: res.locals.merchant.email,
  172. subject: "Email Verification",
  173. html: verifyEmail({
  174. name: res.locals.merchant.name,
  175. link: `${process.env.SITE}/verify/${res.locals.merchant._id}/${res.locals.merchant.sessionId}`
  176. })
  177. };
  178. mailgun.messages().send(mailgunData, (err, body)=>{});
  179. }
  180. res.locals.merchant.save()
  181. .then((merchant)=>{
  182. return res.json(merchant);
  183. })
  184. .catch((err)=>{
  185. if(err.name === "ValidationError"){
  186. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  187. }
  188. return res.json("ERROR: UNABLE TO UPDATE DATA");
  189. });
  190. },
  191. /*
  192. PUT: Update merchant password with current password
  193. req.body = {
  194. current: String (current merchant password),
  195. new: String (new password),
  196. confirm: String (new password again for confirmation)
  197. }
  198. response = {redirect: String (link to redirect to)}
  199. */
  200. changePassword: function(req, res){
  201. if(req.body.new !== req.body.confirm){
  202. return res.json("PASSWORDS DO NOT MATCH");
  203. }
  204. bcrypt.compare(req.body.current, res.locals.merchant.password, (err, result)=>{
  205. if(result === true){
  206. let salt = bcrypt.genSaltSync(10);
  207. let hash = bcrypt.hashSync(req.body.new, salt);
  208. res.locals.merchant.password = hash;
  209. let newExpiration = new Date();
  210. newExpiration.setDate(newExpiration.getDate() + 90);
  211. res.locals.merchant.session.sessionId = helper.generateId(25);
  212. res.locals.merchant.session.expiration = newExpiration;
  213. res.locals.merchant.save()
  214. .then((merchant)=>{
  215. req.session.error = "PLEASE LOG IN";
  216. return res.json({redirect: `http://${process.env.SITE}/login`});
  217. })
  218. .catch((err)=>{
  219. return res.json("ERROR: UNABLE TO UPDATE PASSWORD");
  220. });
  221. }else{
  222. return res.json("INCORRECT PASSWORD");
  223. }
  224. });
  225. }
  226. }