merchantData.js 12 KB

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