recipeData.js 17 KB

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