merchantData.js 11 KB

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