merchantData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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 merchant = new Merchant({
  35. name: req.body.name,
  36. email: req.body.email.toLowerCase(),
  37. password: hash,
  38. pos: "none",
  39. lastUpdatedTime: Date.now(),
  40. createdAt: Date.now(),
  41. status: ["unverified"],
  42. inventory: [],
  43. recipes: [],
  44. verifyId: helper.generateId(15)
  45. });
  46. merchant.save()
  47. .then((merchant)=>{
  48. return res.redirect(`/verify/email/${merchant._id}`);
  49. })
  50. .catch((err)=>{
  51. if(typeof(err) === "string"){
  52. req.session.error = err;
  53. }else if(err.name === "ValidationError"){
  54. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.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. if(typeof(err) === "string"){
  104. req.session.error = err;
  105. }else if(err.name === "ValidationError"){
  106. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  107. }else{
  108. req.session.error = "ERROR: UNABLE TO RETRIEVE DATA FROM CLOVER";
  109. }
  110. return res.redirect("/");
  111. });
  112. },
  113. createMerchantSquare: function(req, res){
  114. let merchant = {}
  115. axios.get(`${process.env.SQUARE_ADDRESS}/v2/merchants/${req.session.merchantId}`, {
  116. headers: {
  117. Authorization: `Bearer ${req.session.accessToken}`
  118. }
  119. })
  120. .then((response)=>{
  121. req.session.merchantId = undefined;
  122. return new Merchant({
  123. name: response.data.merchant.business_name,
  124. pos: "square",
  125. posId: response.data.merchant.id,
  126. posAccessToken: req.session.accessToken,
  127. lastUpdatedTime: new Date(),
  128. createdAt: new Date(),
  129. squareLocation: response.data.merchant.main_location_id,
  130. inventory: [],
  131. recipes: []
  132. });
  133. })
  134. .then((newMerchant)=>{
  135. req.session.accessToken = undefined;
  136. merchant = newMerchant;
  137. return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  138. object_types: ["ITEM"]
  139. }, {
  140. headers: {
  141. Authorization: `Bearer ${merchant.posAccessToken}`
  142. }
  143. });
  144. })
  145. .then((response)=>{
  146. let recipes = [];
  147. for(let i = 0; i < response.data.objects.length; i++){
  148. if(response.data.objects[i].item_data.variations.length > 1){
  149. for(let j = 0; j < response.data.objects[i].item_data.variations.length; j++){
  150. let recipe = new Recipe({
  151. posId: response.data.objects[i].item_data.variations[j].id,
  152. merchant: merchant._id,
  153. name: `${response.data.objects[i].item_data.name} '${response.data.objects[i].item_data.variations[j].item_variation_data.name}'`,
  154. price: response.data.objects[i].item_data.variations[j].item_variation_data.price_money.amount
  155. });
  156. recipes.push(recipe);
  157. merchant.recipes.push(recipe);
  158. }
  159. }else{
  160. let recipe = new Recipe({
  161. posId: response.data.objects[i].item_data.variations[0].id,
  162. merchant: merchant._id,
  163. name: response.data.objects[i].item_data.name,
  164. price: response.data.objects[i].item_data.variations[0].item_variation_data.price_money.amount,
  165. ingredients: []
  166. });
  167. recipes.push(recipe);
  168. merchant.recipes.push(recipe);
  169. }
  170. }
  171. return Recipe.create(recipes);
  172. })
  173. .then((recipes)=>{
  174. return merchant.save();
  175. })
  176. .then((merchant)=>{
  177. req.session.user = merchant._id;
  178. return res.redirect("/dashboard");
  179. })
  180. .catch((err)=>{
  181. if(typeof(err) === "string"){
  182. req.session.error = err;
  183. }else if(err.name === "ValidationError"){
  184. req.session.error = err.errors[Object.keys(err.errors)[0]].properties.message;
  185. }else{
  186. req.session.error = "ERROR: UNABLE TO CREATE NEW USER";
  187. }
  188. return res.redirect("/");
  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. let adjustments = [];
  204. let changedIngredients = [];
  205. Merchant.findOne({_id: req.session.user})
  206. .populate("inventory.ingredient")
  207. .then((merchant)=>{
  208. for(let i = 0; i < req.body.length; i++){
  209. let updateIngredient;
  210. for(let j = 0; j < merchant.inventory.length; j++){
  211. if(merchant.inventory[j].ingredient._id.toString() === req.body[i].id){
  212. updateIngredient = merchant.inventory[j];
  213. break;
  214. }
  215. }
  216. adjustments.push(new InventoryAdjustment({
  217. date: Date.now(),
  218. merchant: req.session.user,
  219. ingredient: req.body[i].id,
  220. quantity: req.body[i].quantity - updateIngredient.quantity,
  221. }));
  222. updateIngredient.quantity = helper.convertQuantityToBaseUnit(req.body[i].quantity, updateIngredient.defaultUnit);
  223. changedIngredients.push(updateIngredient);
  224. }
  225. return merchant.save();
  226. })
  227. .then((newMerchant)=>{
  228. res.json(changedIngredients);
  229. InventoryAdjustment.create(adjustments).catch(()=>{});
  230. return;
  231. })
  232. .catch((err)=>{
  233. if(typeof(err) === "string"){
  234. return res.json(err);
  235. }
  236. if(err.name === "ValidationError"){
  237. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  238. }
  239. return res.json("ERROR: UNABLE TO UPDATE DATA");
  240. });
  241. },
  242. /*
  243. POST - Changes the users password
  244. req.body = {
  245. pass: new password,
  246. confirmPass: new password confirmation,
  247. hash: hashed version of old password
  248. }
  249. */
  250. updatePassword: function(req, res){
  251. Merchant.findOne({password: req.body.hash})
  252. .then((merchant)=>{
  253. if(merchant){
  254. if(req.body.pass.length < 10){
  255. throw "PASSWORD MUST CONTAIN AT LEAST 10 CHARACTERS";
  256. }
  257. if(req.body.pass !== req.body.confirmPass){
  258. throw "PASSWORDS DO NOT MATCH";
  259. }
  260. let salt = bcrypt.genSaltSync(10);
  261. let hash = bcrypt.hashSync(req.body.pass, salt);
  262. merchant.password = hash;
  263. return merchant.save();
  264. }else{
  265. req.session.error = "ERROR: UNABLE TO RETRIEVE USER DATA";
  266. return res.redirect("/");
  267. }
  268. })
  269. .then((merchant)=>{
  270. req.session.success = "PASSWORD SUCCESSFULLY RESET. PLEASE LOG IN";
  271. return res.redirect("/");
  272. })
  273. .catch((err)=>{
  274. if(typeof(err) === "string"){
  275. return res.json(err);
  276. }
  277. if(err.name === "ValidationError"){
  278. return res.json(err.errors[Object.keys(err.errors)[0]].properties.message);
  279. }
  280. return res.json("ERROR: UNABLE TO UPDATE YOUR PASSWORD");
  281. });
  282. }
  283. }