recipeData.js 17 KB

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