merchantData.js 10 KB

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