merchantData.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  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") return res.json(err);
  195. if(err.name === "ValidationError"){
  196. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  197. }
  198. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  199. });
  200. },
  201. /*
  202. PUT: Update merchant data
  203. req.body = {
  204. email: String
  205. name: String
  206. address: String
  207. },
  208. response = {
  209. email: String
  210. name: String,
  211. address: String
  212. }
  213. */
  214. updateData: async function(req, res){
  215. if(req.body.email !== res.locals.owner.email){
  216. let ownerCheck = await Owner.findOne({email: req.body.email});
  217. if(ownerCheck !== null) return res.json("USER WITH THIS EMAIL ADDRESS ALREADY EXISTS");
  218. res.locals.owner.email = req.body.email.toLowerCase();
  219. res.locals.owner.status.push("unverified");
  220. const mailgunData = {
  221. from: "The Subline <clientsupport@thesubline.net>",
  222. to: res.locals.owner.email,
  223. subject: "Email Verification",
  224. html: verifyEmail({
  225. name: res.locals.owner.name,
  226. link: `${process.env.SITE}/verify/${res.locals.owner._id}/${res.locals.owner.session.sessionId}`
  227. })
  228. };
  229. mailgun.messages().send(mailgunData, (err, body)=>{});
  230. }
  231. if(req.body.address !== "", req.body.address.toLowerCase() !== res.locals.merchant.address.full.toLowerCase()){
  232. let baseURL = "https://geocoding.geo.census.gov/geocoder/locations/onelineaddress/";
  233. let address = req.body.address.replace(/ /g, "+");
  234. let geocode = await axios.get(`${baseURL}?address=${address}&benchmark=2020&format=json`);
  235. let addressData = geocode.data.result.addressMatches[0];
  236. res.locals.merchant.address = {
  237. full: addressData.matchedAddress,
  238. city: addressData.addressComponents.city,
  239. state: addressData.addressComponents.state,
  240. zip: addressData.addressComponents.zip
  241. };
  242. res.locals.merchant.location = {
  243. type: "Point",
  244. coordinates: [addressData.coordinates.x, addressData.coordinates.y]
  245. };
  246. }
  247. res.locals.owner.name = req.body.name;
  248. Promise.all([res.locals.owner.save(), res.locals.merchant.save()])
  249. .then(()=>{
  250. return res.json({
  251. email: res.locals.owner.email,
  252. name: res.locals.owner.name,
  253. address: res.locals.merchant.address.full
  254. });
  255. })
  256. .catch((err)=>{
  257. if(err.name === "ValidationError") return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  258. return res.json("ERROR: UNABLE TO UPDATE DATA");
  259. });
  260. },
  261. /*
  262. PUT: Update merchant password with current password
  263. req.body = {
  264. current: String (current merchant password),
  265. new: String (new password),
  266. confirm: String (new password again for confirmation)
  267. }
  268. response = {redirect: String (link to redirect to)}
  269. */
  270. changePassword: function(req, res){
  271. if(req.body.new !== req.body.confirm) return res.json("PASSWORDS DO NOT MATCH");
  272. bcrypt.compare(req.body.current, res.locals.owner.password, (err, result)=>{
  273. if(result === true){
  274. let salt = bcrypt.genSaltSync(10);
  275. let hash = bcrypt.hashSync(req.body.new, salt);
  276. res.locals.owner.password = hash;
  277. let newExpiration = new Date();
  278. newExpiration.setDate(newExpiration.getDate() + 90);
  279. res.locals.owner.session.sessionId = helper.generateId(25);
  280. res.locals.owner.session.expiration = newExpiration;
  281. res.locals.owner.save()
  282. .then((owner)=>{
  283. req.session.owner = undefined;
  284. req.session.merchant = undefined;
  285. req.session.success = "PASSWORD RESET. PLEASE LOG IN AGAIN.";
  286. return res.json({redirect: `http://${process.env.SITE}/login`});
  287. })
  288. .catch((err)=>{
  289. return res.json("ERROR: UNABLE TO UPDATE PASSWORD");
  290. });
  291. }else{
  292. return res.json("INCORRECT PASSWORD");
  293. }
  294. });
  295. },
  296. /*
  297. DELETE: remove a merchant from its owner
  298. response = [Owner, Merchant (the next), [Transaction]]
  299. */
  300. deleteMerchant: function(req, res){
  301. if(res.locals.owner.merchants.length === 1) throw "one";
  302. for(let i = 0; i < res.locals.owner.merchants.length; i++){
  303. if(res.locals.owner.merchants[i].toString() === res.locals.merchant._id.toString()){
  304. res.locals.owner.merchants.splice(i, 1);
  305. break;
  306. }
  307. }
  308. res.locals.merchant.removed = true;
  309. let now = new Date();
  310. let then = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  311. let transactions = Transaction.aggregate([
  312. {$match: {
  313. merchant: ObjectId(res.locals.owner.merchants[0]._id),
  314. date: {$gte: then}
  315. }},
  316. {$sort: {date: -1}},
  317. {$project: {
  318. date: 1,
  319. recipes: 1
  320. }}
  321. ]);
  322. Promise.all([
  323. Merchant.findOne({_id: res.locals.owner.merchants[0]._id}).populate("inventory.ingredient").populate("recipes"),
  324. res.locals.owner.save(),
  325. res.locals.merchant.save(),
  326. res.locals.owner.populate("merchants", "name").execPopulate(),
  327. transactions
  328. ])
  329. .then((response)=>{
  330. let responseOwner = {
  331. _id: res.locals.owner._id,
  332. email: res.locals.owner.email,
  333. merchants: res.locals.owner.merchants.slice(1),
  334. name: res.locals.owner.name
  335. };
  336. response[0].owner = undefined;
  337. response[0].createdAt = undefined;
  338. response[0].locationId = undefined;
  339. req.session.merchant = response[0]._id;
  340. return res.json([responseOwner, response[0], response[4]]);
  341. })
  342. .catch((err)=>{
  343. if(err === "one") return res.json("YOU CANNOT DELETE YOUR ONLY MERCHANT");
  344. return res.json("ERROR: UNABLE TO DELETE THE MERCHANT");
  345. });
  346. },
  347. /*
  348. GET: gets a merchant to send back to its owner
  349. req.params.id = String (merchant id)
  350. response = [Owner, Merchant, [Transaction]];
  351. */
  352. getMerchant: function(req, res){
  353. let owner = Owner.findOne({"session.sessionId": req.session.owner}).populate("merchants", "name");
  354. let merchant = Merchant.findOne({_id: req.params.id}).populate("inventory.ingredient").populate("recipes");
  355. let now = new Date();
  356. let then = new Date(now.getFullYear(), now.getMonth() - 1, 1);
  357. let transactions = Transaction.aggregate([
  358. {$match: {
  359. merchant: ObjectId(req.params.id),
  360. date: {$gte: then}
  361. }},
  362. {$sort: {date: -1}},
  363. {$project: {
  364. date: 1,
  365. recipes: 1
  366. }}
  367. ]);
  368. Promise.all([owner, merchant, transactions])
  369. .then((response)=>{
  370. if(response[0] === null || response[1] === null) throw "unfound";
  371. if(response[1].owner.toString() !== response[0]._id.toString()) throw "permissions";
  372. let responseOwner = {
  373. _id: response[0]._id,
  374. email: response[0].email,
  375. merchants: response[0].merchants,
  376. name: response[0].name
  377. };
  378. for(let i = 0; i < responseOwner.merchants.length; i++){
  379. if(response[1]._id.toString() === responseOwner.merchants[i]._id.toString()){
  380. responseOwner.merchants.splice(i, 1);
  381. break;
  382. }
  383. }
  384. response[1].owner = undefined;
  385. response[1].createdAt = undefined;
  386. req.session.merchant = response[1]._id;
  387. return res.json([responseOwner, response[1], response[2]]);
  388. })
  389. .catch((err)=>{
  390. if(err === "unfound") return res.json("UNABLE TO FIND THAT MERCHANT");
  391. if(err === "permissions") return res.json("YOU DO NOT HAVE PERMISSION TO DO THAT");
  392. return res.json("ERROR: UNABLE TO RETRIEVE DATA");
  393. });
  394. }
  395. }