recipeData.js 17 KB

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