merchantData.js 11 KB

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