Skip to content

Commit

Permalink
get menus and recipes inside
Browse files Browse the repository at this point in the history
  • Loading branch information
jwkaterina committed Apr 16, 2024
1 parent 52b248e commit e9a2ebd
Show file tree
Hide file tree
Showing 12 changed files with 186 additions and 111 deletions.
2 changes: 1 addition & 1 deletion functions/db-controllers/food-controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ const createFood = async (req, res, next) => {
};

const deleteFood = async (req, res, next) => {
const foodId = req.params.pid;
const foodId = req.params.id;

let food;
try {
Expand Down
4 changes: 2 additions & 2 deletions functions/db-controllers/menu-controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ const createMenu = async (req, res, next) => {
const updateMenu = async (req, res, next) => {

const { updatedMenu } = req.body;
const menuId = req.params.pid;
const menuId = req.params.id;
console.log(updatedMenu);

let menu;
Expand Down Expand Up @@ -146,7 +146,7 @@ const updateMenu = async (req, res, next) => {
};

const deleteMenu = async (req, res, next) => {
const menuId = req.params.pid;
const menuId = req.params.id;

let menu;
try {
Expand Down
103 changes: 99 additions & 4 deletions functions/db-controllers/recipe-controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const Recipe = require('../models/recipe');
const User = require('../models/user');
const gcpStorage = require('../storage-controllers/gcpStorage-controllers');

const getRecipes = async (req, res, next) => {
const getAllRecipes = async (req, res, next) => {
const userId = req.userData.userId;

let userWithRecipe;
Expand Down Expand Up @@ -36,6 +36,33 @@ const getRecipes = async (req, res, next) => {
});
};

const getRecipesById = async (req, res, next) => {
const recipeID = req.params.id;
let recipe;
try {
recipe = await Recipe.findById(recipeID);
} catch (err) {
console.error(err);
const error = new HttpError(
'Could not find recipe. Try again later.',
500
);
return next(error);
}

if (!recipe) {
console.error('Could not find recipe by id.');
return next(
new HttpError('Could not find recipe. Try again later.', 404)
);
}

res.json({
recipe: recipe.toObject({ getters: true })
});

}

const createRecipe = async (req, res, next) => {

const { recipe } = req.body;
Expand Down Expand Up @@ -106,7 +133,7 @@ const updateRecipe = async (req, res, next) => {
const updatedRecipe = JSON.parse(recipeString);

const updatedImage = req.image && req.image.url;
const recipeId = req.params.pid;
const recipeId = req.params.id;

let recipe;
try {
Expand Down Expand Up @@ -158,7 +185,7 @@ const updateRecipe = async (req, res, next) => {
};

const deleteRecipe = async (req, res, next) => {
const recipeId = req.params.pid;
const recipeId = req.params.id;

let recipe;
try {
Expand Down Expand Up @@ -211,10 +238,78 @@ const deleteRecipe = async (req, res, next) => {
}
}

try {
await modifyMenus(recipeId, recipe.creator, next);
} catch(err) {
console.error(err);
const error = new HttpError(
'Could not modify menu. Try again later.',
500
);
return next(error);
}

res.status(200).json({ message: 'Deleted recipe.' });
};

exports.getRecipes = getRecipes;
const modifyMenus = async(recipeId, user, next) => {
let userWithMenu;
try {
userWithMenu = await User.findById(user.id).populate('menus');
} catch (err) {
console.error(err);
const error = new HttpError(
'Could not find menu. Try again later.',
500
);
return next(error);
}

if (!userWithMenu) {
console.error('Could not find menu by id.')
return next(
new HttpError('Could not find menu. Try again later.', 404)
);
}
userWithMenu.menus.forEach(async(menu) => {
menu.menu.recipes = menu.menu.recipes.filter(recipe => recipe.selectedRecipe != recipeId);
if(menu.menu.recipes.length == 0 && menu.menu.ingredients.length == 0) {
console.log('empty menu');
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await menu.deleteOne({ session: sess });
user.menus.pull(menu);
await user.save({ session: sess });
await sess.commitTransaction();
return next();

} catch (err) {
console.error(err);
const error = new HttpError(
'Could not delete empty menu. Try again later.',
500
);
return next(error);
}
}
try {
await menu.save();
} catch (err) {
console.error(err);
const error = new HttpError(
'Could not update menu in favorites. Try again later.',
500
);
return next(error);
}
});

next();
}

exports.getAllRecipes = getAllRecipes;
exports.getRecipesById = getRecipesById;
exports.createRecipe = createRecipe;
exports.updateRecipe = updateRecipe;
exports.deleteRecipe = deleteRecipe;
65 changes: 4 additions & 61 deletions functions/models/menu.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,73 +2,16 @@ const mongoose = require('mongoose');

const Schema = mongoose.Schema;

const Nutrient = new Schema({
label: { type: String, required: true },
quantity: { type: Number, required: true },
unit: { type: String, required: true }
})

const Nutrients = new Schema({
CA: { type: Nutrient, required: false },
CHOCDF: { type: Nutrient, required: false },
CHOLE: { type: Nutrient, required: false },
ENERC_KCAL: { type: Nutrient, required: false },
FAMS: { type: Nutrient, required: false },
FAPU: { type: Nutrient, required: false },
FASAT: { type: Nutrient, required: false },
FAT: { type: Nutrient, required: false },
FATRN: { type: Nutrient, required: false },
FE: { type: Nutrient, required: false },
FIBTG: { type: Nutrient, required: false },
FOLAC: { type: Nutrient, required: false },
FOLDFE: { type: Nutrient, required: false },
FOLFD: { type: Nutrient, required: false },
K: { type: Nutrient, required: false },
MG: { type: Nutrient, required: false },
NA: { type: Nutrient, required: false },
NIA: { type: Nutrient, required: false },
P: { type: Nutrient, required: false },
PROCNT: { type: Nutrient, required: false },
RIBF: { type: Nutrient, required: false },
SUGAR: { type: Nutrient, required: false },
THIA: { type: Nutrient, required: false },
TOCPHA: { type: Nutrient, required: false },
VITA_RAE: { type: Nutrient, required: false },
VITB12: { type: Nutrient, required: false },
VITB6A: { type: Nutrient, required: false },
VITC: { type: Nutrient, required: false },
VITD: { type: Nutrient, required: false },
VITK1: { type: Nutrient, required: false },
WATER: { type: Nutrient, required: false },
ZN: { type: Nutrient, required: false }
})

const Recipe = new Schema({
selectedRecipe: {
name: { type: String, required: true },
image: { type: String, required: false },
servings: { type: Number, required: true },
ingredients: [{ type: String, required: true }],
nutrients: {
calories: { type: Number, required: true },
totalNutrients: { type: Nutrients, required: true },
totalDaily: { type: Nutrients, required: true },
totalWeight: { type: Number, required: true }
}},
selectedServings: { type: Number, required: false },
const MenuRecipe = new Schema({
selectedRecipe: { type: mongoose.Types.ObjectId, required: true, ref: 'Recipe'},
selectedServings: { type: Number, required: true },
})

const menuSchema = new Schema({
menu:{
name: { type: String, required: true },
ingredients: [{ type: String, required: false }],
nutrients: {
calories: { type: Number, required: true },
totalNutrients: { type: Nutrients, required: true },
totalDaily: { type: Nutrients, required: true },
totalWeight: { type: Number, required: true }
},
recipes: [{ type: Recipe, required: false}],
recipes: [{ type: MenuRecipe, required: false}],
},
creator: { type: mongoose.Types.ObjectId, required: true, ref: 'User'}
});
Expand Down
2 changes: 1 addition & 1 deletion functions/routes/food-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ router.post(
'/', foodControllers.createFood
);

router.delete('/:pid', foodControllers.deleteFood);
router.delete('/:id', foodControllers.deleteFood);

module.exports = router;
4 changes: 2 additions & 2 deletions functions/routes/menu-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@ router.post(
'/', menuControllers.createMenu
);

router.patch('/:pid', menuControllers.updateMenu);
router.patch('/:id', menuControllers.updateMenu);

router.delete('/:pid', menuControllers.deleteMenu);
router.delete('/:id', menuControllers.deleteMenu);

module.exports = router;
8 changes: 5 additions & 3 deletions functions/routes/recipe-routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@ const checkAuth = require('../middleware/check-auth');
const router = express.Router();
router.use(checkAuth);

router.get('/', recipeControllers.getRecipes);
router.get('/', recipeControllers.getAllRecipes);

router.get('/:id', recipeControllers.getRecipesById);

router.post(
'/',
Expand All @@ -19,13 +21,13 @@ router.post(
);

router.patch(
'/:pid',
'/:id',
multer.all,
compress.compressFile,
gcpStorageControllers.putImage,
recipeControllers.updateRecipe
);

router.delete('/:pid', recipeControllers.deleteRecipe);
router.delete('/:id', recipeControllers.deleteRecipe);

module.exports = router;
8 changes: 4 additions & 4 deletions src/app/analysis/components/form/menu-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ const MenuForm = ({ searchCleared, setClearSearch }: MenuFormProps): JSX.Element
setMessage('You do not have any favorite recipes.');
} else {
setLoadedRecipes(recipes);
setInputsnumber(inputsnumber + 1);
}
} catch (err) {
setIsLoading(false);
Expand Down Expand Up @@ -82,7 +81,9 @@ const MenuForm = ({ searchCleared, setClearSearch }: MenuFormProps): JSX.Element
setInputsnumber(currentMenu.menu.recipes.length);
setCurrentRecipes(currentMenu.menu.recipes);
}
if(currentMenu.menu && currentMenu.mode == AnalysisMode.EDIT && currentMenu.menu.recipes.length > 0) fetchRecipes();
if(currentMenu.menu && currentMenu.mode == AnalysisMode.EDIT && currentMenu.menu.recipes.length > 0) {
fetchRecipes();
}
}, [currentMenu]);

const ArrayfromString = (string: string): string[] => {
Expand Down Expand Up @@ -146,14 +147,13 @@ const MenuForm = ({ searchCleared, setClearSearch }: MenuFormProps): JSX.Element
}

const handleAddRecipe = async() => {
console.log(loadedRecipes);
console.log(currentRecipes);
if(!token) {
setStatus(StatusType.ERROR);
setMessage('You need to be logged in to add a recipe');
return;
}
fetchRecipes();
setInputsnumber(inputsnumber + 1);
}

if(currentMenu.menu && cardOpen == CardState.OPEN) return (
Expand Down
32 changes: 5 additions & 27 deletions src/app/analysis/components/form/recipe-form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ const RecipeForm = ({ searchCleared, setClearSearch, setFile }: RecipeFormProps)
setIsLoading(false);
return;
}
if(await menusWithRecipe()) return;
if(!confirmed()) return;

try {
await sendRequest(
Expand All @@ -119,35 +119,13 @@ const RecipeForm = ({ searchCleared, setClearSearch, setFile }: RecipeFormProps)
} catch (err) {}
}

const menusWithRecipe = async() => {
if(deleteReady) return false;

const responseData = await sendRequest(
`/menus`,'GET', null, {
Authorization: 'Bearer ' + token
}, true, false
);
const menus = () => {
if (!responseData.menus || !responseData.menus.length) {
return null;
}
for (const menu of responseData.menus) {
if (menu.menu.recipes.length > 0) {
const matchingRecipe = menu.menu.recipes.find((recipe: RecipeWithServings) => recipe.selectedRecipe.name === currentRecipe.recipe?.name);
if (matchingRecipe) {
return menu;
}
}
}
//TODO: delete menu
return null;
}
if(!menus()) return false;
const confirmed = () => {
if(deleteReady) return true;

setStatus(StatusType.ERROR);
setMessage('Menus with this recipe will be deleted as well. If you agree press delete button again');
setMessage('Menus with this recipe will be modified. If you agree press delete button again');
setDeleteReady(true);
return true;
return false;
}

const handleNameInput = (e: React.FormEvent<HTMLInputElement>) => {
Expand Down
Loading

0 comments on commit e9a2ebd

Please sign in to comment.