merchantData.js 9.3 KB

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