recipeData.js 17 KB

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