merchantData.js 16 KB

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