merchantData.js 12 KB

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