Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down
Original file line number Diff line number Diff line change
@@ -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<MealPlanResponse> 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<MealPlanResponse> 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<Void> deleteMealPlan(Principal principal, @PathVariable Long mealPlanId) {
mealPlanService.delete(principal.getName(), mealPlanId);
return ResponseEntity.noContent().build();
}
}
13 changes: 13 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/entity/MealPlan.java
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*/
Expand Down
Original file line number Diff line number Diff line change
@@ -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) {
}
Original file line number Diff line number Diff line change
@@ -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());
}
}
Original file line number Diff line number Diff line change
@@ -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) {
}
Original file line number Diff line number Diff line change
@@ -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<MealPlanEntryResponse> 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());
}
}
Original file line number Diff line number Diff line change
@@ -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<MealPlan, Long> {

/**
* 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<MealPlan> 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<MealPlan> 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<User> 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<User> findUserByEmail(String email);
}
114 changes: 114 additions & 0 deletions api/src/main/java/edu/csumb/cst438/api/service/MealPlanService.java
Original file line number Diff line number Diff line change
@@ -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<MealPlanResponse> 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"));
}
}
Loading
Loading