recipeData.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372
  1. const Recipe = require("../models/recipe.js");
  2. const Merchant = require("../models/merchant.js");
  3. const ArchivedRecipe = require("../models/archivedRecipe.js");
  4. const validator = require("./validator.js");
  5. const axios = require("axios");
  6. const xlsx = require("xlsx");
  7. const fs = require("fs");
  8. module.exports = {
  9. /*
  10. POST - creates a single new recipe
  11. req.body = {
  12. name: name of recipe,
  13. price: price of the recipe,
  14. ingredients: [{
  15. id: id of ingredient,
  16. quantity: quantity of ingredient in recipe
  17. }]
  18. }
  19. Return = newly created recipe in same form as above, with _id
  20. */
  21. createRecipe: function(req, res){
  22. if(!req.session.user){
  23. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  24. return res.redirect("/");
  25. }
  26. let validation = validator.recipe(req.body);
  27. if(validation !== true){
  28. return res.json(validation);
  29. }
  30. let recipe = new Recipe({
  31. merchant: req.session.user,
  32. name: req.body.name,
  33. price: Math.round(req.body.price * 100),
  34. ingredients: req.body.ingredients
  35. });
  36. Merchant.findOne({_id: req.session.user})
  37. .then((merchant)=>{
  38. merchant.recipes.push(recipe);
  39. merchant.save()
  40. .catch((err)=>{
  41. return res.json("ERROR: UNABLE TO SAVE RECIPE");
  42. });
  43. })
  44. .catch((err)=>{
  45. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  46. });
  47. recipe.save()
  48. .then((newRecipe)=>{
  49. return res.json(newRecipe);
  50. })
  51. .catch((err)=>{
  52. return res.json("ERROR: UNABLE TO SAVE INGREDIENT");
  53. });
  54. },
  55. /*
  56. PUT - Update a single recipe
  57. req.body = {
  58. id: id of recipe,
  59. name: name of recipe,
  60. price: price of recipe,
  61. ingredients: [{
  62. ingredient: id of ingredient,
  63. quantity: quantity of ingredient in recipe
  64. }]
  65. }
  66. */
  67. updateRecipe: function(req, res){
  68. if(!req.session.user){
  69. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  70. return res.redirect("/");
  71. }
  72. let validation = validator.recipe(req.body);
  73. if(validation !== true){
  74. return res.json(validation);
  75. }
  76. Recipe.findOne({_id: req.body.id})
  77. .then((recipe)=>{
  78. new ArchivedRecipe({
  79. merchant: req.session.user,
  80. name: recipe.name,
  81. price: recipe.price,
  82. date: new Date(),
  83. ingredients: recipe.ingredients
  84. }).save().catch(()=>{});
  85. recipe.name = req.body.name;
  86. recipe.price = req.body.price;
  87. recipe.ingredients = req.body.ingredients;
  88. return recipe.save();
  89. })
  90. .then((recipe)=>{
  91. res.json(recipe);
  92. })
  93. .catch((err)=>{
  94. return res.json("ERROR: UNABLE TO UPDATE RECIPE");
  95. });
  96. },
  97. //DELETE - removes a single recipe from the merchant and the database
  98. removeRecipe: function(req, res){
  99. if(!req.session.user){
  100. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  101. return res.redirect("/");
  102. }
  103. Merchant.findOne({_id: req.session.user})
  104. .then((merchant)=>{
  105. if(merchant.pos === "clover"){
  106. return res.json("YOU MUST EDIT YOUR RECIPES INSIDE CLOVER");
  107. }
  108. for(let i = 0; i < merchant.recipes.length; i++){
  109. if(merchant.recipes[i].toString() === req.params.id){
  110. merchant.recipes.splice(i, 1);
  111. break;
  112. }
  113. }
  114. merchant.save()
  115. .catch((err)=>{
  116. return res.json("ERROR: UNABLE TO SAVE DATA");
  117. })
  118. return Recipe.deleteOne({_id: req.params.id});
  119. })
  120. .then((response)=>{
  121. return res.json({});
  122. })
  123. .catch((err)=>{
  124. return res.json("ERROR: UNABLE TO RETRIEVE USER DATA");
  125. });
  126. },
  127. //GET - Checks clover for new or deleted recipes
  128. //Returns:
  129. // merchant: Full merchant (recipe ingredients populated)
  130. // count: Number of new recipes
  131. updateRecipesClover: function(req, res){
  132. if(!req.session.user){
  133. req.session.error = "Must be logged in to do that";
  134. return res.redirect("/");
  135. }
  136. let merchant = {};
  137. let newRecipes = [];
  138. let deletedRecipes = []
  139. Merchant.findOne({_id: req.session.user})
  140. .populate("recipes")
  141. .then((response)=>{
  142. merchant = response;
  143. return axios.get(`https://apisandbox.dev.clover.com/v3/merchants/${merchant.posId}/items?access_token=${merchant.posAccessToken}`);
  144. })
  145. .then((result)=>{
  146. deletedRecipes = merchant.recipes.slice();
  147. for(let i = 0; i < result.data.elements.length; i++){
  148. for(let j = 0; j < deletedRecipes.length; j++){
  149. if(result.data.elements[i].id === deletedRecipes[j].posId){
  150. result.data.elements.splice(i, 1);
  151. deletedRecipes.splice(j, 1);
  152. i--;
  153. break;
  154. }
  155. }
  156. }
  157. for(let i = 0; i < deletedRecipes.length; i++){
  158. for(let j = 0; j < merchant.recipes.length; j++){
  159. if(deletedRecipes[i]._id === merchant.recipes[j]._id){
  160. merchant.recipes.splice(j, 1);
  161. break;
  162. }
  163. }
  164. }
  165. for(let i = 0; i < result.data.elements.length; i++){
  166. let newRecipe = new Recipe({
  167. posId: result.data.elements[i].id,
  168. merchant: merchant._id,
  169. name: result.data.elements[i].name,
  170. ingredients: [],
  171. price: result.data.elements[i].price
  172. });
  173. merchant.recipes.push(newRecipe);
  174. newRecipes.push(newRecipe);
  175. }
  176. Recipe.create(newRecipes).catch((err)=>{});
  177. return merchant.save();
  178. })
  179. .then((newMerchant)=>{
  180. return res.json({new: newRecipes, removed: deletedRecipes});
  181. })
  182. .catch((err)=>{
  183. return res.json("ERROR: UNABLE TO RETRIEVE MERCHANT DATA");
  184. });
  185. },
  186. updateRecipesSquare: function(req, res){
  187. if(!req.session.user){
  188. req.session.error = "Must be logged in to do that";
  189. return res.redirect("/");
  190. }
  191. let merchant = {};
  192. let merchantRecipes = [];
  193. let newRecipes = [];
  194. Merchant.findOne({_id: req.session.user})
  195. .populate("recipes")
  196. .then((fetchedMerchant)=>{
  197. merchant = fetchedMerchant;
  198. return axios.post(`${process.env.SQUARE_ADDRESS}/v2/catalog/search`, {
  199. object_types: ["ITEM"]
  200. }, {
  201. headers: {
  202. Authorization: `Bearer ${merchant.posAccessToken}`
  203. }
  204. });
  205. })
  206. .then((response)=>{
  207. merchantRecipes = merchant.recipes.slice();
  208. for(let i = 0; i < response.data.objects.length; i++){
  209. let itemData = response.data.objects[i].item_data;
  210. for(let j = 0; j < itemData.variations.length; j++){
  211. let isFound = false;
  212. for(let k = 0; k < merchantRecipes.length; k++){
  213. if(itemData.variations[j].id === merchantRecipes[k].posId){
  214. merchantRecipes.splice(k, 1);
  215. k--;
  216. isFound = true;
  217. break;
  218. }
  219. }
  220. if(!isFound){
  221. let newRecipe = new Recipe({
  222. posId: itemData.variations[j].id,
  223. merchant: merchant._id,
  224. name: "",
  225. price: itemData.variations[j].item_variation_data.price_money.amount,
  226. ingredients: []
  227. });
  228. if(itemData.variations.length > 1){
  229. newRecipe.name = `${itemData.name} '${itemData.variations[j].item_variation_data.name}'`;
  230. }else{
  231. newRecipe.name = itemData.name;
  232. }
  233. newRecipes.push(newRecipe);
  234. merchant.recipes.push(newRecipe);
  235. }
  236. }
  237. }
  238. let ids = [];
  239. for(let i = 0; i < merchantRecipes.length; i++){
  240. ids.push(merchantRecipes[i]._id);
  241. for(let j = 0; j < merchant.recipes.length; j++){
  242. if(merchantRecipes[i]._id.toString() === merchant.recipes[j]._id.toString()){
  243. merchant.recipes.splice(j, 1);
  244. j--;
  245. break;
  246. }
  247. }
  248. }
  249. if(newRecipes.length > 0){
  250. Recipe.create(newRecipes);
  251. }
  252. if(merchantRecipes.length > 0){
  253. Recipe.deleteMany({_id: {$in: ids}});
  254. }
  255. return merchant.save();
  256. })
  257. .then((merchant)=>{
  258. return res.json({new: newRecipes, removed: merchantRecipes});
  259. })
  260. .catch((err)=>{
  261. return "ERROR: UNABLE TO RETRIEVE RECIPE DATA FROM SQUARE";
  262. });
  263. },
  264. createFromSpreadsheet: function(req, res){
  265. if(!req.session.user){
  266. req.session.error = "MUST BE LOGGED IN TO DO THAT";
  267. return res.redirect("/");
  268. }
  269. console.log(req.file);
  270. //read file, get the correct sheet, create array from sheet
  271. let workbook = xlsx.readFile(req.file.path);
  272. fs.unlink(req.file.path, ()=>{});
  273. let sheets = Object.keys(workbook.Sheets);
  274. let sheet = {};
  275. for(let i = 0; i < sheets.length; i++){
  276. let str = sheets[i].toLowerCase();
  277. if(str === "recipe" || str === "recipes"){
  278. sheet = workbook.Sheets[sheets[i]];
  279. }
  280. }
  281. const array = xlsx.utils.sheet_to_json(sheet, {
  282. header: 1
  283. });
  284. //get property locations
  285. let locations = {};
  286. for(let i = 0; i < array[0].length; i++){
  287. switch(array[0][i].toLowerCase()){
  288. case "name": locations.name = i; break;
  289. case "price": locations.price = i; break;
  290. }
  291. }
  292. //Create Recipes
  293. let merchant = {};
  294. let newRecipes = [];
  295. return Merchant.findOne({_id: user})
  296. .then((response)=>{
  297. merchant = response;
  298. let recipes = [];
  299. for(let i = 1; i < array.length; i++){
  300. recipes.push({
  301. name: array[i][locations.name],
  302. price: parseInt(array[i][locations.price] * 100),
  303. merchant: merchant
  304. });
  305. }
  306. return Recipe.create(recipes)
  307. })
  308. .then((recipes)=>{
  309. for(let i = 0; i < recipes.length; i++){
  310. merchant.recipes.push(recipes[i]);
  311. recipes[i].merchant = undefined;
  312. newRecipes.push(recipes[i]);
  313. }
  314. return merchant.save();
  315. })
  316. .then((merchant)=>{
  317. return newRecipes;
  318. })
  319. .catch((err)=>{
  320. return "ERROR: UNABLE TO CREATE RECIPES";
  321. });
  322. }
  323. }