merchantData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. const Merchant = require("../models/merchant");
  2. const Recipe = require("../models/recipe");
  3. const InventoryAdjustment = require("../models/inventoryAdjustment");
  4. const helper = require("./helper.js");
  5. const axios = require("axios");
  6. const bcrypt = require("bcryptjs");
  7. module.exports = {
  8. /*
  9. POST - Create a new merchant with no POS system1
  10. req.body = {
  11. name: retaurant name,
  12. email: registration email,
  13. password: password,
  14. confirmPassword: confirmation password
  15. }
  16. Redirects to /dashboard
  17. */
  18. createMerchantNone: async function(req, res){
  19. if(req.body.password.length < 10){
  20. req.session.error = "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  21. return res.redirect("/");
  22. }
  23. if(req.body.password !== req.body.confirmPassword){
  24. req.session.error = "PASSWORDS DO NOT MATCH";
  25. return res.redirect("/");
  26. }
  27. const merchantFind = await Merchant.findOne({email: req.body.email.toLowerCase()});
  28. if(merchantFind !== null){
  29. req.session.error = "USER WITH THIS EMAIL ADDRESS ALREADY EXISTS";
  30. return res.redirect("/");
  31. }
  32. let salt = bcrypt.genSaltSync(10);
  33. let hash = bcrypt.hashSync(req.body.password, salt);
  34. let expirationDate = new Date();
  35. expirationDate.setDate(expirationDate.getDate() + 90);
  36. let merchant = new Merchant({
  37. name: req.body.name,
  38. email: req.body.email.toLowerCase(),
  39. password: hash,
  40. pos: "none",
  41. lastUpdatedTime: Date.now(),
  42. createdAt: Date.now(),
  43. status: ["unverified"],
  44. inventory: [],
  45. recipes: [],
  46. verifyId: helper.generateId(15),
  47. session: {
  48. sessionId: helper.generateId(25),
  49. expiration: expirationDate
  50. }
  51. });
  52. merchant.save()
  53. .then((merchant)=>{
  54. return res.redirect(`/verify/email/${merchant._id}`);
  55. })
  56. .catch((err)=>{
  57. if(typeof(err) === "string"){
  58. req.session.error = err;
  59. }else if(err.name === "ValidationError"){
  60. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  61. }else{
  62. req.session.error = "ERROR: UNABLE TO CREATE ACCOUNT AT THIS TIME";
  63. }
  64. return res.redirect("/");
  65. });
  66. },
  67. /*
  68. POST - Creates new Clover merchant
  69. Redirects to /dashboard
  70. */
  71. createMerchantClover: async function(req, res){
  72. let merchant = {}
  73. axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}?access_token=${req.session.accessToken}`)
  74. .then((response)=>{
  75. merchant = new Merchant({
  76. name: response.data.name,
  77. pos: "clover",
  78. posId: req.session.merchantId,
  79. posAccessToken: req.session.accessToken,
  80. lastUpdatedTime: Date.now(),
  81. createdAt: Date.now(),
  82. inventory: [],
  83. recipes: []
  84. });
  85. return axios.get(`${process.env.CLOVER_ADDRESS}/v3/merchants/${req.session.merchantId}/items?access_token=${req.session.accessToken}`);
  86. })
  87. .then((response)=>{
  88. let recipes = [];
  89. for(let i = 0; i < response.data.elements.length; i++){
  90. let recipe = new Recipe({
  91. posId: response.data.elements[i].id,
  92. merchant: merchant,
  93. name: response.data.elements[i].name,
  94. price: response.data.elements[i].price,
  95. ingredients: []
  96. });
  97. recipes.push(recipe);
  98. merchant.recipes.push(recipe);
  99. }
  100. Recipe.create(recipes).catch((err)=>{});
  101. return merchant.save();
  102. })
  103. .then((newMerchant)=>{
  104. req.session.accessToken = undefined;
  105. req.session.user = newMerchant._id;
  106. return res.redirect("/dashboard");
  107. })
  108. .catch((err)=>{
  109. if(typeof(err) === "string"){
  110. req.session.error = err;
  111. }else if(err.name === "ValidationError"){
  112. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  113. }else{
  114. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  115. }
  116. return res.redirect("/");
  117. });
  118. },
  119. createMerchantSquare: function(req, res){
  120. let merchant = {}
  121. axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
  122. headers: {
  123. Authorization: `Bearer ${req.session.accessToken}`
  124. }
  125. })
  126. .then((response)=>{
  127. req.session.merchantId = undefined;
  128. return new Merchant({
  129. name: response.data.merchant.business_name,
  130. pos: "square",
  131. posId: response.data.merchant.id,
  132. posAccessToken: req.session.accessToken,
  133. lastUpdatedTime: new Date(),
  134. createdAt: new Date(),
  135. squareLocation: response.data.merchant.main_location_id,
  136. inventory: [],
  137. recipes: []
  138. });
  139. })
  140. .then((newMerchant)=>{
  141. req.session.accessToken = undefined;
  142. merchant = newMerchant;
  143. return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  144. object_types: ["ITEM"]
  145. }, {
  146. headers: {
  147. Authorization: `Bearer ${merchant.posAccessToken}`
  148. }
  149. });
  150. })
  151. .then((response)=>{
  152. let recipes = [];
  153. for(let i = 0; i < response.data.objects.length; i++){
  154. if(response.data.objects[i].item_data.variations.length > 1){
  155. for(let j = 0; j < response.data.objects[i].item_data.variations.length; j++){
  156. let recipe = new Recipe({
  157. posId: response.data.objects[i].item_data.variations[j].id,
  158. merchant: merchant._id,
  159. name: `${response.data.objects[i].item_data.name} '${response.data.objects[i].item_data.variations[j].item_variation_data.name}'`,
  160. price: response.data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
  161. });
  162. recipes.push(recipe);
  163. merchant.recipes.push(recipe);
  164. }
  165. }else{
  166. let recipe = new Recipe({
  167. posId: response.data.objects[i].item_data.variations[0].id,
  168. merchant: merchant._id,
  169. name: response.data.objects[i].item_data.name,
  170. price: response.data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
  171. ingredients: []
  172. });
  173. recipes.push(recipe);
  174. merchant.recipes.push(recipe);
  175. }
  176. }
  177. return Recipe.create(recipes);
  178. })
  179. .then((recipes)=>{
  180. return merchant.save();
  181. })
  182. .then((merchant)=>{
  183. req.session.user = merchant._id;
  184. return res.redirect("/dashboard");
  185. })
  186. .catch((err)=>{
  187. if(typeof(err) === "string"){
  188. req.session.error = err;
  189. }else if(err.name === "ValidationError"){
  190. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  191. }else{
  192. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  193. }
  194. return res.redirect("/");
  195. });
  196. },
  197. /*
  198. POST - Update the quantity for a merchant inventory item
  199. req.body = [{
  200. id: id of ingredient to update,
  201. quantity: change in quantity
  202. }]
  203. */
  204. updateMerchantIngredient: function(req, res){
  205. if(!req.session.user){
  206. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  207. return res.redirect("/");
  208. }
  209. let adjustments = [];
  210. let changedIngredients = [];
  211. Merchant.findOne({_id: req.session.user})
  212. .populate("inventory.ingredient")
  213. .then((merchant)=>{
  214. for(let i = 0; i < req.body.length; i++){
  215. let updateIngredient;
  216. for(let j = 0; j < merchant.inventory.length; j++){
  217. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  218. updateIngredient = merchant.inventory[j];
  219. break;
  220. }
  221. }
  222. adjustments.push(new InventoryAdjustment({
  223. date: Date.now(),
  224. merchant: req.session.user,
  225. ingredient: req.body[i].id,
  226. quantity: req.body[i].quantity - updateIngredient.quantity,
  227. }));
  228. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  229. changedIngredients.push(updateIngredient);
  230. }
  231. return merchant.save();
  232. })
  233. .then((newMerchant)=>{
  234. res.json(changedIngredients);
  235. InventoryAdjustment.create(adjustments).catch(()=>{});
  236. return;
  237. })
  238. .catch((err)=>{
  239. if(typeof(err) === "string"){
  240. return res.json(err);
  241. }
  242. if(err.name === "ValidationError"){
  243. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  244. }
  245. return res.json("ERROR: UNABLE TO UPDATE DATA");
  246. });
  247. },
  248. /*
  249. POST - Changes the users password
  250. req.body = {
  251. pass: new password,
  252. confirmPass: new password confirmation,
  253. hash: hashed version of old password
  254. }
  255. */
  256. updatePassword: function(req, res){
  257. Merchant.findOne({password: req.body.hash})
  258. .then((merchant)=>{
  259. if(merchant){
  260. if(req.body.pass.length < 10){
  261. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  262. }
  263. if(req.body.pass !== req.body.confirmPass){
  264. throw "PASSWORDS DO NOT MATCH";
  265. }
  266. let salt = bcrypt.genSaltSync(10);
  267. let hash = bcrypt.hashSync(req.body.pass, salt);
  268. merchant.password = hash;
  269. return merchant.save();
  270. }else{
  271. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  272. return res.redirect("/");
  273. }
  274. })
  275. .then((merchant)=>{
  276. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  277. return res.redirect("/");
  278. })
  279. .catch((err)=>{
  280. if(typeof(err) === "string"){
  281. return res.json(err);
  282. }
  283. if(err.name === "ValidationError"){
  284. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  285. }
  286. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  287. });
  288. }
  289. }