merchantData.js 14 KB

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