diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java b/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java new file mode 100644 index 0000000..6ac4b23 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/controller/RecipeController.java @@ -0,0 +1,163 @@ +package edu.csumb.cst438.api.controller; + +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.UserRepository; +import edu.csumb.cst438.api.service.RecipeService; +import jakarta.validation.Valid; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; +import org.springframework.data.domain.Sort; +import org.springframework.data.web.PagedModel; +import org.springframework.http.ResponseEntity; +import org.springframework.security.core.Authentication; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; + +@RestController +@RequestMapping("/api/v1/recipes") +public class RecipeController { + + private final RecipeService recipeService; + private final UserRepository userRepository; + + public RecipeController( + RecipeService recipeService, + UserRepository userRepository) { + this.recipeService = recipeService; + this.userRepository = userRepository; + } + + @GetMapping + public PagedModel listRecipes( + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size, + @RequestParam(defaultValue = "createdAt,desc") String sort) { + + if (page < 0) { + throw new IllegalArgumentException( + "Page index must be 0 or greater"); + } + + if (size < 1 || size > 100) { + throw new IllegalArgumentException( + "Page size must be between 1 and 100"); + } + + Pageable pageable = createPageable(page, size, sort); + + return new PagedModel<>( + recipeService.listRecipes(pageable) + ); + } + + @PostMapping + public ResponseEntity createRecipe( + @Valid @RequestBody RecipeCreate request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + RecipeResponse created = + recipeService.createRecipe(request, owner); + + return ResponseEntity + .created(URI.create( + "/api/v1/recipes/" + created.id() + )) + .body(created); + } + + @GetMapping("/{recipeId}") + public RecipeResponse getRecipe(@PathVariable Long recipeId) { + return recipeService.getRecipe(recipeId); + } + + @PutMapping("/{recipeId}") + public RecipeResponse replaceRecipe( + @PathVariable Long recipeId, + @Valid @RequestBody RecipeCreate request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + return recipeService.replaceRecipe( + recipeId, + request, + owner + ); + } + + @PatchMapping("/{recipeId}") + public RecipeResponse patchRecipe( + @PathVariable Long recipeId, + @Valid @RequestBody RecipePatch request, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + return recipeService.patchRecipe( + recipeId, + request, + owner + ); + } + + @DeleteMapping("/{recipeId}") + public ResponseEntity deleteRecipe( + @PathVariable Long recipeId, + Authentication authentication) { + + User owner = getCurrentUser(authentication); + + recipeService.deleteRecipe(recipeId, owner); + + return ResponseEntity.noContent().build(); + } + + private User getCurrentUser(Authentication authentication) { + return userRepository.findByEmail(authentication.getName()) + .orElseThrow(() -> new IllegalArgumentException( + "Authenticated user was not found")); + } + + private Pageable createPageable( + int page, + int size, + String sort) { + + String[] sortParts = sort.split(","); + + if (sortParts.length != 2) { + throw new IllegalArgumentException( + "Sort must use the format field,direction"); + } + + String field = sortParts[0]; + String direction = sortParts[1]; + + if (!field.equals("name") && !field.equals("createdAt")) { + throw new IllegalArgumentException( + "Recipes can only be sorted by name or createdAt"); + } + + if (!direction.equals("asc") && !direction.equals("desc")) { + throw new IllegalArgumentException( + "Sort direction must be asc or desc"); + } + + Sort.Direction sortDirection = + direction.equals("asc") + ? Sort.Direction.ASC + : Sort.Direction.DESC; + + return PageRequest.of( + page, + size, + Sort.by(sortDirection, field) + ); + } +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java new file mode 100644 index 0000000..da7cd2a --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipeCreate.java @@ -0,0 +1,19 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +import java.util.Set; + +public record RecipeCreate( + @NotBlank(message = "Recipe name is required") + String name, + + @NotNull(message = "Ingredient IDs are required") + Set ingredientIds, + + String measurements, + + String instructions +) { +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java new file mode 100644 index 0000000..c6e8965 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipePatch.java @@ -0,0 +1,21 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.Pattern; +import tools.jackson.databind.JsonNode; + +import java.util.Set; + +public record RecipePatch( + @Pattern( + regexp = ".*\\S.*", + message = "Name must not be blank" + ) + String name, + + Set ingredientIds, + + JsonNode measurements, + + JsonNode instructions +) { +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java b/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java new file mode 100644 index 0000000..6a64ba8 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/RecipeResponse.java @@ -0,0 +1,30 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.Recipe; + +import java.time.Instant; +import java.util.Set; +import java.util.stream.Collectors; + +public record RecipeResponse( + Long id, + String name, + Instant createdAt, + Set ingredients, + String measurements, + String instructions +) { + public static RecipeResponse from(Recipe recipe) { + return new RecipeResponse( + recipe.getId(), + recipe.getName(), + recipe.getCreatedAt(), + recipe.getIngredients() + .stream() + .map(IngredientResponse::from) + .collect(Collectors.toSet()), + recipe.getMeasurements(), + recipe.getInstructions() + ); + } +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java b/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java new file mode 100644 index 0000000..f6775f1 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/repository/RecipeRepository.java @@ -0,0 +1,10 @@ +package edu.csumb.cst438.api.repository; + +import edu.csumb.cst438.api.entity.Recipe; +import org.springframework.data.jpa.repository.JpaRepository; + +/** + * Repository for accessing recipes in the database. + */ +public interface RecipeRepository extends JpaRepository { +} \ No newline at end of file diff --git a/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java new file mode 100644 index 0000000..cdc5854 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/service/RecipeService.java @@ -0,0 +1,201 @@ +package edu.csumb.cst438.api.service; + +import tools.jackson.databind.JsonNode; +import edu.csumb.cst438.api.entity.Ingredient; +import edu.csumb.cst438.api.entity.Recipe; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.IngredientRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; +import jakarta.persistence.EntityNotFoundException; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * Provides business logic for recipe operations. + */ +@Service +@Transactional +public class RecipeService { + + private final RecipeRepository recipeRepository; + private final IngredientRepository ingredientRepository; + + public RecipeService( + RecipeRepository recipeRepository, + IngredientRepository ingredientRepository) { + this.recipeRepository = recipeRepository; + this.ingredientRepository = ingredientRepository; + } + + @Transactional(readOnly = true) + public Page listRecipes(Pageable pageable) { + return recipeRepository + .findAll(pageable) + .map(RecipeResponse::from); + } + + public RecipeResponse createRecipe( + RecipeCreate request, + User owner) { + + Set ingredients = + findIngredients(request.ingredientIds()); + + Recipe recipe = new Recipe( + request.name(), + request.measurements(), + request.instructions(), + owner + ); + + ingredients.forEach(recipe::addIngredient); + + return RecipeResponse.from( + recipeRepository.save(recipe) + ); + } + + @Transactional(readOnly = true) + public RecipeResponse getRecipe(Long recipeId) { + Recipe recipe = recipeRepository.findById(recipeId) + .orElseThrow(() -> new EntityNotFoundException( + "Recipe " + recipeId + " not found" + )); + + return RecipeResponse.from(recipe); + } + + public RecipeResponse replaceRecipe( + Long recipeId, + RecipeCreate request, + User owner) { + + Recipe recipe = findOwnedRecipe(recipeId, owner); + + recipe.updateDetails( + request.name(), + request.measurements(), + request.instructions() + ); + + replaceIngredients(recipe, request.ingredientIds()); + + return RecipeResponse.from(recipe); + } + + public RecipeResponse patchRecipe( + Long recipeId, + RecipePatch request, + User owner) { + + Recipe recipe = findOwnedRecipe(recipeId, owner); + + String name = request.name() != null + ? request.name() + : recipe.getName(); + + String measurements = patchValue( + request.measurements(), + recipe.getMeasurements() + ); + + String instructions = patchValue( + request.instructions(), + recipe.getInstructions() + ); + + recipe.updateDetails( + name, + measurements, + instructions + ); + + if (request.ingredientIds() != null) { + replaceIngredients(recipe, request.ingredientIds()); + } + + return RecipeResponse.from(recipe); + } + + public void deleteRecipe(Long recipeId, User owner) { + Recipe recipe = findOwnedRecipe(recipeId, owner); + recipeRepository.delete(recipe); + } + + private Recipe findOwnedRecipe(Long recipeId, User owner) { + Recipe recipe = recipeRepository.findById(recipeId) + .orElseThrow(() -> new EntityNotFoundException( + "Recipe " + recipeId + " not found" + )); + + if (recipe.getOwner() == null + || !recipe.getOwner().getId().equals(owner.getId())) { + throw new EntityNotFoundException( + "Recipe " + recipeId + " not found" + ); + } + + return recipe; + } + + private void replaceIngredients( + Recipe recipe, + Set ingredientIds) { + + Set newIngredients = + findIngredients(ingredientIds); + + Set oldIngredients = + new HashSet<>(recipe.getIngredients()); + + oldIngredients.forEach(recipe::removeIngredient); + newIngredients.forEach(recipe::addIngredient); + } + + private Set findIngredients( + Set ingredientIds) { + + List ingredients = + ingredientRepository.findAllById(ingredientIds); + + if (ingredients.size() != ingredientIds.size()) { + throw new EntityNotFoundException( + "One or more ingredients were not found" + ); + } + + return new HashSet<>(ingredients); + } + + private String patchValue( + JsonNode value, + String currentValue) { + + // Field omitted: preserve the current value. + if (value == null) { + return currentValue; + } + + // Field explicitly set to null: clear the value. + if (value.isNull()) { + return null; + } + + if (!value.isTextual()) { + throw new IllegalArgumentException( + "Recipe text fields must be strings or null" + ); + } + + return value.asText(); + } +} \ No newline at end of file diff --git a/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java new file mode 100644 index 0000000..6b0e569 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/service/RecipeServiceTest.java @@ -0,0 +1,352 @@ +package edu.csumb.cst438.api.service; + +import tools.jackson.databind.node.JsonNodeFactory; +import edu.csumb.cst438.api.entity.Ingredient; +import edu.csumb.cst438.api.entity.Recipe; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.RecipeCreate; +import edu.csumb.cst438.api.record.RecipePatch; +import edu.csumb.cst438.api.record.RecipeResponse; +import edu.csumb.cst438.api.repository.IngredientRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; +import jakarta.persistence.EntityNotFoundException; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Pageable; + +import java.lang.reflect.Field; +import java.util.List; +import java.util.Optional; +import java.util.Set; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.*; + +class RecipeServiceTest { + + private RecipeRepository recipeRepository; + private IngredientRepository ingredientRepository; + private RecipeService recipeService; + + private User owner; + private User otherUser; + private Ingredient flour; + private Ingredient sugar; + private Recipe recipe; + + @BeforeEach + void setUp() throws Exception { + recipeRepository = mock(RecipeRepository.class); + ingredientRepository = mock(IngredientRepository.class); + + recipeService = new RecipeService( + recipeRepository, + ingredientRepository + ); + + owner = new User( + "owner@example.com", + "Owner", + "USER" + ); + + otherUser = new User( + "other@example.com", + "Other User", + "USER" + ); + + setId(owner, 1L); + setId(otherUser, 2L); + + flour = new Ingredient("Flour"); + sugar = new Ingredient("Sugar"); + + setId(flour, 1L); + setId(sugar, 2L); + + recipe = new Recipe( + "Pancakes", + "2 cups", + "Mix and cook.", + owner + ); + + recipe.addIngredient(flour); + setId(recipe, 10L); + } + + @Test + void listRecipesReturnsRecipes() { + Pageable pageable = PageRequest.of(0, 20); + + Page recipePage = + new PageImpl<>(List.of(recipe)); + + when(recipeRepository.findAll(pageable)) + .thenReturn(recipePage); + + Page result = + recipeService.listRecipes(pageable); + + assertEquals(1, result.getTotalElements()); + assertEquals("Pancakes", result.getContent().get(0).name()); + + verify(recipeRepository).findAll(pageable); + } + + @Test + void getRecipeReturnsRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.getRecipe(10L); + + assertEquals(10L, result.id()); + assertEquals("Pancakes", result.name()); + } + + @Test + void getRecipeThrowsWhenRecipeDoesNotExist() { + when(recipeRepository.findById(999L)) + .thenReturn(Optional.empty()); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.getRecipe(999L) + ); + } + + @Test + void createRecipeSavesRecipeWithIngredients() { + RecipeCreate request = new RecipeCreate( + "Sugar Pancakes", + Set.of(1L, 2L), + "3 cups", + "Mix and cook." + ); + + when(ingredientRepository.findAllById(Set.of(1L, 2L))) + .thenReturn(List.of(flour, sugar)); + + when(recipeRepository.save(any(Recipe.class))) + .thenAnswer(invocation -> invocation.getArgument(0)); + + RecipeResponse result = + recipeService.createRecipe(request, owner); + + assertEquals("Sugar Pancakes", result.name()); + assertEquals(2, result.ingredients().size()); + + verify(ingredientRepository) + .findAllById(Set.of(1L, 2L)); + + verify(recipeRepository).save(any(Recipe.class)); + } + + @Test + void createRecipeThrowsWhenIngredientIsMissing() { + RecipeCreate request = new RecipeCreate( + "Invalid Recipe", + Set.of(1L, 999L), + "2 cups", + "Instructions" + ); + + when(ingredientRepository.findAllById(Set.of(1L, 999L))) + .thenReturn(List.of(flour)); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.createRecipe(request, owner) + ); + + verify(recipeRepository, never()) + .save(any(Recipe.class)); + } + + @Test + void replaceRecipeUpdatesAllRecipeFields() { + RecipeCreate request = new RecipeCreate( + "Updated Pancakes", + Set.of(2L), + "4 cups", + "Updated instructions." + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + when(ingredientRepository.findAllById(Set.of(2L))) + .thenReturn(List.of(sugar)); + + RecipeResponse result = + recipeService.replaceRecipe( + 10L, + request, + owner + ); + + assertEquals("Updated Pancakes", result.name()); + assertEquals("4 cups", result.measurements()); + assertEquals( + "Updated instructions.", + result.instructions() + ); + assertEquals(1, result.ingredients().size()); + } + + @Test + void patchRecipeUpdatesOnlyProvidedFields() { + RecipePatch request = new RecipePatch( + null, + null, + null, + JsonNodeFactory.instance.textNode( + "Updated instructions." + ) + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertEquals("Pancakes", result.name()); + assertEquals("2 cups", result.measurements()); + assertEquals( + "Updated instructions.", + result.instructions() + ); + } + + @Test + void patchRecipeClearsInstructionsWhenExplicitlyNull() { + RecipePatch request = new RecipePatch( + null, + null, + null, + JsonNodeFactory.instance.nullNode() + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertNull(result.instructions()); + assertEquals("2 cups", result.measurements()); + } + + @Test + void patchRecipeReplacesIngredientsWhenIngredientIdsProvided() { + RecipePatch request = new RecipePatch( + null, + Set.of(2L), + null, + null + ); + + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + when(ingredientRepository.findAllById(Set.of(2L))) + .thenReturn(List.of(sugar)); + + RecipeResponse result = + recipeService.patchRecipe( + 10L, + request, + owner + ); + + assertEquals(1, result.ingredients().size()); + assertEquals( + "Sugar", + result.ingredients() + .iterator() + .next() + .ingredientName() + ); + } + + @Test + void deleteRecipeDeletesOwnedRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + recipeService.deleteRecipe(10L, owner); + + verify(recipeRepository).delete(recipe); + } + + @Test + void anotherUserCannotUpdateRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + RecipeCreate request = new RecipeCreate( + "Unauthorized Update", + Set.of(1L), + "1 cup", + "Instructions" + ); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.replaceRecipe( + 10L, + request, + otherUser + ) + ); + + verify(recipeRepository, never()) + .save(any(Recipe.class)); + } + + @Test + void anotherUserCannotDeleteRecipe() { + when(recipeRepository.findById(10L)) + .thenReturn(Optional.of(recipe)); + + assertThrows( + EntityNotFoundException.class, + () -> recipeService.deleteRecipe( + 10L, + otherUser + ) + ); + + verify(recipeRepository, never()) + .delete(any(Recipe.class)); + } + + private static void setId( + Object entity, + Long id) throws Exception { + + Field idField = + entity.getClass().getDeclaredField("id"); + + idField.setAccessible(true); + idField.set(entity, id); + } +} \ No newline at end of file diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 8214a70..0198e81 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -787,16 +787,18 @@ components: RecipeCreate: description: Body for POST and PUT. PUT replaces every field. type: object - required: [name, ingredients, measurements, instructions] + required: [name, ingredientIds, measurements, instructions] properties: name: type: string minLength: 1 example: Brown Sugar Oatmeal - ingredients: + ingredientIds: type: array items: - $ref: '#/components/schemas/Ingredient' + type: integer + format: int64 + example: [1, 2, 3] measurements: type: string nullable: true @@ -823,10 +825,16 @@ components: type: object minProperties: 1 properties: - ingredients: + name: + type: string + minLength: 1 + example: Updated Recipe Name + ingredientIds: type: array items: - $ref: '#/components/schemas/Ingredient' + type: integer + format: int64 + example: [1, 3] measurements: type: string nullable: true