merchantData.js 14 KB

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