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