recipeData.js 17 KB

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