merchantData.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. const Merchant = require("../models/merchant");
  2. const Recipe = require("../models/recipe");
  3. const InventoryAdjustment = require("../models/inventoryAdjustment");
  4. const validator = require("./validator.js");
  5. const helper = require("./helper.js");
  6. const axios = require("axios");
  7. const bcrypt = require("bcryptjs");
  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. /*
  171. POST - Update the quantity for a merchant inventory item
  172. req.body = [{
  173. id: id of ingredient to update,
  174. quantity: change in quantity
  175. }]
  176. */
  177. updateMerchantIngredient: function(req, res){
  178. if(!req.session.user){
  179. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  180. return res.redirect("/");
  181. }
  182. for(let i = 0; i < req.body.length; i++){
  183. let validation = validator.quantity(req.body[i].quantity);
  184. if(validation !== true){
  185. return res.json(validation);
  186. }
  187. }
  188. let adjustments = [];
  189. let changedIngredients = []
  190. Merchant.findOne({_id: req.session.user})
  191. .populate("inventory.ingredient")
  192. .then((merchant)=>{
  193. for(let i = 0; i < req.body.length; i++){
  194. let updateIngredient;
  195. for(let j = 0; j < merchant.inventory.length; j++){
  196. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  197. updateIngredient = merchant.inventory[j];
  198. break;
  199. }
  200. }
  201. adjustments.push(new InventoryAdjustment({
  202. date: Date.now(),
  203. merchant: req.session.user,
  204. ingredient: req.body[i].id,
  205. quantity: req.body[i].quantity - updateIngredient.quantity,
  206. }));
  207. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  208. changedIngredients.push(updateIngredient);
  209. }
  210. return merchant.save();
  211. })
  212. .then((newMerchant)=>{
  213. res.json(changedIngredients);
  214. InventoryAdjustment.create(adjustments).catch(()=>{});
  215. return;
  216. })
  217. .catch((err)=>{
  218. return res.json("ERROR: UNABLE TO UPDATE DATA");
  219. });
  220. },
  221. /*
  222. POST - Changes the users password
  223. req.body = {
  224. pass: new password,
  225. confirmPass: new password confirmation,
  226. hash: hashed version of old password
  227. }
  228. */
  229. updatePassword: function(req, res){
  230. let validation = validator.password(req.body.pass, req.body.confirmPass);
  231. if(validation !== true){
  232. return res.json(validation);
  233. }
  234. Merchant.findOne({password: req.body.hash})
  235. .then((merchant)=>{
  236. if(merchant){
  237. let salt = bcrypt.genSaltSync(10);
  238. let hash = bcrypt.hashSync(req.body.pass, salt);
  239. merchant.password = hash;
  240. return merchant.save();
  241. }else{
  242. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  243. return res.redirect("/");
  244. }
  245. })
  246. .then((merchant)=>{
  247. req.session.error = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  248. return res.redirect("/");
  249. })
  250. .catch((err)=>{});
  251. }
  252. }