From b9e973dfb464b8a17f3c463bf33293fd3ce406e3 Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:27:45 -0700 Subject: [PATCH 1/7] fix: unproxy lazy associations before identity checks in entry sync methods --- api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java | 6 ++++-- api/src/main/java/edu/csumb/cst438/api/entity/Recipe.java | 6 ++++-- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java index c816f87..4f477e3 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.Getter; +import org.hibernate.Hibernate; import java.time.LocalDate; import java.util.ArrayList; @@ -62,7 +63,8 @@ public void addMealPlanEntry(MealPlanEntry mealPlanEntry){ if(mealPlanEntry == null){ throw new IllegalArgumentException("Meal plan entry must not be null."); } - if(mealPlanEntry.getMealPlan() != null && mealPlanEntry.getMealPlan() != this){ + // unproxy: a lazy-loaded getter returns a Hibernate proxy, which is never == this + if(mealPlanEntry.getMealPlan() != null && Hibernate.unproxy(mealPlanEntry.getMealPlan()) != this){ throw new IllegalStateException("A meal plan entry cannot be transferred between meal plans."); } mealPlanEntries.add(mealPlanEntry); @@ -77,7 +79,7 @@ public void addMealPlanEntry(MealPlanEntry mealPlanEntry){ * @throws IllegalArgumentException if the entry doesn't belong to this meal plan or if the entry is null */ public void removeMealPlanEntry(MealPlanEntry mealPlanEntry){ - if(mealPlanEntry == null || mealPlanEntry.getMealPlan() != this){ + if(mealPlanEntry == null || Hibernate.unproxy(mealPlanEntry.getMealPlan()) != this){ throw new IllegalArgumentException("Meal plan entry does not belong to meal plan."); } mealPlanEntries.remove(mealPlanEntry); diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/Recipe.java b/api/src/main/java/edu/csumb/cst438/api/entity/Recipe.java index 73acd91..cfc3fca 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/Recipe.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/Recipe.java @@ -2,6 +2,7 @@ import jakarta.persistence.*; import lombok.Getter; +import org.hibernate.Hibernate; import org.hibernate.annotations.CreationTimestamp; import java.time.Instant; @@ -147,7 +148,8 @@ public void addMealPlanEntry(MealPlanEntry mealPlanEntry){ if(mealPlanEntry == null){ throw new IllegalArgumentException("Meal plan entry must not be null."); } - if(mealPlanEntry.getRecipe() != null && mealPlanEntry.getRecipe() != this){ + // unproxy: a lazy-loaded getter returns a Hibernate proxy, which is never == this + if(mealPlanEntry.getRecipe() != null && Hibernate.unproxy(mealPlanEntry.getRecipe()) != this){ throw new IllegalStateException("A meal plan entry cannot be transferred between recipes."); } mealPlanEntries.add(mealPlanEntry); @@ -162,7 +164,7 @@ public void addMealPlanEntry(MealPlanEntry mealPlanEntry){ * @throws IllegalArgumentException if the entry doesn't belong to this recipe or if the entry is null */ public void removeMealPlanEntry(MealPlanEntry mealPlanEntry){ - if(mealPlanEntry == null || mealPlanEntry.getRecipe() != this){ + if(mealPlanEntry == null || Hibernate.unproxy(mealPlanEntry.getRecipe()) != this){ throw new IllegalArgumentException("Meal plan entry does not have this recipe."); } mealPlanEntries.remove(mealPlanEntry); From 0299010c755bbdf6a79ca12393deb5494e7e3ed5 Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:28:08 -0700 Subject: [PATCH 2/7] feat: add change methods to MealPlanEntry --- .../cst438/api/entity/MealPlanEntry.java | 41 +++++++++++++++++++ 1 file changed, 41 insertions(+) diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java index 2658329..49f34e2 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java @@ -52,6 +52,47 @@ public MealPlanEntry(MealPlan meal_plan, Recipe recipe, LocalDate planned_date, mealType = meal_type; } + /** + * Moves this entry to a different recipe and keeps both recipes' entry collections in sync. + * + * @param recipe the new recipe, cannot be null + * @throws IllegalArgumentException if recipe is null + */ + public void changeRecipe(Recipe recipe){ + if(recipe == null){ + throw new IllegalArgumentException("Meal plan entries must have a recipe."); + } + this.recipe.removeMealPlanEntry(this); + this.recipe = null; + recipe.addMealPlanEntry(this); + } + + /** + * Changes the date the meal is planned for. + * + * @param plannedDate the new date, cannot be null + * @throws IllegalArgumentException if plannedDate is null + */ + public void changePlannedDate(LocalDate plannedDate){ + if(plannedDate == null){ + throw new IllegalArgumentException("Meal plan entries must have a planned date."); + } + this.plannedDate = plannedDate; + } + + /** + * Changes the type of meal. + * + * @param mealType the new meal type, cannot be null + * @throws IllegalArgumentException if mealType is null + */ + public void changeMealType(mealType mealType){ + if(mealType == null){ + throw new IllegalArgumentException("Meal plan entries must have a meal type."); + } + this.mealType = mealType; + } + /** * Called by MealPlan.addMealPlanEntry so the mealPlan side cannot get out of sync. */ From dad0ce396492fe1d75025a39fc1b7ce0308cd886 Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:28:40 -0700 Subject: [PATCH 3/7] feat: add update and delete for meal plan entries in MealPlanService --- .../cst438/api/record/MealPlanEntryPatch.java | 27 +++++ .../cst438/api/service/MealPlanService.java | 67 +++++++++++- .../cst438/api/MealPlanServiceJpaTest.java | 61 +++++++++++ .../csumb/cst438/api/MealPlanServiceTest.java | 102 ++++++++++++++++++ 4 files changed, 256 insertions(+), 1 deletion(-) create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryPatch.java diff --git a/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryPatch.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryPatch.java new file mode 100644 index 0000000..be9e1e2 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryPatch.java @@ -0,0 +1,27 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.mealType; +import jakarta.validation.constraints.AssertTrue; + +import java.time.LocalDate; + +/** + * Body for PATCH /api/v1/meal-plans/{mealPlanId}/entries/{entryId}. + * Only the non-null fields are changed. An unknown mealType fails JSON parsing, which is a 400. + * + * @param recipeId the new recipe + * @param plannedDate the new planned date + * @param mealType the new meal type + */ +public record MealPlanEntryPatch(Long recipeId, LocalDate plannedDate, mealType mealType) { + + /** + * The contract requires at least one property (minProperties: 1). + * + * @return true if at least one field was sent + */ + @AssertTrue(message = "at least one field must be provided") + public boolean isNotEmpty() { + return recipeId != null || plannedDate != null || mealType != null; + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java index 5d575c7..08e025c 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java @@ -1,9 +1,14 @@ package edu.csumb.cst438.api.service; import edu.csumb.cst438.api.entity.MealPlan; +import edu.csumb.cst438.api.entity.MealPlanEntry; +import edu.csumb.cst438.api.entity.Recipe; import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.MealPlanEntryPatch; +import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; import edu.csumb.cst438.api.repository.MealPlanRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; import org.springframework.data.domain.Page; import org.springframework.data.domain.PageRequest; import org.springframework.data.domain.Sort; @@ -23,13 +28,16 @@ @Transactional public class MealPlanService { private final MealPlanRepository mealPlanRepository; + private final RecipeRepository recipeRepository; /** * Constructor for MealPlanService * @param mealPlanRepository the meal plan repository + * @param recipeRepository the recipe repository, for changing an entry's recipe */ - public MealPlanService(MealPlanRepository mealPlanRepository) { + public MealPlanService(MealPlanRepository mealPlanRepository, RecipeRepository recipeRepository) { this.mealPlanRepository = mealPlanRepository; + this.recipeRepository = recipeRepository; } /** @@ -100,6 +108,47 @@ public void delete(String email, Long mealPlanId) { owner.removeMealPlan(findOwned(owner, mealPlanId)); } + /** + * Changes the fields that were sent on one entry of the user's meal plan. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @param entryId the entry id + * @param patch the fields to change; null fields are left as they are + * @return the updated entry + * @throws ResponseStatusException 404 if the meal plan, entry, or recipe isn't the user's + */ + public MealPlanEntryResponse updateEntry(String email, Long mealPlanId, Long entryId, MealPlanEntryPatch patch) { + User owner = currentUser(email); + MealPlanEntry entry = findEntry(findOwned(owner, mealPlanId), entryId); + if (patch.recipeId() != null) { + entry.changeRecipe(findUsableRecipe(owner, patch.recipeId())); + } + if (patch.plannedDate() != null) { + entry.changePlannedDate(patch.plannedDate()); + } + if (patch.mealType() != null) { + entry.changeMealType(patch.mealType()); + } + return MealPlanEntryResponse.from(entry); + } + + /** + * Removes one entry from the user's meal plan. The recipe is kept. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @param entryId the entry id + * @throws ResponseStatusException 404 if the meal plan or entry isn't the user's + */ + public void deleteEntry(String email, Long mealPlanId, Long entryId) { + MealPlan mealPlan = findOwned(currentUser(email), mealPlanId); + MealPlanEntry entry = findEntry(mealPlan, entryId); + entry.getRecipe().removeMealPlanEntry(entry); + // orphanRemoval deletes the row + mealPlan.removeMealPlanEntry(entry); + } + // TODO(#48): replace with userService.getUserByEmail(email); see MealPlanRepository.findUserByEmail private User currentUser(String email) { return mealPlanRepository.findUserByEmail(email) @@ -111,4 +160,20 @@ private MealPlan findOwned(User owner, Long mealPlanId) { .orElseThrow(() -> new ResponseStatusException( HttpStatus.NOT_FOUND, "Meal plan " + mealPlanId + " not found")); } + + private MealPlanEntry findEntry(MealPlan mealPlan, Long entryId) { + return mealPlan.getMealPlanEntries().stream() + .filter(e -> entryId.equals(e.getId())) + .findFirst() + .orElseThrow(() -> new ResponseStatusException( + HttpStatus.NOT_FOUND, "Meal plan entry " + entryId + " not found")); + } + + // A user can plan their own recipes and the prepopulated ones; anything else is hidden as 404. + private Recipe findUsableRecipe(User owner, Long recipeId) { + return recipeRepository.findById(recipeId) + .filter(r -> r.isPrepopulated() || r.getOwner() == owner) + .orElseThrow(() -> new ResponseStatusException( + HttpStatus.NOT_FOUND, "Recipe " + recipeId + " not found")); + } } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java index 735688d..3aa4360 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java @@ -1,6 +1,7 @@ package edu.csumb.cst438.api; import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.record.MealPlanEntryPatch; import edu.csumb.cst438.api.service.MealPlanService; import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; @@ -73,4 +74,64 @@ void otherUsersPlanIsHidden() { .singleElement() .satisfies(p -> assertThat(p.weekStart()).isEqualTo(LocalDate.of(2026, 10, 12))); } + + /** + * Deleting an entry deletes only that row and keeps the recipe + */ + @Test + void deleteEntryKeepsRecipe() { + User owner = new User("owner@example.com", "Owner", "USER"); + entityManager.persist(owner); + MealPlan mealPlan = new MealPlan(owner, LocalDate.of(2026, 10, 5)); + Recipe recipe = new Recipe("Pizza", null, "Eat it", owner); + entityManager.persist(mealPlan); + entityManager.persist(recipe); + MealPlanEntry entry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 6), mealType.DINNER); + entityManager.flush(); + entityManager.clear(); + + mealPlanService.deleteEntry("owner@example.com", mealPlan.getId(), entry.getId()); + entityManager.flush(); + entityManager.clear(); + + assertThat(entityManager.find(MealPlanEntry.class, entry.getId())).isNull(); + assertThat(entityManager.find(MealPlan.class, mealPlan.getId())).isNotNull(); + assertThat(entityManager.find(Recipe.class, recipe.getId())).isNotNull(); + } + + /** + * An entry can be moved to the user's own recipe, but another user's recipe is not found + */ + @Test + void updateEntryOnlyUsesOwnRecipes() { + User owner = new User("owner@example.com", "Owner", "USER"); + User other = new User("other@example.com", "Other", "USER"); + entityManager.persist(owner); + entityManager.persist(other); + MealPlan mealPlan = new MealPlan(owner, LocalDate.of(2026, 10, 5)); + Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); + Recipe soup = new Recipe("Soup", null, "Heat it", owner); + Recipe secret = new Recipe("Secret", null, "Shh", other); + entityManager.persist(mealPlan); + entityManager.persist(pizza); + entityManager.persist(soup); + entityManager.persist(secret); + MealPlanEntry entry = new MealPlanEntry(mealPlan, pizza, LocalDate.of(2026, 10, 6), mealType.DINNER); + entityManager.flush(); + entityManager.clear(); + + assertThatThrownBy(() -> mealPlanService.updateEntry("owner@example.com", mealPlan.getId(), entry.getId(), + new MealPlanEntryPatch(secret.getId(), null, null))) + .isInstanceOf(ResponseStatusException.class); + entityManager.clear(); + + mealPlanService.updateEntry("owner@example.com", mealPlan.getId(), entry.getId(), + new MealPlanEntryPatch(soup.getId(), null, mealType.LUNCH)); + entityManager.flush(); + entityManager.clear(); + + MealPlanEntry saved = entityManager.find(MealPlanEntry.class, entry.getId()); + assertThat(saved.getRecipe().getId()).isEqualTo(soup.getId()); + assertThat(saved.getMealType()).isEqualTo(mealType.LUNCH); + } } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java index 8822750..bc10df8 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java @@ -1,8 +1,11 @@ package edu.csumb.cst438.api; import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.record.MealPlanEntryPatch; +import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; import edu.csumb.cst438.api.repository.MealPlanRepository; +import edu.csumb.cst438.api.repository.RecipeRepository; import edu.csumb.cst438.api.service.MealPlanService; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -13,6 +16,7 @@ import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.http.HttpStatus; +import org.springframework.test.util.ReflectionTestUtils; import org.springframework.web.server.ResponseStatusException; import java.time.LocalDate; @@ -33,6 +37,9 @@ public class MealPlanServiceTest { @Mock private MealPlanRepository mealPlanRepository; + @Mock + private RecipeRepository recipeRepository; + @InjectMocks private MealPlanService mealPlanService; @@ -74,6 +81,9 @@ void notOwnedMealPlanIsNotFound() { assertStatus(() -> mealPlanService.get(EMAIL, 7L), HttpStatus.NOT_FOUND); assertStatus(() -> mealPlanService.update(EMAIL, 7L, WEEK), HttpStatus.NOT_FOUND); assertStatus(() -> mealPlanService.delete(EMAIL, 7L), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.updateEntry(EMAIL, 7L, 5L, + new MealPlanEntryPatch(null, null, mealType.LUNCH)), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.deleteEntry(EMAIL, 7L, 5L), HttpStatus.NOT_FOUND); } /** @@ -137,4 +147,96 @@ void deleteRemovesFromOwner() { assertThat(owner.getMealPlans()).isEmpty(); verify(mealPlanRepository).findByIdAndOwner(1L, owner); } + + private MealPlanEntry ownedEntry(MealPlan mealPlan, Recipe recipe) { + MealPlanEntry entry = new MealPlanEntry(mealPlan, recipe, WEEK, mealType.DINNER); + ReflectionTestUtils.setField(entry, "id", 5L); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + return entry; + } + + /** + * Patching an entry changes only the fields that were sent + */ + @Test + void updateEntryChangesOnlySentFields() { + signedIn(); + ownedEntry(new MealPlan(owner, WEEK), new Recipe("Pizza", null, "Eat it", owner)); + + MealPlanEntryResponse updated = mealPlanService.updateEntry(EMAIL, 1L, 5L, + new MealPlanEntryPatch(null, null, mealType.LUNCH)); + + assertThat(updated.mealType()).isEqualTo(mealType.LUNCH); + assertThat(updated.plannedDate()).isEqualTo(WEEK); + } + + /** + * Changing the recipe moves the entry from the old recipe to the new one + */ + @Test + void updateEntryMovesToPrepopulatedRecipe() { + signedIn(); + Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); + Recipe soup = new Recipe("Soup", null, "Heat it", null); + MealPlanEntry entry = ownedEntry(new MealPlan(owner, WEEK), pizza); + when(recipeRepository.findById(9L)).thenReturn(Optional.of(soup)); + + mealPlanService.updateEntry(EMAIL, 1L, 5L, + new MealPlanEntryPatch(9L, WEEK.plusDays(1), null)); + + assertThat(entry.getRecipe()).isSameAs(soup); + assertThat(entry.getPlannedDate()).isEqualTo(WEEK.plusDays(1)); + assertThat(entry.getMealType()).isEqualTo(mealType.DINNER); + assertThat(pizza.getMealPlanEntries()).isEmpty(); + assertThat(soup.getMealPlanEntries()).containsExactly(entry); + } + + /** + * Another user's recipe and a missing recipe are both 404, and the entry is unchanged + */ + @Test + void updateEntryRejectsOthersRecipe() { + signedIn(); + Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); + MealPlanEntry entry = ownedEntry(new MealPlan(owner, WEEK), pizza); + Recipe othersRecipe = new Recipe("Secret", null, "Shh", new User("other@example.com", "Other", "USER")); + when(recipeRepository.findById(9L)).thenReturn(Optional.of(othersRecipe)); + when(recipeRepository.findById(10L)).thenReturn(Optional.empty()); + + assertStatus(() -> mealPlanService.updateEntry(EMAIL, 1L, 5L, + new MealPlanEntryPatch(9L, null, null)), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.updateEntry(EMAIL, 1L, 5L, + new MealPlanEntryPatch(10L, null, null)), HttpStatus.NOT_FOUND); + assertThat(entry.getRecipe()).isSameAs(pizza); + } + + /** + * An entry id that isn't in the meal plan is 404 for update and delete + */ + @Test + void entryNotInMealPlanIsNotFound() { + signedIn(); + ownedEntry(new MealPlan(owner, WEEK), new Recipe("Pizza", null, "Eat it", owner)); + + assertStatus(() -> mealPlanService.updateEntry(EMAIL, 1L, 6L, + new MealPlanEntryPatch(null, null, mealType.LUNCH)), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.deleteEntry(EMAIL, 1L, 6L), HttpStatus.NOT_FOUND); + } + + /** + * Deleting an entry removes it from the meal plan and the recipe, but keeps the recipe + */ + @Test + void deleteEntryKeepsRecipe() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); + ownedEntry(mealPlan, pizza); + + mealPlanService.deleteEntry(EMAIL, 1L, 5L); + + assertThat(mealPlan.getMealPlanEntries()).isEmpty(); + assertThat(pizza.getMealPlanEntries()).isEmpty(); + assertThat(owner.getRecipes()).containsExactly(pizza); + } } From b0545850371a7a803abafc82ed7da9d06b0f091d Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:29:07 -0700 Subject: [PATCH 4/7] feat: add PATCH and DELETE /api/v1/meal-plans/{mealPlanId}/entries/{entryId} --- .../api/controller/MealPlanController.java | 33 ++++++++++ .../cst438/api/MealPlanControllerTest.java | 66 +++++++++++++++++++ 2 files changed, 99 insertions(+) diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java b/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java index e9cc73e..d0366f7 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java @@ -1,6 +1,8 @@ package edu.csumb.cst438.api.controller; import edu.csumb.cst438.api.record.MealPlanCreate; +import edu.csumb.cst438.api.record.MealPlanEntryPatch; +import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanPatch; import edu.csumb.cst438.api.record.MealPlanResponse; import edu.csumb.cst438.api.service.MealPlanService; @@ -101,4 +103,35 @@ public ResponseEntity deleteMealPlan(Principal principal, @PathVariable Lo mealPlanService.delete(principal.getName(), mealPlanId); return ResponseEntity.noContent().build(); } + + /** + * Changes the fields that were sent on one planned meal. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @param entryId the entry id + * @param body the fields to change, at least one + * @return 200 with the updated entry + */ + @PatchMapping("/{mealPlanId}/entries/{entryId}") + public MealPlanEntryResponse updateMealPlanEntry(Principal principal, @PathVariable Long mealPlanId, + @PathVariable Long entryId, + @Valid @RequestBody MealPlanEntryPatch body) { + return mealPlanService.updateEntry(principal.getName(), mealPlanId, entryId, body); + } + + /** + * Removes one planned meal. The recipe is kept. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @param entryId the entry id + * @return 204 with no body + */ + @DeleteMapping("/{mealPlanId}/entries/{entryId}") + public ResponseEntity deleteMealPlanEntry(Principal principal, @PathVariable Long mealPlanId, + @PathVariable Long entryId) { + mealPlanService.deleteEntry(principal.getName(), mealPlanId, entryId); + return ResponseEntity.noContent().build(); + } } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java index 77ae13f..d1102f3 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java @@ -1,6 +1,9 @@ package edu.csumb.cst438.api; import edu.csumb.cst438.api.controller.MealPlanController; +import edu.csumb.cst438.api.entity.mealType; +import edu.csumb.cst438.api.record.MealPlanEntryPatch; +import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; import edu.csumb.cst438.api.service.MealPlanService; import edu.csumb.cst438.api.repository.UserRepository; @@ -26,6 +29,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.when; @@ -160,4 +164,66 @@ void notFoundIsProblemDetails() throws Exception { .andExpect(jsonPath("$.title").value("Not Found")) .andExpect(jsonPath("$.detail").value("Meal plan 99 not found")); } + + @Test + @WithMockUser("owner@example.com") + void updateEntrySendsOnlyChangedFields() throws Exception { + when(mealPlanService.updateEntry(EMAIL, 67L, 5L, new MealPlanEntryPatch(null, null, mealType.LUNCH))) + .thenReturn(new MealPlanEntryResponse(5L, 67L, 42L, WEEK, mealType.LUNCH)); + + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/5"), "{\"mealType\":\"LUNCH\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(5)) + .andExpect(jsonPath("$.mealPlanId").value(67)) + .andExpect(jsonPath("$.recipeId").value(42)) + .andExpect(jsonPath("$.mealType").value("LUNCH")); + } + + @Test + @WithMockUser("owner@example.com") + void updateEntryRejectsEmptyOrInvalidBody() throws Exception { + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/5"), "{}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/5"), "{\"mealType\":\"BRUNCH\"}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/5"), "{\"plannedDate\":\"not-a-date\"}")) + .andExpect(status().isBadRequest()); + verifyNoInteractions(mealPlanService); + } + + @Test + @WithMockUser("owner@example.com") + void deleteEntryReturns204() throws Exception { + mvc.perform(delete("/api/v1/meal-plans/67/entries/5")) + .andExpect(status().isNoContent()) + .andExpect(content().string("")); + verify(mealPlanService).deleteEntry(EMAIL, 67L, 5L); + } + + @Test + @WithMockUser("owner@example.com") + void missingEntryIsNotFound() throws Exception { + when(mealPlanService.updateEntry(eq(EMAIL), eq(67L), eq(99L), any())).thenThrow( + new ResponseStatusException(HttpStatus.NOT_FOUND, "Meal plan entry 99 not found")); + doThrow(new ResponseStatusException(HttpStatus.NOT_FOUND, "Meal plan entry 99 not found")) + .when(mealPlanService).deleteEntry(EMAIL, 67L, 99L); + + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/99"), "{\"mealType\":\"LUNCH\"}")) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(delete("/api/v1/meal-plans/67/entries/99")) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + } + + @Test + void entryRoutesRequireToken() throws Exception { + mvc.perform(json(patch("/api/v1/meal-plans/67/entries/5"), "{\"mealType\":\"LUNCH\"}")) + .andExpect(status().isUnauthorized()); + mvc.perform(delete("/api/v1/meal-plans/67/entries/5")) + .andExpect(status().isUnauthorized()); + verifyNoInteractions(mealPlanService); + } } From d2899f575a37a4867731eb919d3083d491b6a925 Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:37:37 -0700 Subject: [PATCH 5/7] feat: require meal plan entry dates to be within the plan's week --- .../edu/csumb/cst438/api/entity/MealPlan.java | 18 +++++++++++++++++- .../csumb/cst438/api/entity/MealPlanEntry.java | 18 ++++++++++++++++-- .../api/MealPlanEntryPersistenceTest.java | 6 +++--- docs/openapi.yaml | 8 +++++--- 4 files changed, 41 insertions(+), 9 deletions(-) diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java index 4f477e3..1754b1c 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java @@ -5,6 +5,7 @@ import org.hibernate.Hibernate; import java.time.LocalDate; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; @@ -86,7 +87,8 @@ public void removeMealPlanEntry(MealPlanEntry mealPlanEntry){ } /** - * Moves this meal plan to a different week. Entries are left unchanged. + * Moves this meal plan to a different week. Entries move by the same number of days, + * so they stay on the same weekday inside the plan's week. * * @param weekStart the new week start, cannot be null * @throws IllegalArgumentException if weekStart is null @@ -95,9 +97,23 @@ public void changeWeekStart(LocalDate weekStart){ if(weekStart == null){ throw new IllegalArgumentException("Meal plans must have a starting week."); } + long days = ChronoUnit.DAYS.between(this.weekStart, weekStart); + for(MealPlanEntry entry : mealPlanEntries){ + entry.shiftPlannedDate(days); + } this.weekStart = weekStart; } + /** + * Checks whether a date is in this meal plan's week, weekStart through the 6 days after it. + * + * @param date the date to check + * @return true if the date is in the week + */ + public boolean coversDate(LocalDate date){ + return !date.isBefore(weekStart) && date.isBefore(weekStart.plusDays(7)); + } + /** * Called by User.addMealPlan owning side cannot get out of sync similar to the recipe table. */ diff --git a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java index 49f34e2..6540e07 100644 --- a/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java +++ b/api/src/main/java/edu/csumb/cst438/api/entity/MealPlanEntry.java @@ -40,12 +40,13 @@ protected MealPlanEntry(){} * @param recipe the recipe this entry contains * @param planned_date the date the meal is planned to be made * @param meal_type the type of meal - * @throws IllegalArgumentException if anything inputted is null + * @throws IllegalArgumentException if anything inputted is null or the date isn't in the meal plan's week */ public MealPlanEntry(MealPlan meal_plan, Recipe recipe, LocalDate planned_date, mealType meal_type){ if(meal_plan == null || recipe == null || planned_date == null || meal_type == null){ throw new IllegalArgumentException("Meal plan entries must have a meal plan, recipe, planned date, and meal type."); } + requireInWeek(meal_plan, planned_date); meal_plan.addMealPlanEntry(this); recipe.addMealPlanEntry(this); plannedDate = planned_date; @@ -71,15 +72,28 @@ public void changeRecipe(Recipe recipe){ * Changes the date the meal is planned for. * * @param plannedDate the new date, cannot be null - * @throws IllegalArgumentException if plannedDate is null + * @throws IllegalArgumentException if plannedDate is null or isn't in the meal plan's week */ public void changePlannedDate(LocalDate plannedDate){ if(plannedDate == null){ throw new IllegalArgumentException("Meal plan entries must have a planned date."); } + requireInWeek(mealPlan, plannedDate); this.plannedDate = plannedDate; } + /** + * Called by MealPlan.changeWeekStart so entries move with their week. + */ + void shiftPlannedDate(long days){plannedDate = plannedDate.plusDays(days);} + + private static void requireInWeek(MealPlan mealPlan, LocalDate plannedDate){ + if(!mealPlan.coversDate(plannedDate)){ + throw new IllegalArgumentException("Planned date " + plannedDate + " must be within the week starting " + + mealPlan.getWeekStart() + "."); + } + } + /** * Changes the type of meal. * diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanEntryPersistenceTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanEntryPersistenceTest.java index be9b532..477a576 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanEntryPersistenceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanEntryPersistenceTest.java @@ -29,7 +29,7 @@ void mealPlanEntryReload(){ entityManager.persist(mealPlan); entityManager.persist(recipe); - MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 31), mealType.DINNER); + MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 12), mealType.DINNER); entityManager.flush(); Long entryId = mealPlanEntry.getId(); entityManager.clear(); @@ -54,7 +54,7 @@ void entryMPDelete(){ entityManager.persist(mealPlan); entityManager.persist(recipe); - MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 31), mealType.DINNER); + MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 12), mealType.DINNER); entityManager.flush(); owner.removeMealPlan(mealPlan); @@ -77,7 +77,7 @@ void entryRecipeDelete(){ entityManager.persist(mealPlan); entityManager.persist(recipe); - MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 31), mealType.DINNER); + MealPlanEntry mealPlanEntry = new MealPlanEntry(mealPlan, recipe, LocalDate.of(2026, 10, 12), mealType.DINNER); entityManager.flush(); entityManager.remove(recipe); diff --git a/docs/openapi.yaml b/docs/openapi.yaml index 0198e81..af53029 100644 --- a/docs/openapi.yaml +++ b/docs/openapi.yaml @@ -715,10 +715,11 @@ components: type: integer format: int64 example: 57 - plannedDate: + plannedDate: type: string format: date - example: "2023-02-10" + description: Must be within the meal plan's week (weekStart through weekStart + 6 days), otherwise 400. + example: "2026-10-07" mealType: type: string enum: [BREAKFAST, LUNCH, DINNER] @@ -736,7 +737,8 @@ components: plannedDate: type: string format: date - example: "2026-10-02" + description: Must be within the meal plan's week (weekStart through weekStart + 6 days), otherwise 400. + example: "2026-10-07" mealType: type: string enum: [BREAKFAST, LUNCH, DINNER] From 71cc2a9c3995d094ca381f1c45f69864a4d35646 Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 16:38:42 -0700 Subject: [PATCH 6/7] feat: add POST and GET /api/v1/meal-plans/{mealPlanId}/entries --- .../api/controller/MealPlanController.java | 30 +++++++ .../api/record/MealPlanEntryCreate.java | 16 ++++ .../cst438/api/service/MealPlanService.java | 38 +++++++- .../cst438/api/MealPlanControllerTest.java | 62 +++++++++++++ .../cst438/api/MealPlanServiceJpaTest.java | 28 ++++++ .../csumb/cst438/api/MealPlanServiceTest.java | 90 ++++++++++++++++++- 6 files changed, 262 insertions(+), 2 deletions(-) create mode 100644 api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryCreate.java diff --git a/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java b/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java index d0366f7..9fe0da0 100644 --- a/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java +++ b/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java @@ -1,6 +1,7 @@ package edu.csumb.cst438.api.controller; import edu.csumb.cst438.api.record.MealPlanCreate; +import edu.csumb.cst438.api.record.MealPlanEntryCreate; import edu.csumb.cst438.api.record.MealPlanEntryPatch; import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanPatch; @@ -15,6 +16,7 @@ import java.net.URI; import java.security.Principal; +import java.util.List; /** * API routes for the signed-in user's weekly meal plans, under /api/v1/meal-plans. @@ -104,6 +106,34 @@ public ResponseEntity deleteMealPlan(Principal principal, @PathVariable Lo return ResponseEntity.noContent().build(); } + /** + * Lists the planned meals in a meal plan. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @return 200 with the entries + */ + @GetMapping("/{mealPlanId}/entries") + public List listMealPlanEntries(Principal principal, @PathVariable Long mealPlanId) { + return mealPlanService.listEntries(principal.getName(), mealPlanId); + } + + /** + * Adds a recipe to a meal plan. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @param body the recipe, date, and meal type + * @return 201 with the new entry and its Location + */ + @PostMapping("/{mealPlanId}/entries") + public ResponseEntity addMealPlanEntry(Principal principal, @PathVariable Long mealPlanId, + @Valid @RequestBody MealPlanEntryCreate body) { + MealPlanEntryResponse created = mealPlanService.addEntry(principal.getName(), mealPlanId, body); + return ResponseEntity.created( + URI.create("/api/v1/meal-plans/" + mealPlanId + "/entries/" + created.id())).body(created); + } + /** * Changes the fields that were sent on one planned meal. * diff --git a/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryCreate.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryCreate.java new file mode 100644 index 0000000..7f1be4b --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryCreate.java @@ -0,0 +1,16 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.mealType; +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; + +/** + * Body for POST /api/v1/meal-plans/{mealPlanId}/entries. + * + * @param recipeId the recipe to plan + * @param plannedDate the date the meal is planned for, within the meal plan's week + * @param mealType breakfast, lunch, or dinner + */ +public record MealPlanEntryCreate(@NotNull Long recipeId, @NotNull LocalDate plannedDate, @NotNull mealType mealType) { +} diff --git a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java index 08e025c..ea94923 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java @@ -4,6 +4,7 @@ import edu.csumb.cst438.api.entity.MealPlanEntry; import edu.csumb.cst438.api.entity.Recipe; import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.MealPlanEntryCreate; import edu.csumb.cst438.api.record.MealPlanEntryPatch; import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; @@ -18,6 +19,7 @@ import org.springframework.web.server.ResponseStatusException; import java.time.LocalDate; +import java.util.List; /** * Business logic for the signed-in user's meal plans. @@ -80,7 +82,7 @@ public MealPlanResponse get(String email, Long mealPlanId) { } /** - * Changes the week of one of the user's meal plans. Entries are left unchanged. + * Changes the week of one of the user's meal plans. Entries move with the week. * * @param email the signed-in user's email * @param mealPlanId the meal plan id @@ -108,6 +110,39 @@ public void delete(String email, Long mealPlanId) { owner.removeMealPlan(findOwned(owner, mealPlanId)); } + /** + * Lists the entries of one of the user's meal plans. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @return the meal plan's entries + * @throws ResponseStatusException 404 if missing or owned by another user + */ + @Transactional(readOnly = true) + public List listEntries(String email, Long mealPlanId) { + return MealPlanResponse.from(findOwned(currentUser(email), mealPlanId)).entries(); + } + + /** + * Adds a recipe to one of the user's meal plans. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @param body the recipe, date, and meal type + * @return the new entry + * @throws ResponseStatusException 404 if the meal plan or recipe isn't the user's + * @throws IllegalArgumentException if the date isn't in the meal plan's week (400) + */ + public MealPlanEntryResponse addEntry(String email, Long mealPlanId, MealPlanEntryCreate body) { + User owner = currentUser(email); + MealPlan mealPlan = findOwned(owner, mealPlanId); + MealPlanEntry entry = new MealPlanEntry(mealPlan, findUsableRecipe(owner, body.recipeId()), + body.plannedDate(), body.mealType()); + // flush so the generated id is in the response + mealPlanRepository.flush(); + return MealPlanEntryResponse.from(entry); + } + /** * Changes the fields that were sent on one entry of the user's meal plan. * @@ -117,6 +152,7 @@ public void delete(String email, Long mealPlanId) { * @param patch the fields to change; null fields are left as they are * @return the updated entry * @throws ResponseStatusException 404 if the meal plan, entry, or recipe isn't the user's + * @throws IllegalArgumentException if the new date isn't in the meal plan's week (400) */ public MealPlanEntryResponse updateEntry(String email, Long mealPlanId, Long entryId, MealPlanEntryPatch patch) { User owner = currentUser(email); diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java index d1102f3..48aa971 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java @@ -2,6 +2,7 @@ import edu.csumb.cst438.api.controller.MealPlanController; import edu.csumb.cst438.api.entity.mealType; +import edu.csumb.cst438.api.record.MealPlanEntryCreate; import edu.csumb.cst438.api.record.MealPlanEntryPatch; import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; @@ -226,4 +227,65 @@ void entryRoutesRequireToken() throws Exception { .andExpect(status().isUnauthorized()); verifyNoInteractions(mealPlanService); } + + @Test + @WithMockUser("owner@example.com") + void listEntriesReturnsArray() throws Exception { + when(mealPlanService.listEntries(EMAIL, 67L)) + .thenReturn(List.of(new MealPlanEntryResponse(5L, 67L, 42L, WEEK, mealType.DINNER))); + + mvc.perform(get("/api/v1/meal-plans/67/entries")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$[0].id").value(5)) + .andExpect(jsonPath("$[0].recipeId").value(42)); + } + + @Test + @WithMockUser("owner@example.com") + void addEntryReturns201WithLocation() throws Exception { + when(mealPlanService.addEntry(EMAIL, 67L, new MealPlanEntryCreate(42L, WEEK, mealType.LUNCH))) + .thenReturn(new MealPlanEntryResponse(5L, 67L, 42L, WEEK, mealType.LUNCH)); + + mvc.perform(json(post("/api/v1/meal-plans/67/entries"), + "{\"recipeId\":42,\"plannedDate\":\"2026-10-05\",\"mealType\":\"LUNCH\"}")) + .andExpect(status().isCreated()) + .andExpect(header().string("Location", "/api/v1/meal-plans/67/entries/5")) + .andExpect(jsonPath("$.id").value(5)) + .andExpect(jsonPath("$.mealType").value("LUNCH")); + } + + @Test + @WithMockUser("owner@example.com") + void addEntryRejectsMissingOrInvalidFields() throws Exception { + mvc.perform(json(post("/api/v1/meal-plans/67/entries"), "{\"recipeId\":42,\"mealType\":\"LUNCH\"}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(json(post("/api/v1/meal-plans/67/entries"), + "{\"recipeId\":42,\"plannedDate\":\"2026-10-05\",\"mealType\":\"BRUNCH\"}")) + .andExpect(status().isBadRequest()); + verifyNoInteractions(mealPlanService); + } + + @Test + @WithMockUser("owner@example.com") + void dateOutsideWeekIsBadRequest() throws Exception { + when(mealPlanService.addEntry(eq(EMAIL), eq(67L), any())).thenThrow( + new IllegalArgumentException("Planned date 2026-10-12 must be within the week starting 2026-10-05.")); + + mvc.perform(json(post("/api/v1/meal-plans/67/entries"), + "{\"recipeId\":42,\"plannedDate\":\"2026-10-12\",\"mealType\":\"LUNCH\"}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.detail").value("Planned date 2026-10-12 must be within the week starting 2026-10-05.")); + } + + @Test + void entryListAndAddRequireToken() throws Exception { + mvc.perform(get("/api/v1/meal-plans/67/entries")) + .andExpect(status().isUnauthorized()); + mvc.perform(json(post("/api/v1/meal-plans/67/entries"), + "{\"recipeId\":42,\"plannedDate\":\"2026-10-05\",\"mealType\":\"LUNCH\"}")) + .andExpect(status().isUnauthorized()); + verifyNoInteractions(mealPlanService); + } } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java index 3aa4360..6672408 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java @@ -1,7 +1,9 @@ package edu.csumb.cst438.api; import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.record.MealPlanEntryCreate; import edu.csumb.cst438.api.record.MealPlanEntryPatch; +import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.service.MealPlanService; import jakarta.persistence.EntityManager; import org.junit.jupiter.api.Test; @@ -134,4 +136,30 @@ void updateEntryOnlyUsesOwnRecipes() { assertThat(saved.getRecipe().getId()).isEqualTo(soup.getId()); assertThat(saved.getMealType()).isEqualTo(mealType.LUNCH); } + + /** + * Adding an entry saves it with an id, and it is listed with the meal plan + */ + @Test + void addEntryIsSaved() { + User owner = new User("owner@example.com", "Owner", "USER"); + entityManager.persist(owner); + MealPlan mealPlan = new MealPlan(owner, LocalDate.of(2026, 10, 5)); + Recipe recipe = new Recipe("Pizza", null, "Eat it", owner); + entityManager.persist(mealPlan); + entityManager.persist(recipe); + entityManager.flush(); + entityManager.clear(); + + MealPlanEntryResponse created = mealPlanService.addEntry("owner@example.com", mealPlan.getId(), + new MealPlanEntryCreate(recipe.getId(), LocalDate.of(2026, 10, 7), mealType.LUNCH)); + entityManager.flush(); + entityManager.clear(); + + assertThat(created.id()).isNotNull(); + assertThat(created.mealPlanId()).isEqualTo(mealPlan.getId()); + assertThat(mealPlanService.listEntries("owner@example.com", mealPlan.getId())) + .singleElement() + .satisfies(e -> assertThat(e.recipeId()).isEqualTo(recipe.getId())); + } } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java index bc10df8..5f0b576 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java @@ -1,6 +1,7 @@ package edu.csumb.cst438.api; import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.record.MealPlanEntryCreate; import edu.csumb.cst438.api.record.MealPlanEntryPatch; import edu.csumb.cst438.api.record.MealPlanEntryResponse; import edu.csumb.cst438.api.record.MealPlanResponse; @@ -84,6 +85,9 @@ void notOwnedMealPlanIsNotFound() { assertStatus(() -> mealPlanService.updateEntry(EMAIL, 7L, 5L, new MealPlanEntryPatch(null, null, mealType.LUNCH)), HttpStatus.NOT_FOUND); assertStatus(() -> mealPlanService.deleteEntry(EMAIL, 7L, 5L), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.listEntries(EMAIL, 7L), HttpStatus.NOT_FOUND); + assertStatus(() -> mealPlanService.addEntry(EMAIL, 7L, + new MealPlanEntryCreate(9L, WEEK, mealType.LUNCH)), HttpStatus.NOT_FOUND); } /** @@ -116,7 +120,7 @@ void createIsOwnedAndEmpty() { } /** - * Updating the week keeps the existing entries + * Updating the week keeps the existing entries and moves them to the new week */ @Test void updateKeepsEntries() { @@ -131,6 +135,7 @@ void updateKeepsEntries() { assertThat(updated.weekStart()).isEqualTo(LocalDate.of(2026, 10, 12)); assertThat(updated.entries()).hasSize(1); assertThat(updated.entries().getFirst().mealType()).isEqualTo(mealType.DINNER); + assertThat(updated.entries().getFirst().plannedDate()).isEqualTo(LocalDate.of(2026, 10, 12)); } /** @@ -239,4 +244,87 @@ void deleteEntryKeepsRecipe() { assertThat(pizza.getMealPlanEntries()).isEmpty(); assertThat(owner.getRecipes()).containsExactly(pizza); } + + /** + * A meal plan's week is weekStart through the 6 days after it + */ + @Test + void weekCoversSevenDays() { + MealPlan mealPlan = new MealPlan(owner, WEEK); + + assertThat(mealPlan.coversDate(WEEK)).isTrue(); + assertThat(mealPlan.coversDate(WEEK.plusDays(6))).isTrue(); + assertThat(mealPlan.coversDate(WEEK.minusDays(1))).isFalse(); + assertThat(mealPlan.coversDate(WEEK.plusDays(7))).isFalse(); + } + + /** + * Adding an entry links it to both the meal plan and the recipe + */ + @Test + void addEntryLinksPlanAndRecipe() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + Recipe soup = new Recipe("Soup", null, "Heat it", null); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + when(recipeRepository.findById(9L)).thenReturn(Optional.of(soup)); + + MealPlanEntryResponse created = mealPlanService.addEntry(EMAIL, 1L, + new MealPlanEntryCreate(9L, WEEK.plusDays(2), mealType.LUNCH)); + + assertThat(created.plannedDate()).isEqualTo(WEEK.plusDays(2)); + assertThat(created.mealType()).isEqualTo(mealType.LUNCH); + assertThat(mealPlan.getMealPlanEntries()).singleElement() + .satisfies(e -> assertThat(e.getRecipe()).isSameAs(soup)); + assertThat(soup.getMealPlanEntries()).hasSize(1); + } + + /** + * Another user's recipe can't be added, and nothing is added to the plan + */ + @Test + void addEntryRejectsOthersRecipe() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + when(recipeRepository.findById(9L)).thenReturn(Optional.of( + new Recipe("Secret", null, "Shh", new User("other@example.com", "Other", "USER")))); + + assertStatus(() -> mealPlanService.addEntry(EMAIL, 1L, + new MealPlanEntryCreate(9L, WEEK, mealType.LUNCH)), HttpStatus.NOT_FOUND); + assertThat(mealPlan.getMealPlanEntries()).isEmpty(); + } + + /** + * A date outside the meal plan's week is rejected when adding or changing an entry + */ + @Test + void dateOutsideWeekIsRejected() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); + MealPlanEntry entry = ownedEntry(mealPlan, pizza); + when(recipeRepository.findById(9L)).thenReturn(Optional.of(pizza)); + + assertThatThrownBy(() -> mealPlanService.addEntry(EMAIL, 1L, + new MealPlanEntryCreate(9L, WEEK.plusDays(7), mealType.LUNCH))) + .isInstanceOf(IllegalArgumentException.class); + assertThatThrownBy(() -> mealPlanService.updateEntry(EMAIL, 1L, 5L, + new MealPlanEntryPatch(null, WEEK.minusDays(1), null))) + .isInstanceOf(IllegalArgumentException.class); + assertThat(mealPlan.getMealPlanEntries()).containsExactly(entry); + assertThat(entry.getPlannedDate()).isEqualTo(WEEK); + } + + /** + * Listing entries returns the meal plan's entries + */ + @Test + void listEntriesReturnsPlanEntries() { + signedIn(); + ownedEntry(new MealPlan(owner, WEEK), new Recipe("Pizza", null, "Eat it", owner)); + + assertThat(mealPlanService.listEntries(EMAIL, 1L)).singleElement() + .satisfies(e -> assertThat(e.id()).isEqualTo(5L)); + } } From c148fd01add619f909b978fed6c9b98524f2846d Mon Sep 17 00:00:00 2001 From: Crom Date: Wed, 21 Oct 2026 22:05:44 -0700 Subject: [PATCH 7/7] fix review --- .../cst438/api/service/MealPlanService.java | 2 +- .../csumb/cst438/api/MealPlanServiceTest.java | 28 +++++++++++++++++-- 2 files changed, 27 insertions(+), 3 deletions(-) diff --git a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java index ea94923..fe5c781 100644 --- a/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java +++ b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java @@ -208,7 +208,7 @@ private MealPlanEntry findEntry(MealPlan mealPlan, Long entryId) { // A user can plan their own recipes and the prepopulated ones; anything else is hidden as 404. private Recipe findUsableRecipe(User owner, Long recipeId) { return recipeRepository.findById(recipeId) - .filter(r -> r.isPrepopulated() || r.getOwner() == owner) + .filter(r -> r.isPrepopulated() || r.getOwner().getId().equals(owner.getId())) .orElseThrow(() -> new ResponseStatusException( HttpStatus.NOT_FOUND, "Recipe " + recipeId + " not found")); } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java index 5f0b576..6fffa89 100644 --- a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java @@ -49,6 +49,13 @@ public class MealPlanServiceTest { @BeforeEach void setUp() { owner = new User(EMAIL, "Owner", "USER"); + ReflectionTestUtils.setField(owner, "id", 1L); + } + + private static User otherUser() { + User other = new User("other@example.com", "Other", "USER"); + ReflectionTestUtils.setField(other, "id", 2L); + return other; } private void signedIn() { @@ -204,7 +211,7 @@ void updateEntryRejectsOthersRecipe() { signedIn(); Recipe pizza = new Recipe("Pizza", null, "Eat it", owner); MealPlanEntry entry = ownedEntry(new MealPlan(owner, WEEK), pizza); - Recipe othersRecipe = new Recipe("Secret", null, "Shh", new User("other@example.com", "Other", "USER")); + Recipe othersRecipe = new Recipe("Secret", null, "Shh", otherUser()); when(recipeRepository.findById(9L)).thenReturn(Optional.of(othersRecipe)); when(recipeRepository.findById(10L)).thenReturn(Optional.empty()); @@ -279,6 +286,23 @@ void addEntryLinksPlanAndRecipe() { assertThat(soup.getMealPlanEntries()).hasSize(1); } + /** + * The user's own recipe is accepted even when it's loaded as a different User instance + */ + @Test + void addEntryAcceptsOwnRecipeWithDifferentOwnerInstance() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + User sameOwner = new User(EMAIL, "Owner", "USER"); + ReflectionTestUtils.setField(sameOwner, "id", 1L); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + when(recipeRepository.findById(9L)).thenReturn(Optional.of(new Recipe("Pizza", null, "Eat it", sameOwner))); + + mealPlanService.addEntry(EMAIL, 1L, new MealPlanEntryCreate(9L, WEEK, mealType.LUNCH)); + + assertThat(mealPlan.getMealPlanEntries()).hasSize(1); + } + /** * Another user's recipe can't be added, and nothing is added to the plan */ @@ -288,7 +312,7 @@ void addEntryRejectsOthersRecipe() { MealPlan mealPlan = new MealPlan(owner, WEEK); when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); when(recipeRepository.findById(9L)).thenReturn(Optional.of( - new Recipe("Secret", null, "Shh", new User("other@example.com", "Other", "USER")))); + new Recipe("Secret", null, "Shh", otherUser()))); assertStatus(() -> mealPlanService.addEntry(EMAIL, 1L, new MealPlanEntryCreate(9L, WEEK, mealType.LUNCH)), HttpStatus.NOT_FOUND);