merchantData.js 11 KB

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