recipeData.js 17 KB

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