merchantData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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});
  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. return res.json([responseOwner, response[1], response[2]]);
  37. })
  38. .catch((err)=>{
  39. console.log(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. return res.json([owner, response[1]]);
  136. })
  137. .catch((err)=>{
  138. if(err.name === "ValidationError"){
  139. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  140. }
  141. return res.json("ERROR: UNABLE TO CREATE NEW MERCHANT");
  142. });
  143. },
  144. /*
  145. POST - Update the quantity for a merchant inventory item
  146. req.body = [{
  147. id: id of ingredient to update,
  148. quantity: change in quantity
  149. }]
  150. */
  151. updateIngredientQuantities: function(req, res){
  152. let adjustments = [];
  153. let changedIngredients = [];
  154. res.locals.merchant
  155. .populate("inventory.ingredient")
  156. .execPopulate()
  157. .then((merchant)=>{
  158. for(let i = 0; i < req.body.length; i++){
  159. let updateIngredient;
  160. for(let j = 0; j < merchant.inventory.length; j++){
  161. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  162. updateIngredient = merchant.inventory[j];
  163. break;
  164. }
  165. }
  166. adjustments.push(new InventoryAdjustment({
  167. date: Date.now(),
  168. merchant: req.session.owner,
  169. ingredient: req.body[i].id,
  170. quantity: req.body[i].quantity - updateIngredient.quantity,
  171. }));
  172. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  173. changedIngredients.push(updateIngredient);
  174. }
  175. return merchant.save();
  176. })
  177. .then((newMerchant)=>{
  178. res.json(changedIngredients);
  179. InventoryAdjustment.create(adjustments).catch(()=>{});
  180. return;
  181. })
  182. .catch((err)=>{
  183. if(typeof(err) === "string"){
  184. return res.json(err);
  185. }
  186. if(err.name === "ValidationError"){
  187. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  188. }
  189. return res.json("ERROR: UNABLE TO UPDATE DATA");
  190. });
  191. },
  192. /*
  193. POST - Changes the users password
  194. req.body = {
  195. pass: new password,
  196. confirmPass: new password confirmation,
  197. hash: hashed version of old password
  198. }
  199. */
  200. updatePassword: function(req, res){
  201. Merchant.findOne({password: req.body.hash})
  202. .then((merchant)=>{
  203. if(merchant){
  204. if(req.body.pass.length < 10){
  205. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  206. }
  207. if(req.body.pass !== req.body.confirmPass){
  208. throw "PASSWORDS DO NOT MATCH";
  209. }
  210. let salt = bcrypt.genSaltSync(10);
  211. let hash = bcrypt.hashSync(req.body.pass, salt);
  212. merchant.password = hash;
  213. return merchant.save();
  214. }else{
  215. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA";
  216. return res.redirect("/");
  217. }
  218. })
  219. .then((merchant)=>{
  220. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  221. return res.redirect("/login");
  222. })
  223. .catch((err)=>{
  224. if(typeof(err) === "string"){
  225. return res.json(err);
  226. }
  227. if(err.name === "ValidationError"){
  228. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  229. }
  230. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  231. });
  232. },
  233. /*
  234. PUT: Update merchant data
  235. req.body = {
  236. email: String (merchant email address)
  237. },
  238. response = Merchant
  239. */
  240. updateData: async function(req, res){
  241. if(req.body.email !== res.locals.merchant.email){
  242. let merchantCheck = await Merchant.findOne({email: req.body.email});
  243. if(merchantCheck !== null){
  244. return res.json("USER WITH THIS EMAIL ADDRESS ALREADY EXISTS");
  245. }
  246. res.locals.merchant.email = req.body.email;
  247. res.locals.merchant.status.push("unverified");
  248. const mailgunData = {
  249. from: "The Subline <clientsupport@thesubline.net>",
  250. to: res.locals.merchant.email,
  251. subject: "Email Verification",
  252. html: verifyEmail({
  253. name: res.locals.merchant.name,
  254. link: `${process.env.SITE}/verify/${res.locals.merchant._id}/${res.locals.merchant.sessionId}`
  255. })
  256. };
  257. mailgun.messages().send(mailgunData, (err, body)=>{});
  258. }
  259. res.locals.merchant.save()
  260. .then((merchant)=>{
  261. return res.json(merchant);
  262. })
  263. .catch((err)=>{
  264. if(err.name === "ValidationError"){
  265. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  266. }
  267. return res.json("ERROR: UNABLE TO UPDATE DATA");
  268. });
  269. },
  270. /*
  271. PUT: Update merchant password with current password
  272. req.body = {
  273. current: String (current merchant password),
  274. new: String (new password),
  275. confirm: String (new password again for confirmation)
  276. }
  277. response = {redirect: String (link to redirect to)}
  278. */
  279. changePassword: function(req, res){
  280. if(req.body.new !== req.body.confirm){
  281. return res.json("PASSWORDS DO NOT MATCH");
  282. }
  283. bcrypt.compare(req.body.current, res.locals.merchant.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.merchant.password = hash;
  288. let newExpiration = new Date();
  289. newExpiration.setDate(newExpiration.getDate() + 90);
  290. res.locals.merchant.session.sessionId = helper.generateId(25);
  291. res.locals.merchant.session.expiration = newExpiration;
  292. res.locals.merchant.save()
  293. .then((merchant)=>{
  294. req.session.error = "PLEASE LOG IN";
  295. return res.json({redirect: `http://${process.env.SITE}/login`});
  296. })
  297. .catch((err)=>{
  298. return res.json("ERROR: UNABLE TO UPDATE PASSWORD");
  299. });
  300. }else{
  301. return res.json("INCORRECT PASSWORD");
  302. }
  303. });
  304. }
  305. }