merchantData.js 14 KB

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