diff --git a/api/build.gradle b/api/build.gradle index 55edbfb..18f66ab 100644 --- a/api/build.gradle +++ b/api/build.gradle @@ -30,6 +30,7 @@ dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-jpa' implementation 'org.springframework.boot:spring-boot-starter-validation' implementation 'org.springframework.boot:spring-boot-starter-webmvc' + implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:3.1.1' runtimeOnly 'com.h2database:h2' runtimeOnly 'org.postgresql:postgresql' testImplementation 'org.springframework.boot:spring-boot-starter-actuator-test' 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 new file mode 100644 index 0000000..e9cc73e --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/controller/MealPlanController.java @@ -0,0 +1,104 @@ +package edu.csumb.cst438.api.controller; + +import edu.csumb.cst438.api.record.MealPlanCreate; +import edu.csumb.cst438.api.record.MealPlanPatch; +import edu.csumb.cst438.api.record.MealPlanResponse; +import edu.csumb.cst438.api.service.MealPlanService; +import jakarta.validation.Valid; +import jakarta.validation.constraints.Max; +import jakarta.validation.constraints.Min; +import org.springframework.data.web.PagedModel; +import org.springframework.http.ResponseEntity; +import org.springframework.web.bind.annotation.*; + +import java.net.URI; +import java.security.Principal; + +/** + * API routes for the signed-in user's weekly meal plans, under /api/v1/meal-plans. + * Principal.getName() is the user's email. + * + * TODO(#48): Spring Security comes with PR #48. Until it merges there is no Principal, so these + * routes only work in tests. 401 (as Problem Details) is handled by #48's SecurityConfig. + */ +@RestController +@RequestMapping("/api/v1/meal-plans") +public class MealPlanController { + private final MealPlanService mealPlanService; + + /** + * Constructor for MealPlanController + * @param mealPlanService the meal plan service + */ + public MealPlanController(MealPlanService mealPlanService) { + this.mealPlanService = mealPlanService; + } + + /** + * Lists the user's meal plans. Uses plain request params instead of Pageable so that + * size above 100 returns 400 instead of being silently capped. + * + * @param principal the signed-in user + * @param page zero-based page number + * @param size items per page, 1 to 100 + * @return 200 with a page of meal plans + */ + @GetMapping + public PagedModel listMealPlans(Principal principal, + @RequestParam(defaultValue = "0") @Min(0) int page, + @RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) { + return new PagedModel<>(mealPlanService.list(principal.getName(), page, size)); + } + + /** + * Creates an empty meal plan. + * + * @param principal the signed-in user + * @param body the week the plan starts + * @return 201 with the new meal plan and its Location + */ + @PostMapping + public ResponseEntity createMealPlan(Principal principal, @Valid @RequestBody MealPlanCreate body) { + MealPlanResponse created = mealPlanService.create(principal.getName(), body.weekStart()); + return ResponseEntity.created(URI.create("/api/v1/meal-plans/" + created.id())).body(created); + } + + /** + * Gets one meal plan and its entries. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @return 200 with the meal plan + */ + @GetMapping("/{mealPlanId}") + public MealPlanResponse getMealPlan(Principal principal, @PathVariable Long mealPlanId) { + return mealPlanService.get(principal.getName(), mealPlanId); + } + + /** + * Changes a meal plan's week start. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @param body the fields to change + * @return 200 with the updated meal plan + */ + @PatchMapping("/{mealPlanId}") + public MealPlanResponse updateMealPlan(Principal principal, @PathVariable Long mealPlanId, + @Valid @RequestBody MealPlanPatch body) { + return mealPlanService.update(principal.getName(), mealPlanId, body.weekStart()); + } + + /** + * Deletes a meal plan and its entries. + * + * @param principal the signed-in user + * @param mealPlanId the meal plan id + * @return 204 with no body + */ + @DeleteMapping("/{mealPlanId}") + public ResponseEntity deleteMealPlan(Principal principal, @PathVariable Long mealPlanId) { + mealPlanService.delete(principal.getName(), mealPlanId); + return ResponseEntity.noContent().build(); + } +} 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 9491a7b..c816f87 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 @@ -83,6 +83,19 @@ public void removeMealPlanEntry(MealPlanEntry mealPlanEntry){ mealPlanEntries.remove(mealPlanEntry); } + /** + * Moves this meal plan to a different week. Entries are left unchanged. + * + * @param weekStart the new week start, cannot be null + * @throws IllegalArgumentException if weekStart is null + */ + public void changeWeekStart(LocalDate weekStart){ + if(weekStart == null){ + throw new IllegalArgumentException("Meal plans must have a starting week."); + } + this.weekStart = weekStart; + } + /** * 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/record/MealPlanCreate.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanCreate.java new file mode 100644 index 0000000..702d3c0 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanCreate.java @@ -0,0 +1,13 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; + +/** + * Body for POST /api/v1/meal-plans. + * + * @param weekStart the week the meal plan starts + */ +public record MealPlanCreate(@NotNull LocalDate weekStart) { +} diff --git a/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryResponse.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryResponse.java new file mode 100644 index 0000000..282d3e1 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanEntryResponse.java @@ -0,0 +1,33 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.MealPlanEntry; +import edu.csumb.cst438.api.entity.mealType; + +import java.time.LocalDate; + +/** + * The MealPlanEntry schema returned by the API. + * + * @param id the entry id + * @param mealPlanId the meal plan this entry belongs to + * @param recipeId the planned recipe + * @param plannedDate the date the meal is planned for + * @param mealType breakfast, lunch, or dinner + */ +public record MealPlanEntryResponse(Long id, Long mealPlanId, Long recipeId, LocalDate plannedDate, mealType mealType) { + + /** + * Converts an entry entity to its API shape. + * + * @param entry the entry entity + * @return the API representation + */ + public static MealPlanEntryResponse from(MealPlanEntry entry) { + return new MealPlanEntryResponse( + entry.getId(), + entry.getMealPlan().getId(), + entry.getRecipe().getId(), + entry.getPlannedDate(), + entry.getMealType()); + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/record/MealPlanPatch.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanPatch.java new file mode 100644 index 0000000..e81d7b6 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanPatch.java @@ -0,0 +1,16 @@ +package edu.csumb.cst438.api.record; + +import jakarta.validation.constraints.NotNull; + +import java.time.LocalDate; + +/** + * Body for PATCH /api/v1/meal-plans/{mealPlanId}. + * The contract requires at least one property, and weekStart is the only one, + * so it is required here. Replace @NotNull with an "at least one non-null field" check + * if more patchable fields are added. + * + * @param weekStart the new week the meal plan starts + */ +public record MealPlanPatch(@NotNull LocalDate weekStart) { +} diff --git a/api/src/main/java/edu/csumb/cst438/api/record/MealPlanResponse.java b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanResponse.java new file mode 100644 index 0000000..b95a82d --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/record/MealPlanResponse.java @@ -0,0 +1,29 @@ +package edu.csumb.cst438.api.record; + +import edu.csumb.cst438.api.entity.MealPlan; + +import java.time.LocalDate; +import java.util.List; + +/** + * The MealPlan schema returned by the API. + * + * @param id the meal plan id + * @param weekStart the week the meal plan starts + * @param entries the meals planned in this meal plan + */ +public record MealPlanResponse(Long id, LocalDate weekStart, List entries) { + + /** + * Converts a meal plan entity to its API shape. + * + * @param mealPlan the meal plan entity + * @return the API representation + */ + public static MealPlanResponse from(MealPlan mealPlan) { + return new MealPlanResponse( + mealPlan.getId(), + mealPlan.getWeekStart(), + mealPlan.getMealPlanEntries().stream().map(MealPlanEntryResponse::from).toList()); + } +} diff --git a/api/src/main/java/edu/csumb/cst438/api/repository/MealPlanRepository.java b/api/src/main/java/edu/csumb/cst438/api/repository/MealPlanRepository.java new file mode 100644 index 0000000..54a853a --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/repository/MealPlanRepository.java @@ -0,0 +1,55 @@ +package edu.csumb.cst438.api.repository; + +import edu.csumb.cst438.api.entity.MealPlan; +import edu.csumb.cst438.api.entity.User; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.data.jpa.repository.JpaRepository; +import org.springframework.data.jpa.repository.Query; + +import java.util.Optional; + +/** + * Database access for meal plans. Every lookup is scoped to an owner so one user + * can never read another user's meal plans. + */ +public interface MealPlanRepository extends JpaRepository { + + /** + * Returns one page of the owner's meal plans. + * + * @param owner the user who owns the meal plans + * @param pageable page number, size, and sort + * @return a page of meal plans + */ + Page findByOwner(User owner, Pageable pageable); + + /** + * Finds a meal plan only if it belongs to the owner. + * + * @param id the meal plan id + * @param owner the user who must own the meal plan + * @return the meal plan, or empty if it doesn't exist or belongs to someone else + */ + Optional findByIdAndOwner(Long id, User owner); + + /** + * Finds the signed-in user by email. + * + * TODO(#48): after PR #48 merges, delete this method and resolve the user through + * UserRepository instead: + * 1. add {@code Optional findByEmail(String email)} to UserRepository + * 2. add {@code User getUserByEmail(String email)} to UserService and use it in place of + * UserService.getUserByName (also in UserController's /me handlers) + * 3. change UserService.loadUserByUsername to look up by email and build the UserDetails + * with {@code .withUsername(user.getEmail())}, so Principal.getName() returns the email + * 4. inject UserService into MealPlanService and replace currentUser() with getUserByEmail + * 5. after #20 (OAuth2 JWT): set JwtAuthenticationConverter.setPrincipalClaimName("email") + * so Principal.getName() keeps returning the email + * + * @param email the user's email + * @return the user, or empty if no user has that email + */ + @Query("SELECT u FROM User u WHERE u.email = :email") + Optional findUserByEmail(String email); +} 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 new file mode 100644 index 0000000..5d575c7 --- /dev/null +++ b/api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java @@ -0,0 +1,114 @@ +package edu.csumb.cst438.api.service; + +import edu.csumb.cst438.api.entity.MealPlan; +import edu.csumb.cst438.api.entity.User; +import edu.csumb.cst438.api.record.MealPlanResponse; +import edu.csumb.cst438.api.repository.MealPlanRepository; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.PageRequest; +import org.springframework.data.domain.Sort; +import org.springframework.http.HttpStatus; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; + +/** + * Business logic for the signed-in user's meal plans. + * A meal plan that doesn't exist and one owned by another user both return 404, + * so the API never reveals that someone else's meal plan exists. + */ +@Service +@Transactional +public class MealPlanService { + private final MealPlanRepository mealPlanRepository; + + /** + * Constructor for MealPlanService + * @param mealPlanRepository the meal plan repository + */ + public MealPlanService(MealPlanRepository mealPlanRepository) { + this.mealPlanRepository = mealPlanRepository; + } + + /** + * Lists one page of the user's meal plans, ordered by week start. + * + * @param email the signed-in user's email + * @param page zero-based page number + * @param size items per page + * @return a page of meal plans with their entries + */ + @Transactional(readOnly = true) + public Page list(String email, int page, int size) { + PageRequest pageRequest = PageRequest.of(page, size, Sort.by("weekStart", "id")); + return mealPlanRepository.findByOwner(currentUser(email), pageRequest).map(MealPlanResponse::from); + } + + /** + * Creates an empty meal plan owned by the user. + * + * @param email the signed-in user's email + * @param weekStart the week the meal plan starts + * @return the new meal plan + */ + public MealPlanResponse create(String email, LocalDate weekStart) { + MealPlan mealPlan = new MealPlan(currentUser(email), weekStart); + return MealPlanResponse.from(mealPlanRepository.save(mealPlan)); + } + + /** + * Gets 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 with its entries + * @throws ResponseStatusException 404 if missing or owned by another user + */ + @Transactional(readOnly = true) + public MealPlanResponse get(String email, Long mealPlanId) { + return MealPlanResponse.from(findOwned(currentUser(email), mealPlanId)); + } + + /** + * Changes the week of one of the user's meal plans. Entries are left unchanged. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @param weekStart the new week start + * @return the updated meal plan + * @throws ResponseStatusException 404 if missing or owned by another user + */ + public MealPlanResponse update(String email, Long mealPlanId, LocalDate weekStart) { + MealPlan mealPlan = findOwned(currentUser(email), mealPlanId); + mealPlan.changeWeekStart(weekStart); + return MealPlanResponse.from(mealPlan); + } + + /** + * Deletes one of the user's meal plans and all of its entries. Recipes are kept. + * + * @param email the signed-in user's email + * @param mealPlanId the meal plan id + * @throws ResponseStatusException 404 if missing or owned by another user + */ + public void delete(String email, Long mealPlanId) { + User owner = currentUser(email); + // Removing through the owner (orphanRemoval) instead of repository.delete(), so User's + // cascade = ALL collection can't re-save the deleted plan on flush. + owner.removeMealPlan(findOwned(owner, mealPlanId)); + } + + // TODO(#48): replace with userService.getUserByEmail(email); see MealPlanRepository.findUserByEmail + private User currentUser(String email) { + return mealPlanRepository.findUserByEmail(email) + .orElseThrow(() -> new ResponseStatusException(HttpStatus.UNAUTHORIZED)); + } + + private MealPlan findOwned(User owner, Long mealPlanId) { + return mealPlanRepository.findByIdAndOwner(mealPlanId, owner) + .orElseThrow(() -> new ResponseStatusException( + HttpStatus.NOT_FOUND, "Meal plan " + mealPlanId + " not found")); + } +} diff --git a/api/src/main/resources/application.yaml b/api/src/main/resources/application.yaml index e14c857..2b9df7e 100644 --- a/api/src/main/resources/application.yaml +++ b/api/src/main/resources/application.yaml @@ -3,6 +3,9 @@ spring: import: optional:file:.env[.properties] application: name: api + mvc: + problemdetails: + enabled: true datasource: url: ${DATABASE_URL} username: ${DB_USER} @@ -12,4 +15,7 @@ spring: database-platform: org.hibernate.dialect.PostgreSQLDialect hibernate: ddl-auto: update + properties: + hibernate: + default_batch_fetch_size: 100 show-sql: true \ No newline at end of file diff --git a/api/src/test/java/edu/csumb/cst438/api/ApiApplicationTests.java b/api/src/test/java/edu/csumb/cst438/api/ApiApplicationTests.java index 188c871..beb0e36 100644 --- a/api/src/test/java/edu/csumb/cst438/api/ApiApplicationTests.java +++ b/api/src/test/java/edu/csumb/cst438/api/ApiApplicationTests.java @@ -1,15 +1,37 @@ package edu.csumb.cst438.api; import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.web.servlet.MockMvc; + +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; @ActiveProfiles("test") @SpringBootTest +@AutoConfigureMockMvc class ApiApplicationTests { + @Autowired + private MockMvc mvc; + @Test void contextLoads() { } + /** + * Swagger UI and the generated OpenAPI docs are served (required on the live deployment) + */ + @Test + void swaggerIsReachable() throws Exception { + mvc.perform(get("/v3/api-docs")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.paths['/api/v1/meal-plans']").exists()); + mvc.perform(get("/swagger-ui.html")) + .andExpect(status().is3xxRedirection()); + } + } diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java new file mode 100644 index 0000000..77f1f90 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanControllerTest.java @@ -0,0 +1,137 @@ +package edu.csumb.cst438.api; + +import edu.csumb.cst438.api.controller.MealPlanController; +import edu.csumb.cst438.api.record.MealPlanResponse; +import edu.csumb.cst438.api.service.MealPlanService; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.webmvc.test.autoconfigure.WebMvcTest; +import org.springframework.data.domain.PageImpl; +import org.springframework.data.domain.PageRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; +import org.springframework.web.server.ResponseStatusException; + +import java.security.Principal; +import java.time.LocalDate; +import java.util.List; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; + +// TODO(#48): once Spring Security is on the classpath, use @WithMockUser("owner@example.com") +// instead of .principal(...) and add a "no credentials -> 401 problem+json" test. +@WebMvcTest(MealPlanController.class) +@ActiveProfiles("test") +public class MealPlanControllerTest { + private static final String EMAIL = "owner@example.com"; + private static final Principal USER = () -> EMAIL; + private static final LocalDate WEEK = LocalDate.of(2026, 10, 5); + + @Autowired + private MockMvc mvc; + + @MockitoBean + private MealPlanService mealPlanService; + + private static MockHttpServletRequestBuilder json(MockHttpServletRequestBuilder request, String body) { + return request.principal(USER).contentType(MediaType.APPLICATION_JSON).content(body); + } + + @Test + void listReturnsPageShape() throws Exception { + when(mealPlanService.list(EMAIL, 0, 20)).thenReturn( + new PageImpl<>(List.of(new MealPlanResponse(67L, WEEK, List.of())), PageRequest.of(0, 20), 1)); + + mvc.perform(get("/api/v1/meal-plans").principal(USER)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.content[0].id").value(67)) + .andExpect(jsonPath("$.content[0].weekStart").value("2026-10-05")) + .andExpect(jsonPath("$.content[0].entries").isArray()) + .andExpect(jsonPath("$.page.size").value(20)) + .andExpect(jsonPath("$.page.number").value(0)) + .andExpect(jsonPath("$.page.totalElements").value(1)) + .andExpect(jsonPath("$.page.totalPages").value(1)); + } + + @Test + void listRejectsBadPaging() throws Exception { + mvc.perform(get("/api/v1/meal-plans?size=101").principal(USER)) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(get("/api/v1/meal-plans?page=-1").principal(USER)) + .andExpect(status().isBadRequest()); + mvc.perform(get("/api/v1/meal-plans?size=0").principal(USER)) + .andExpect(status().isBadRequest()); + verifyNoInteractions(mealPlanService); + } + + @Test + void createReturns201WithLocation() throws Exception { + when(mealPlanService.create(EMAIL, WEEK)).thenReturn(new MealPlanResponse(67L, WEEK, List.of())); + + mvc.perform(json(post("/api/v1/meal-plans"), "{\"weekStart\":\"2026-10-05\"}")) + .andExpect(status().isCreated()) + .andExpect(header().string("Location", "/api/v1/meal-plans/67")) + .andExpect(jsonPath("$.entries").isEmpty()); + } + + @Test + void createRejectsMissingOrInvalidDate() throws Exception { + mvc.perform(json(post("/api/v1/meal-plans"), "{}")) + .andExpect(status().isBadRequest()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)); + mvc.perform(json(post("/api/v1/meal-plans"), "{\"weekStart\":\"2026-13-40\"}")) + .andExpect(status().isBadRequest()); + verifyNoInteractions(mealPlanService); + } + + @Test + void updateChangesWeek() throws Exception { + LocalDate next = LocalDate.of(2026, 10, 12); + when(mealPlanService.update(EMAIL, 67L, next)).thenReturn(new MealPlanResponse(67L, next, List.of())); + + mvc.perform(json(patch("/api/v1/meal-plans/67"), "{\"weekStart\":\"2026-10-12\"}")) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.weekStart").value("2026-10-12")); + } + + @Test + void updateRejectsEmptyOrInvalidBody() throws Exception { + mvc.perform(json(patch("/api/v1/meal-plans/67"), "{}")) + .andExpect(status().isBadRequest()); + mvc.perform(json(patch("/api/v1/meal-plans/67"), "{\"weekStart\":\"not-a-date\"}")) + .andExpect(status().isBadRequest()); + verifyNoInteractions(mealPlanService); + } + + @Test + void deleteReturns204() throws Exception { + mvc.perform(delete("/api/v1/meal-plans/67").principal(USER)) + .andExpect(status().isNoContent()) + .andExpect(content().string("")); + verify(mealPlanService).delete(EMAIL, 67L); + } + + @Test + void notFoundIsProblemDetails() throws Exception { + when(mealPlanService.get(eq(EMAIL), any())).thenThrow( + new ResponseStatusException(HttpStatus.NOT_FOUND, "Meal plan 99 not found")); + + mvc.perform(get("/api/v1/meal-plans/99").principal(USER)) + .andExpect(status().isNotFound()) + .andExpect(content().contentType(MediaType.APPLICATION_PROBLEM_JSON)) + .andExpect(jsonPath("$.status").value(404)) + .andExpect(jsonPath("$.title").value("Not Found")) + .andExpect(jsonPath("$.detail").value("Meal plan 99 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 new file mode 100644 index 0000000..735688d --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceJpaTest.java @@ -0,0 +1,76 @@ +package edu.csumb.cst438.api; + +import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.service.MealPlanService; +import jakarta.persistence.EntityManager; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.data.jpa.test.autoconfigure.DataJpaTest; +import org.springframework.context.annotation.Import; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Runs MealPlanService against a real database to check the queries and cascades. + */ +@DataJpaTest +@ActiveProfiles("test") +@Import(MealPlanService.class) +public class MealPlanServiceJpaTest { + @Autowired + private EntityManager entityManager; + + @Autowired + private MealPlanService mealPlanService; + + /** + * Deleting a meal plan deletes its entries but keeps the recipes + */ + @Test + void deleteKeepsRecipes() { + 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.delete("owner@example.com", mealPlan.getId()); + entityManager.flush(); + entityManager.clear(); + + assertThat(entityManager.find(MealPlan.class, mealPlan.getId())).isNull(); + assertThat(entityManager.find(MealPlanEntry.class, entry.getId())).isNull(); + assertThat(entityManager.find(Recipe.class, recipe.getId())).isNotNull(); + } + + /** + * Another user's meal plan is not found, and only the user's own plans are listed + */ + @Test + void otherUsersPlanIsHidden() { + 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 othersPlan = new MealPlan(other, LocalDate.of(2026, 10, 5)); + entityManager.persist(othersPlan); + entityManager.persist(new MealPlan(owner, LocalDate.of(2026, 10, 12))); + entityManager.flush(); + entityManager.clear(); + + assertThatThrownBy(() -> mealPlanService.get("owner@example.com", othersPlan.getId())) + .isInstanceOf(ResponseStatusException.class); + assertThat(mealPlanService.list("owner@example.com", 0, 20).getContent()) + .singleElement() + .satisfies(p -> assertThat(p.weekStart()).isEqualTo(LocalDate.of(2026, 10, 12))); + } +} diff --git a/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java new file mode 100644 index 0000000..8822750 --- /dev/null +++ b/api/src/test/java/edu/csumb/cst438/api/MealPlanServiceTest.java @@ -0,0 +1,140 @@ +package edu.csumb.cst438.api; + +import edu.csumb.cst438.api.entity.*; +import edu.csumb.cst438.api.record.MealPlanResponse; +import edu.csumb.cst438.api.repository.MealPlanRepository; +import edu.csumb.cst438.api.service.MealPlanService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.domain.Page; +import org.springframework.data.domain.Pageable; +import org.springframework.http.HttpStatus; +import org.springframework.web.server.ResponseStatusException; + +import java.time.LocalDate; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +public class MealPlanServiceTest { + private static final String EMAIL = "owner@example.com"; + private static final LocalDate WEEK = LocalDate.of(2026, 10, 5); + + @Mock + private MealPlanRepository mealPlanRepository; + + @InjectMocks + private MealPlanService mealPlanService; + + private User owner; + + @BeforeEach + void setUp() { + owner = new User(EMAIL, "Owner", "USER"); + } + + private void signedIn() { + when(mealPlanRepository.findUserByEmail(EMAIL)).thenReturn(Optional.of(owner)); + } + + private void assertStatus(Runnable call, HttpStatus status) { + assertThatThrownBy(call::run) + .isInstanceOfSatisfying(ResponseStatusException.class, + e -> assertThat(e.getStatusCode()).isEqualTo(status)); + } + + /** + * A user that isn't in the database cannot use meal plans + */ + @Test + void unknownUserIsUnauthorized() { + when(mealPlanRepository.findUserByEmail(EMAIL)).thenReturn(Optional.empty()); + + assertStatus(() -> mealPlanService.get(EMAIL, 1L), HttpStatus.UNAUTHORIZED); + } + + /** + * Missing meal plans and other users' meal plans are both 404 for get, update, and delete + */ + @Test + void notOwnedMealPlanIsNotFound() { + signedIn(); + when(mealPlanRepository.findByIdAndOwner(7L, owner)).thenReturn(Optional.empty()); + + 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); + } + + /** + * An empty result is still a page, with no content + */ + @Test + void listEmpty() { + signedIn(); + when(mealPlanRepository.findByOwner(eq(owner), any(Pageable.class))).thenReturn(Page.empty()); + + Page result = mealPlanService.list(EMAIL, 0, 20); + + assertThat(result.getContent()).isEmpty(); + } + + /** + * A new meal plan belongs to the signed-in user and has no entries + */ + @Test + void createIsOwnedAndEmpty() { + signedIn(); + when(mealPlanRepository.save(any(MealPlan.class))).thenAnswer(inv -> inv.getArgument(0)); + + MealPlanResponse created = mealPlanService.create(EMAIL, WEEK); + + assertThat(created.weekStart()).isEqualTo(WEEK); + assertThat(created.entries()).isEmpty(); + assertThat(owner.getMealPlans()).hasSize(1); + assertThat(owner.getMealPlans().getFirst().getOwner()).isSameAs(owner); + } + + /** + * Updating the week keeps the existing entries + */ + @Test + void updateKeepsEntries() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + Recipe recipe = new Recipe("Pizza", null, "Eat it", owner); + new MealPlanEntry(mealPlan, recipe, WEEK, mealType.DINNER); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + + MealPlanResponse updated = mealPlanService.update(EMAIL, 1L, LocalDate.of(2026, 10, 12)); + + assertThat(updated.weekStart()).isEqualTo(LocalDate.of(2026, 10, 12)); + assertThat(updated.entries()).hasSize(1); + assertThat(updated.entries().getFirst().mealType()).isEqualTo(mealType.DINNER); + } + + /** + * Deleting removes the meal plan from its owner + */ + @Test + void deleteRemovesFromOwner() { + signedIn(); + MealPlan mealPlan = new MealPlan(owner, WEEK); + when(mealPlanRepository.findByIdAndOwner(1L, owner)).thenReturn(Optional.of(mealPlan)); + + mealPlanService.delete(EMAIL, 1L); + + assertThat(owner.getMealPlans()).isEmpty(); + verify(mealPlanRepository).findByIdAndOwner(1L, owner); + } +}