merchantData.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470
  1. const Owner = require("../models/owner.js");
  2. const Merchant = require("../models/merchant.js");
  3. const Transaction = require("../models/transaction.js");
  4. const helper = require("./helper.js");
  5. const verifyEmail = require("../emails/verifyEmail.js");
  6. const bcrypt = require("bcryptjs");
  7. const ObjectId = require("mongoose").Types.ObjectId;
  8. const axios = require("axios");
  9. const queryString = require("querystring");
  10. module.exports = {
  11. /*
  12. POST - Create a new merchant with no POS system
  13. req.body = {
  14. name: retaurant name,
  15. email: registration email,
  16. password: password,
  17. confirmPassword: confirmation password
  18. owner: String (id of the owner, new owner of undefined)
  19. }
  20. Redirects to /dashboard
  21. */
  22. createMerchantNone: async function(req, res){
  23. if(req.body.password.length < 10){
  24. req.session.error = "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  25. return res.redirect("/register");
  26. }
  27. if(req.body.password !== req.body.confirmPassword){
  28. req.session.error = "PASSWORDS DO NOT MATCH";
  29. return res.redirect("/register");
  30. }
  31. let email = req.body.email.toLowerCase();
  32. const merchantFind = await Merchant.findOne({email: email});
  33. if(merchantFind !== null){
  34. req.session.error = "USER WITH THIS EMAIL ADDRESS ALREADY EXISTS";
  35. return res.redirect("/login");
  36. }
  37. let salt = bcrypt.genSaltSync(10);
  38. let hash = bcrypt.hashSync(req.body.password, salt);
  39. let expirationDate = new Date();
  40. expirationDate.setDate(expirationDate.getDate() + 90);
  41. let owner = new Owner({
  42. email: email,
  43. name: req.body.name,
  44. password: hash,
  45. createdAt: new Date(),
  46. status: ["unverified"],
  47. session: {
  48. sessionId: helper.generateId(25),
  49. expiration: expirationDate
  50. },
  51. merchants: []
  52. });
  53. let merchant = new Merchant({
  54. owner: owner._id,
  55. name: req.body.name,
  56. pos: "none",
  57. createdAt: Date.now(),
  58. inventory: [],
  59. recipes: []
  60. });
  61. owner.merchants.push(merchant._id);
  62. if(email.includes("***")){
  63. owner.email = owner.email.replace("***", "");
  64. owner.status = [];
  65. Promise.all([owner.save(), merchant.save()])
  66. .then((response)=>{
  67. req.session.owner = owner.session.sessionId;
  68. req.session.merchant = merchant._id;
  69. return res.redirect("/dashboard");
  70. })
  71. .catch((err)=>{});
  72. return;
  73. }
  74. Promise.all([owner.save(), merchant.save()])
  75. .then((response)=>{
  76. return res.redirect(`/verify/email/${response[0]._id}`);
  77. })
  78. .catch((err)=>{
  79. if(typeof(err) === "string"){
  80. req.session.error = err;
  81. }else if(err.name === "ValidationError"){
  82. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  83. }else{
  84. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  85. }
  86. return res.redirect("/");
  87. });
  88. },
  89. /*
  90. POST: create new merchant for existing owner
  91. req.body = {
  92. name: String
  93. }
  94. response = [Owner, Merchant]
  95. */
  96. addMerchantNone: function(req, res){
  97. let merchant = new Merchant({
  98. owner: res.locals.owner._id,
  99. name: req.body.name,
  100. pos: "none",
  101. createdAt: new Date(),
  102. inventory: [],
  103. recipes: []
  104. });
  105. res.locals.owner.merchants.push(merchant._id);
  106. let populate = res.locals.owner.populate("merchants", "name").execPopulate();
  107. Promise.all([res.locals.owner.save(), merchant.save(), populate])
  108. .then((response)=>{
  109. let owner = {
  110. _id: response[0]._id,
  111. email: response[0].email,
  112. merchants: response[0].merchants,
  113. name: response[0].name
  114. }
  115. req.session.merchant = response[1]._id;
  116. return res.json([owner, response[1]]);
  117. })
  118. .catch((err)=>{
  119. if(err.name === "ValidationError"){
  120. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  121. }
  122. return res.json("ERROR: UNABLE TO CREATE NEW MERCHANT");
  123. });
  124. },
  125. /*
  126. POST - Update the quantity for a merchant inventory item
  127. req.body = [{
  128. id: id of ingredient to update,
  129. quantity: change in quantity
  130. }]
  131. */
  132. updateIngredientQuantities: function(req, res){
  133. let changedIngredients = [];
  134. res.locals.merchant
  135. .populate("inventory.ingredient")
  136. .execPopulate()
  137. .then((merchant)=>{
  138. for(let i = 0; i < req.body.length; i++){
  139. let updateIngredient;
  140. for(let j = 0; j < merchant.inventory.length; j++){
  141. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  142. updateIngredient = merchant.inventory[j];
  143. break;
  144. }
  145. }
  146. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  147. changedIngredients.push(updateIngredient);
  148. }
  149. return merchant.save();
  150. })
  151. .then((newMerchant)=>{
  152. return res.json(changedIngredients);
  153. })
  154. .catch((err)=>{
  155. if(typeof(err) === "string"){
  156. return res.json(err);
  157. }
  158. if(err.name === "ValidationError"){
  159. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  160. }
  161. return res.json("ERROR: UNABLE TO UPDATE DATA");
  162. });
  163. },
  164. /*
  165. POST - Changes the users password
  166. req.body = {
  167. pass: new password,
  168. confirmPass: new password confirmation,
  169. hash: hashed version of old password
  170. }
  171. */
  172. updatePassword: function(req, res){
  173. Merchant.findOne({password: req.body.hash})
  174. .then((merchant)=>{
  175. if(merchant){
  176. if(req.body.pass.length < 10){
  177. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  178. }
  179. if(req.body.pass !== req.body.confirmPass){
  180. throw "PASSWORDS DO NOT MATCH";
  181. }
  182. let salt = bcrypt.genSaltSync(10);
  183. let hash = bcrypt.hashSync(req.body.pass, salt);
  184. merchant.password = hash;
  185. return merchant.save();
  186. }else{
  187. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA";
  188. return res.redirect("/");
  189. }
  190. })
  191. .then((merchant)=>{
  192. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  193. return res.redirect("/login");
  194. })
  195. .catch((err)=>{
  196. if(typeof(err) === "string") return res.json(err);
  197. if(err.name === "ValidationError"){
  198. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  199. }
  200. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  201. });
  202. },
  203. /*
  204. PUT: Update merchant data
  205. req.body = {
  206. email: String
  207. name: String
  208. address: String
  209. },
  210. response = {
  211. email: String
  212. name: String,
  213. address: String
  214. }
  215. */
  216. updateData: async function(req, res){
  217. if(req.body.email !== res.locals.owner.email){
  218. let ownerCheck = await Owner.findOne({email: req.body.email});
  219. if(ownerCheck !== null) return res.json("USER WITH THIS EMAIL ADDRESS ALREADY EXISTS");
  220. res.locals.owner.email = req.body.email.toLowerCase();
  221. res.locals.owner.status.push("unverified");
  222. axios({
  223. method: "post",
  224. url: "https://api.mailgun.net/v3/mailg.thesubline.net/messages",
  225. headers: {
  226. "Content-Type": "application/x-www-form-urlencoded",
  227. },
  228. auth: {
  229. username: "api",
  230. password: process.env.SUBLINE_MAILGUN_API
  231. },
  232. data: queryString.stringify({
  233. from: "The Subline <subline@leemorgan.dev>",
  234. to: res.locals.owner.email,
  235. subject: "The Subline Email Verification",
  236. html: verifyEmail({
  237. name: res.locals.owner.name,
  238. link: `${process.env.SITE}/verify/${res.locals.owner._id}/${res.locals.owner.session.sessionId}`
  239. })
  240. })
  241. });
  242. }
  243. if(req.body.address !== "" &&
  244. (
  245. res.locals.merchant.address.full === undefined ||
  246. req.body.address.toLowerCase() !== res.locals.merchant.address.full.toLowerCase()
  247. )
  248. ){
  249. let baseURL = "https://geocoding.geo.census.gov/geocoder/locations/onelineaddress/";
  250. let address = req.body.address.replace(/ /g, "+");
  251. let geocode = await axios.get(`${baseURL}?address=${address}&benchmark=2020&format=json`);
  252. let addressData = geocode.data.result.addressMatches[0];
  253. res.locals.merchant.address = {
  254. full: addressData.matchedAddress,
  255. city: addressData.addressComponents.city,
  256. state: addressData.addressComponents.state,
  257. zip: addressData.addressComponents.zip
  258. };
  259. res.locals.merchant.location = {
  260. type: "Point",
  261. coordinates: [addressData.coordinates.x, addressData.coordinates.y]
  262. };
  263. }
  264. res.locals.owner.name = req.body.name;
  265. Promise.all([res.locals.owner.save(), res.locals.merchant.save()])
  266. .then(()=>{
  267. return res.json({
  268. email: res.locals.owner.email,
  269. name: res.locals.owner.name,
  270. address: res.locals.merchant.address.full
  271. });
  272. })
  273. .catch((err)=>{
  274. if(err.name === "ValidationError") return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  275. return res.json("ERROR: UNABLE TO UPDATE DATA");
  276. });
  277. },
  278. /*
  279. PUT: Update merchant password with current password
  280. req.body = {
  281. current: String (current merchant password),
  282. new: String (new password),
  283. confirm: String (new password again for confirmation)
  284. }
  285. response = {redirect: String (link to redirect to)}
  286. */
  287. changePassword: function(req, res){
  288. if(req.body.new !== req.body.confirm) return res.json("PASSWORDS DO NOT MATCH");
  289. bcrypt.compare(req.body.current, res.locals.owner.password, (err, result)=>{
  290. if(result === true){
  291. let salt = bcrypt.genSaltSync(10);
  292. let hash = bcrypt.hashSync(req.body.new, salt);
  293. res.locals.owner.password = hash;
  294. let newExpiration = new Date();
  295. newExpiration.setDate(newExpiration.getDate() + 90);
  296. res.locals.owner.session.sessionId = helper.generateId(25);
  297. res.locals.owner.session.expiration = newExpiration;
  298. res.locals.owner.save()
  299. .then((owner)=>{
  300. req.session.owner = undefined;
  301. req.session.merchant = undefined;
  302. req.session.success = "PASSWORD RESET. PLEASE LOG IN AGAIN.";
  303. return res.json({redirect: `http://${process.env.SITE}/login`});
  304. })
  305. .catch((err)=>{
  306. return res.json("ERROR: UNABLE TO UPDATE PASSWORD");
  307. });
  308. }else{
  309. return res.json("INCORRECT PASSWORD");
  310. }
  311. });
  312. },
  313. /*
  314. DELETE: remove a merchant from its owner
  315. response = [Owner, Merchant (the next), [Transaction]]
  316. */
  317. deleteMerchant: function(req, res){
  318. if(res.locals.owner.merchants.length === 1) throw "one";
  319. for(let i = 0; i < res.locals.owner.merchants.length; i++){
  320. if(res.locals.owner.merchants[i].toString() === res.locals.merchant._id.toString()){
  321. res.locals.owner.merchants.splice(i, 1);
  322. break;
  323. }
  324. }
  325. res.locals.merchant.removed = true;
  326. let now = new Date();
  327. let then = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  328. let transactions = Transaction.aggregate([
  329. {$match: {
  330. merchant: ObjectId(res.locals.owner.merchants[0]._id),
  331. date: {$gte: then}
  332. }},
  333. {$sort: {date: -1}},
  334. {$project: {
  335. date: 1,
  336. recipes: 1
  337. }}
  338. ]);
  339. Promise.all([
  340. Merchant.findOne({_id: res.locals.owner.merchants[0]._id}).populate("inventory.ingredient").populate("recipes"),
  341. res.locals.owner.save(),
  342. res.locals.merchant.save(),
  343. res.locals.owner.populate("merchants", "name").execPopulate(),
  344. transactions
  345. ])
  346. .then((response)=>{
  347. let responseOwner = {
  348. _id: res.locals.owner._id,
  349. email: res.locals.owner.email,
  350. merchants: res.locals.owner.merchants.slice(1),
  351. name: res.locals.owner.name
  352. };
  353. response[0].owner = undefined;
  354. response[0].createdAt = undefined;
  355. response[0].locationId = undefined;
  356. req.session.merchant = response[0]._id;
  357. return res.json([responseOwner, response[0], response[4]]);
  358. })
  359. .catch((err)=>{
  360. if(err === "one") return res.json("YOU CANNOT DELETE YOUR ONLY MERCHANT");
  361. return res.json("ERROR: UNABLE TO DELETE THE MERCHANT");
  362. });
  363. },
  364. /*
  365. GET: gets a merchant to send back to its owner
  366. req.params.id = String (merchant id)
  367. response = [Owner, Merchant, [Transaction]];
  368. */
  369. getMerchant: function(req, res){
  370. let owner = Owner.findOne({"session.sessionId": req.session.owner}).populate("merchants", "name");
  371. let merchant = Merchant.findOne({_id: req.params.id}).populate("inventory.ingredient").populate("recipes");
  372. let now = new Date();
  373. let then = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  374. let transactions = Transaction.aggregate([
  375. {$match: {
  376. merchant: ObjectId(req.params.id),
  377. date: {$gte: then}
  378. }},
  379. {$sort: {date: -1}},
  380. {$project: {
  381. date: 1,
  382. recipes: 1
  383. }}
  384. ]);
  385. Promise.all([owner, merchant, transactions])
  386. .then((response)=>{
  387. if(response[0] === null || response[1] === null) throw "unfound";
  388. if(response[1].owner.toString() !== response[0]._id.toString()) throw "permissions";
  389. let responseOwner = {
  390. _id: response[0]._id,
  391. email: response[0].email,
  392. merchants: response[0].merchants,
  393. name: response[0].name
  394. };
  395. for(let i = 0; i < responseOwner.merchants.length; i++){
  396. if(response[1]._id.toString() === responseOwner.merchants[i]._id.toString()){
  397. responseOwner.merchants.splice(i, 1);
  398. break;
  399. }
  400. }
  401. response[1].owner = undefined;
  402. response[1].createdAt = undefined;
  403. req.session.merchant = response[1]._id;
  404. return res.json([responseOwner, response[1], response[2]]);
  405. })
  406. .catch((err)=>{
  407. if(err === "unfound") return res.json("UNABLE TO FIND THAT MERCHANT");
  408. if(err === "permissions") return res.json("YOU DO NOT HAVE PERMISSION TO DO THAT");
  409. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  410. });
  411. }
  412. }