merchantData.js 9.1 KB

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