merchantData.js 9.5 KB

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