recipeData.js 14 KB

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