recipeData.js 17 KB

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