mirror of
https://gitlab.com/etc404/software-engineering-project.git
synced 2026-05-10 20:52:58 +00:00
The Unpopular Decision
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
package com.example.demo;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class RecipeDemoApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(RecipeDemoApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.example.demo.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig {
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
|
||||
// Allow your frontend origin (adjust if different)
|
||||
config.setAllowedOrigins(List.of("http://localhost:8080/",
|
||||
"http://localhost:5173"));
|
||||
|
||||
// Allow common HTTP methods
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS"));
|
||||
|
||||
// Allow headers like Authorization (for JWT later)
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
|
||||
// Allow cookies if using sessions
|
||||
config.setAllowCredentials(true);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package com.example.demo.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.csrf.CsrfAuthenticationStrategy;
|
||||
|
||||
@Configuration
|
||||
public class SecurityConfig {
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/login", "/register", "/css/**", "/images/**").permitAll()
|
||||
.requestMatchers("/api/users").permitAll()
|
||||
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.formLogin(form -> form
|
||||
.loginPage("/login")
|
||||
.defaultSuccessUrl("/", true)
|
||||
.permitAll()
|
||||
)
|
||||
.logout(logout -> logout.permitAll());
|
||||
|
||||
return http.build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.service.UserService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/admin")
|
||||
public class AdminController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
public AdminController(UserService userService) {
|
||||
this.userService = userService;
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/ban")
|
||||
public ResponseEntity<UserDto> banUser(@PathVariable Integer id) {
|
||||
return new ResponseEntity<>(userService.banUser(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/unban")
|
||||
public ResponseEntity<UserDto> unbanUser(@PathVariable Integer id) {
|
||||
return new ResponseEntity<>(userService.unbanUser(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/make-admin")
|
||||
public ResponseEntity<UserDto> makeAdmin(@PathVariable Integer id) {
|
||||
return new ResponseEntity<>(userService.makeAdmin(id), HttpStatus.OK);
|
||||
}
|
||||
|
||||
@PostMapping("/users/{id}/make-user")
|
||||
public ResponseEntity<UserDto> makeUser(@PathVariable Integer id) {
|
||||
return new ResponseEntity<>(userService.makeUser(id), HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
public class AuthController {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalValidationHandler {
|
||||
|
||||
@ExceptionHandler(ConstraintViolationException.class)
|
||||
public ResponseEntity<Map<String, String>> handleConstraintViolation(ConstraintViolationException ex) {
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
ex.getConstraintViolations().forEach(violation -> {
|
||||
String fieldPath = violation.getPropertyPath().toString();
|
||||
errors.put(fieldPath, violation.getMessage());
|
||||
});
|
||||
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
public ResponseEntity<Map<String, String>> handleValidationExceptions(MethodArgumentNotValidException ex) {
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
ex.getBindingResult().getFieldErrors().forEach(error -> {
|
||||
errors.put(error.getField(), error.getDefaultMessage());
|
||||
});
|
||||
return new ResponseEntity<>(errors, HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping("/api/health")
|
||||
public Map<String, Object> healthCheck() {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
|
||||
response.put("status", "UP");
|
||||
response.put("timestamp", LocalDateTime.now());
|
||||
response.put("service", "Recipe Backend");
|
||||
|
||||
return response;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import org.springframework.security.core.Authentication;
|
||||
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.entity.Recipe;
|
||||
import com.example.demo.entity.User;
|
||||
import com.example.demo.service.RecipeService;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/recipes")
|
||||
public class RecipeController {
|
||||
|
||||
private RecipeService recipeService;
|
||||
|
||||
public RecipeController(RecipeService recipeService) {
|
||||
super();
|
||||
this.recipeService = recipeService;
|
||||
}
|
||||
|
||||
// build create recipe REST API
|
||||
@PostMapping
|
||||
public ResponseEntity<RecipeDto> saveRecipe(@RequestBody RecipeDto recipeDto, Authentication authentication) {
|
||||
String currentUsername = authentication.getName();
|
||||
return new ResponseEntity<>(recipeService.saveRecipe(recipeDto, currentUsername), HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
// build get all recipes REST API
|
||||
@GetMapping
|
||||
public List<RecipeDto> getAllRecipes() {
|
||||
return recipeService.getAllRecipes();
|
||||
}
|
||||
|
||||
// build get recipe by id REST API
|
||||
// http://localhost:8080/api/recipes/(id number goes here)
|
||||
@GetMapping("{id}")
|
||||
public ResponseEntity<RecipeDto> getRecipeById(@PathVariable("id") Integer recipeId) {
|
||||
return new ResponseEntity<RecipeDto>(recipeService.getRecipeById(recipeId), HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build get recipe by name REST API
|
||||
@GetMapping("/search")
|
||||
public ResponseEntity<List<RecipeDto>> searchRecipes(
|
||||
@RequestParam(required = false) String name, // by not adding a name all recipes will appear basically
|
||||
@RequestParam(required = false) List<String> tags // since users can choose no tags this isnt required
|
||||
) {
|
||||
|
||||
|
||||
|
||||
List<RecipeDto> recipes = recipeService.getRecipes(name, tags);
|
||||
return new ResponseEntity<>(recipes, HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build update recipe REST API
|
||||
// http://localhost:8080/api/recipes/(id number goes here)
|
||||
@PutMapping("{id}")
|
||||
public ResponseEntity<RecipeDto> updateRecipe(
|
||||
@PathVariable("id") Integer recipeId,
|
||||
@RequestBody RecipeDto recipeDto,
|
||||
Authentication authentication) {
|
||||
String currentUsername = authentication.getName();
|
||||
return new ResponseEntity<>(recipeService.updateRecipe(recipeDto, recipeId, currentUsername), HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build delete recipe REST API
|
||||
// http://localhost:8080/api/recipes/(id number goes here)
|
||||
@DeleteMapping("{id}")
|
||||
public ResponseEntity<String> deleteRecipe(@PathVariable("id") Integer recipeId, Authentication authentication) {
|
||||
String currentUsername = authentication.getName();
|
||||
recipeService.deleteRecipe(recipeId, currentUsername);
|
||||
return new ResponseEntity<>("Recipe deleted successfully!", HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import com.example.demo.service.RecipeService;
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.entity.Recipe;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
@Controller
|
||||
public class SiteController {
|
||||
|
||||
private final RecipeService recipeService;
|
||||
|
||||
public SiteController(RecipeService recipeService) {
|
||||
this.recipeService = recipeService;
|
||||
}
|
||||
@GetMapping("/")
|
||||
public String viewHomePage(Model model) {
|
||||
//model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee());
|
||||
List<RecipeDto> recipes = recipeService.getAllRecipes();
|
||||
model.addAttribute("recipes", recipes);
|
||||
return "home";
|
||||
}
|
||||
|
||||
@GetMapping("/login")
|
||||
public String viewLoginPage(Model model) {
|
||||
return "login";
|
||||
}
|
||||
|
||||
@GetMapping("/register")
|
||||
public String viewRegisterPage(Model model) {
|
||||
return "create-account";
|
||||
}
|
||||
|
||||
@GetMapping("/create")
|
||||
public String viewCreatePage(Model model) {
|
||||
return "create-recipe";
|
||||
}
|
||||
|
||||
@GetMapping("/recipes/{id}")
|
||||
public String viewRecipe(@PathVariable Integer id, Model model) {
|
||||
RecipeDto recipe = recipeService.getRecipeById(id);
|
||||
model.addAttribute("recipe", recipe);
|
||||
return "view-recipe";
|
||||
}
|
||||
|
||||
@GetMapping("/explore")
|
||||
public String viewExplorePage(Model model) {
|
||||
//model.addAttribute("allemplist", employeeServiceImpl.getAllEmployee());
|
||||
List<RecipeDto> recipes = recipeService.getAllRecipes();
|
||||
model.addAttribute("recipes", recipes);
|
||||
return "explore";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.security.Principal;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.entity.User;
|
||||
import com.example.demo.repository.UserRepo;
|
||||
import com.example.demo.service.UserService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/users")
|
||||
public class UserController {
|
||||
|
||||
private UserService userService;
|
||||
private UserRepo userRepo;
|
||||
|
||||
public UserController(UserService userService, UserRepo userRepo) {
|
||||
super();
|
||||
this.userService = userService;
|
||||
this.userRepo = userRepo;
|
||||
}
|
||||
|
||||
// build create user REST API
|
||||
@PostMapping
|
||||
public ResponseEntity<User> saveUser(@RequestBody User user) {
|
||||
|
||||
return new ResponseEntity<User>(userService.saveUser(user), HttpStatus.CREATED);
|
||||
}
|
||||
|
||||
// build get all users REST API
|
||||
@GetMapping
|
||||
public List<UserDto> getAllUsers() {
|
||||
return userService.getAllUsers();
|
||||
}
|
||||
|
||||
// build get user by name REST API
|
||||
@GetMapping("/search")
|
||||
public ResponseEntity<List<UserDto>> getUsersByName(@RequestParam String name) {
|
||||
List<UserDto> users = userService.getUsersByName(name);
|
||||
return new ResponseEntity<>(users, HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build get current user REST API
|
||||
@GetMapping("/me")
|
||||
public UserDto getLoggedInUser(Principal principal) {
|
||||
if (principal == null) return null;
|
||||
String username = principal.getName();
|
||||
User user = (userRepo.findByUsername(username))
|
||||
.orElse(null);
|
||||
return userService.convertToDto(user);
|
||||
}
|
||||
|
||||
// build get user by id REST API
|
||||
// http://localhost:8080/api/users/(id number goes here)
|
||||
@GetMapping("{id}")
|
||||
public ResponseEntity<UserDto> getUserById(@PathVariable("id") Integer userId) {
|
||||
return new ResponseEntity<UserDto>(userService.getUserById(userId), HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build create favorite REST API
|
||||
@PostMapping("/{userId}/favorites/{recipeId}")
|
||||
public ResponseEntity<UserDto> saveFavorite(@PathVariable Integer userId, @PathVariable Integer recipeId) {
|
||||
|
||||
UserDto updatedUser = userService.saveFavorite(userId, recipeId);
|
||||
|
||||
return new ResponseEntity<>(updatedUser, HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build update user REST API
|
||||
// http://localhost:8080/api/users/(id number goes here)
|
||||
@PutMapping("{id}")
|
||||
public ResponseEntity<UserDto> updateUser(@PathVariable("id") Integer userId, @RequestBody User user) {
|
||||
return new ResponseEntity<UserDto>(userService.updateUser(user, userId), HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build delete user REST API
|
||||
@DeleteMapping("{id}")
|
||||
public ResponseEntity<String> deleteUser(@PathVariable("id") Integer userId) {
|
||||
userService.deleteUser(userId);
|
||||
return new ResponseEntity<String>("User deleted succesfully!", HttpStatus.OK);
|
||||
}
|
||||
|
||||
// build delete favorite REST API
|
||||
@DeleteMapping("/{userId}/favorites/{recipeId}")
|
||||
public ResponseEntity<String> deleteFavorite(@PathVariable Integer userId, @PathVariable Integer recipeId) {
|
||||
|
||||
userService.deleteFavorite(userId, recipeId);
|
||||
return new ResponseEntity<String>("Favorite deleted succesfully!", HttpStatus.OK);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class AuthResponse {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class ImageDto {
|
||||
String imageUrl;
|
||||
|
||||
public ImageDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public ImageDto(String imageUrl) {
|
||||
super();
|
||||
this.imageUrl = imageUrl;
|
||||
}
|
||||
|
||||
public String getImageUrl() {
|
||||
return imageUrl;
|
||||
}
|
||||
|
||||
public void setImageUrl(String imageUrl) {
|
||||
this.imageUrl = imageUrl;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
|
||||
public class IngredientDto {
|
||||
|
||||
@NotBlank(message = "ingredientName is required")
|
||||
private String ingredientName;
|
||||
|
||||
@PositiveOrZero(message = "quantity must be 0 or greater")
|
||||
private BigDecimal quantity;
|
||||
|
||||
private String unit;
|
||||
|
||||
public String getIngredientName() { return ingredientName; }
|
||||
public void setIngredientName(String ingredientName) { this.ingredientName = ingredientName; }
|
||||
|
||||
public @PositiveOrZero(message = "quantity must be 0 or greater") BigDecimal getQuantity() { return quantity; }
|
||||
public void setQuantity(BigDecimal bigDecimal) { this.quantity = bigDecimal; }
|
||||
|
||||
public String getUnit() { return unit; }
|
||||
public void setUnit(String unit) { this.unit = unit; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class LoginRequest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.example.demo.dto.StepDto;
|
||||
|
||||
public class RecipeCreateRequest {
|
||||
|
||||
@NotBlank(message = "title is required")
|
||||
@Size(max = 100, message = "title must be 100 characters or less")
|
||||
private String title;
|
||||
|
||||
@Size(max = 1000, message = "description must be 1000 characters or less")
|
||||
private String description;
|
||||
|
||||
@PositiveOrZero(message = "prepTimeMinutes must be 0 or greater")
|
||||
private int prepTimeMinutes;
|
||||
|
||||
@PositiveOrZero(message = "cookTimeMinutes must be 0 or greater")
|
||||
private int cookTimeMinutes;
|
||||
|
||||
@PositiveOrZero(message = "servings must be 0 or greater")
|
||||
private int servings;
|
||||
|
||||
@NotNull(message = "ingredients list is required")
|
||||
@Valid
|
||||
private java.util.List<IngredientDto> ingredients;
|
||||
|
||||
@NotNull(message = "steps list is required")
|
||||
@Valid
|
||||
private java.util.List<StepDto> steps;
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public int getPrepTimeMinutes() { return prepTimeMinutes; }
|
||||
public void setPrepTimeMinutes(int prepTimeMinutes) { this.prepTimeMinutes = prepTimeMinutes; }
|
||||
|
||||
public int getCookTimeMinutes() { return cookTimeMinutes; }
|
||||
public void setCookTimeMinutes(int cookTimeMinutes) { this.cookTimeMinutes = cookTimeMinutes; }
|
||||
|
||||
public int getServings() { return servings; }
|
||||
public void setServings(int servings) { this.servings = servings; }
|
||||
|
||||
public java.util.List<IngredientDto> getIngredients() { return ingredients; }
|
||||
public void setIngredients(java.util.List<IngredientDto> ingredients) { this.ingredients = ingredients; }
|
||||
|
||||
public java.util.List<StepDto> getSteps() { return steps; }
|
||||
public void setSteps(java.util.List<StepDto> steps) { this.steps = steps; }
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.example.demo.entity.Recipe;
|
||||
|
||||
public class RecipeDto {
|
||||
private String title;
|
||||
private String description;
|
||||
private Integer prepTimeMinutes;
|
||||
private Integer cookTimeMinutes;
|
||||
private Integer servings;
|
||||
private UserDto userDto;
|
||||
private String status;
|
||||
private Integer id;
|
||||
private List<RecipeIngredientDto> ingredients;
|
||||
private List<StepDto> steps;
|
||||
private List<ImageDto> images;
|
||||
private List<TagDto> tags;
|
||||
|
||||
public RecipeDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public RecipeDto(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes,
|
||||
Integer servings, UserDto userDto, String status, List<RecipeIngredientDto> ingredients,
|
||||
List<StepDto> steps, List<ImageDto> images, List<TagDto> tags) {
|
||||
super();
|
||||
this.title = title;
|
||||
this.description = description;
|
||||
this.prepTimeMinutes = prepTimeMinutes;
|
||||
this.cookTimeMinutes = cookTimeMinutes;
|
||||
this.servings = servings;
|
||||
this.userDto = userDto;
|
||||
this.status = status;
|
||||
this.ingredients = ingredients;
|
||||
this.steps = steps;
|
||||
this.images = images;
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getPrepTimeMinutes() {
|
||||
return prepTimeMinutes;
|
||||
}
|
||||
|
||||
public void setPrepTimeMinutes(Integer prepTimeMinutes) {
|
||||
this.prepTimeMinutes = prepTimeMinutes;
|
||||
}
|
||||
|
||||
public Integer getCookTimeMinutes() {
|
||||
return cookTimeMinutes;
|
||||
}
|
||||
|
||||
public void setCookTimeMinutes(Integer cookTimeMinutes) {
|
||||
this.cookTimeMinutes = cookTimeMinutes;
|
||||
}
|
||||
|
||||
public Integer getServings() {
|
||||
return servings;
|
||||
}
|
||||
|
||||
public void setServings(Integer servings) {
|
||||
this.servings = servings;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public List<RecipeIngredientDto> getIngredients() {
|
||||
return ingredients;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setIngredients(List<RecipeIngredientDto> ingredients) {
|
||||
this.ingredients = ingredients;
|
||||
}
|
||||
|
||||
public List<StepDto> getSteps() {
|
||||
return steps;
|
||||
}
|
||||
|
||||
public void setSteps(List<StepDto> steps) {
|
||||
this.steps = steps;
|
||||
}
|
||||
|
||||
public List<ImageDto> getImages() {
|
||||
return images;
|
||||
}
|
||||
|
||||
public void setImages(List<ImageDto> images) {
|
||||
this.images = images;
|
||||
}
|
||||
|
||||
public List<TagDto> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(List<TagDto> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
public UserDto getUserDto() {
|
||||
return userDto;
|
||||
}
|
||||
|
||||
public void setUserDto(UserDto userDto) {
|
||||
this.userDto = userDto;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
public class RecipeIngredientDto {
|
||||
private String ingredientName;
|
||||
private BigDecimal quantity;
|
||||
private String unit;
|
||||
private String notes;
|
||||
|
||||
public RecipeIngredientDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public RecipeIngredientDto(String ingredientName, BigDecimal quantity, String unit, String notes) {
|
||||
super();
|
||||
this.ingredientName = ingredientName;
|
||||
this.quantity = quantity;
|
||||
this.unit = unit;
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
// getters and setters
|
||||
public String getIngredientName() {
|
||||
return ingredientName;
|
||||
}
|
||||
|
||||
public void setIngredientName(String ingredientName) {
|
||||
this.ingredientName = ingredientName;
|
||||
}
|
||||
|
||||
public BigDecimal getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(BigDecimal quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
public String getNotes() {
|
||||
return notes;
|
||||
}
|
||||
|
||||
public void setNotes(String notes) {
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import com.example.demo.dto.StepDto;
|
||||
|
||||
public class RecipeResponse {
|
||||
|
||||
private Long id;
|
||||
private String title;
|
||||
private String description;
|
||||
|
||||
private int prepTimeMinutes;
|
||||
private int cookTimeMinutes;
|
||||
private int servings;
|
||||
|
||||
private List<IngredientDto> ingredients;
|
||||
private List<StepDto> steps;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public int getPrepTimeMinutes() { return prepTimeMinutes; }
|
||||
public void setPrepTimeMinutes(int prepTimeMinutes) { this.prepTimeMinutes = prepTimeMinutes; }
|
||||
|
||||
public int getCookTimeMinutes() { return cookTimeMinutes; }
|
||||
public void setCookTimeMinutes(int cookTimeMinutes) { this.cookTimeMinutes = cookTimeMinutes; }
|
||||
|
||||
public int getServings() { return servings; }
|
||||
public void setServings(int servings) { this.servings = servings; }
|
||||
|
||||
public List<IngredientDto> getIngredients() { return ingredients; }
|
||||
public void setIngredients(List<IngredientDto> ingredients) { this.ingredients = ingredients; }
|
||||
|
||||
public List<StepDto> getSteps() { return steps; }
|
||||
public void setSteps(List<StepDto> steps) { this.steps = steps; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.example.demo.dto.StepDto;
|
||||
|
||||
public class RecipeUpdateRequest {
|
||||
|
||||
@NotBlank(message = "title is required")
|
||||
@Size(max = 100, message = "title must be 100 characters or less")
|
||||
private String title;
|
||||
|
||||
@Size(max = 1000, message = "description must be 1000 characters or less")
|
||||
private String description;
|
||||
|
||||
@PositiveOrZero(message = "prepTimeMinutes must be 0 or greater")
|
||||
private int prepTimeMinutes;
|
||||
|
||||
@PositiveOrZero(message = "cookTimeMinutes must be 0 or greater")
|
||||
private int cookTimeMinutes;
|
||||
|
||||
@PositiveOrZero(message = "servings must be 0 or greater")
|
||||
private int servings;
|
||||
|
||||
@NotNull(message = "ingredients list is required")
|
||||
@Valid
|
||||
private List<IngredientDto> ingredients;
|
||||
|
||||
@NotNull(message = "steps list is required")
|
||||
@Valid
|
||||
private List<StepDto> steps;
|
||||
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public int getPrepTimeMinutes() { return prepTimeMinutes; }
|
||||
public void setPrepTimeMinutes(int prepTimeMinutes) { this.prepTimeMinutes = prepTimeMinutes; }
|
||||
|
||||
public int getCookTimeMinutes() { return cookTimeMinutes; }
|
||||
public void setCookTimeMinutes(int cookTimeMinutes) { this.cookTimeMinutes = cookTimeMinutes; }
|
||||
|
||||
public int getServings() { return servings; }
|
||||
public void setServings(int servings) { this.servings = servings; }
|
||||
|
||||
public List<IngredientDto> getIngredients() { return ingredients; }
|
||||
public void setIngredients(List<IngredientDto> ingredients) { this.ingredients = ingredients; }
|
||||
|
||||
public List<StepDto> getSteps() { return steps; }
|
||||
public void setSteps(List<StepDto> steps) { this.steps = steps; }
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class RegisterRequest {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class StepDto {
|
||||
private Integer stepNumber;
|
||||
private String instruction;
|
||||
|
||||
public StepDto() {
|
||||
}
|
||||
|
||||
public StepDto(Integer stepNumber, String instruction) {
|
||||
this.stepNumber = stepNumber;
|
||||
this.instruction = instruction;
|
||||
}
|
||||
|
||||
public Integer getStepNumber() {
|
||||
return stepNumber;
|
||||
}
|
||||
|
||||
public void setStepNumber(Integer stepNumber) {
|
||||
this.stepNumber = stepNumber;
|
||||
}
|
||||
|
||||
public String getInstruction() {
|
||||
return instruction;
|
||||
}
|
||||
|
||||
public void setInstruction(String instruction) {
|
||||
this.instruction = instruction;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class TagDto {
|
||||
private String name;
|
||||
|
||||
public TagDto() {
|
||||
super();
|
||||
}
|
||||
|
||||
public TagDto(String name) {
|
||||
super();
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package com.example.demo.dto;
|
||||
|
||||
public class UserDto {
|
||||
private Integer id;
|
||||
private String username;
|
||||
private String email;
|
||||
|
||||
public UserDto() {
|
||||
}
|
||||
|
||||
public UserDto(Integer id, String username, String email) {
|
||||
this.id = id;
|
||||
this.username = username;
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "favorites")
|
||||
public class Favorite {
|
||||
|
||||
@EmbeddedId
|
||||
private FavoriteId id;
|
||||
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public Favorite() {}
|
||||
|
||||
public Favorite(Integer userId, Integer recipeId) {
|
||||
this.id = new FavoriteId(userId, recipeId);
|
||||
this.createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public FavoriteId getId() { return id; }
|
||||
public void setId(FavoriteId id) { this.id = id; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Embeddable
|
||||
public class FavoriteId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 7241804509064720087L;
|
||||
private Integer userId;
|
||||
private Integer recipeId;
|
||||
|
||||
public FavoriteId() {}
|
||||
|
||||
public FavoriteId(Integer userId, Integer recipeId) {
|
||||
this.userId = userId;
|
||||
this.recipeId = recipeId;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getUserId() { return userId; }
|
||||
public void setUserId(Integer userId) { this.userId = userId; }
|
||||
|
||||
public Integer getRecipeId() { return recipeId; }
|
||||
public void setRecipeId(Integer recipeId) { this.recipeId = recipeId; }
|
||||
|
||||
// equals and hashCode required for composite keys
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (!(o instanceof FavoriteId)) return false;
|
||||
FavoriteId that = (FavoriteId) o;
|
||||
return Objects.equals(userId, that.userId) &&
|
||||
Objects.equals(recipeId, that.recipeId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(userId, recipeId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Entity
|
||||
@Table(name = "recipe_images")
|
||||
public class Image {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "recipe_id", nullable = false)
|
||||
@EqualsAndHashCode.Include
|
||||
private Recipe recipe;
|
||||
|
||||
@Column(name = "image_url", nullable = false)
|
||||
private String imageUrl;
|
||||
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
public Image() {
|
||||
}
|
||||
|
||||
public Image(Recipe recipe, String imageUrl) {
|
||||
this.recipe = recipe;
|
||||
this.imageUrl = imageUrl;
|
||||
this.createdAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Recipe getRecipe() {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
public void setRecipe(Recipe recipe) {
|
||||
this.recipe = recipe;
|
||||
}
|
||||
|
||||
public String getImageUrl() {
|
||||
return imageUrl;
|
||||
}
|
||||
|
||||
public void setImageUrl(String imageUrl) {
|
||||
this.imageUrl = imageUrl;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
|
||||
@Entity
|
||||
@Table(name = "ingredients", uniqueConstraints = { @UniqueConstraint(columnNames = "name") })
|
||||
public class Ingredient {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(nullable = false, unique = true,columnDefinition = "TEXT")
|
||||
@NotBlank(message = "Please provide an ingredient name")
|
||||
@Size(max = 128, message = "Name cannot be longer than 128 characters")
|
||||
private String name;
|
||||
|
||||
@OneToMany(mappedBy = "ingredient")
|
||||
private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
|
||||
|
||||
public Ingredient() {
|
||||
}
|
||||
|
||||
public Ingredient(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<RecipeIngredient> getRecipeIngredients() {
|
||||
return recipeIngredients;
|
||||
}
|
||||
|
||||
public void setRecipeIngredients(Set<RecipeIngredient> recipeIngredients) {
|
||||
this.recipeIngredients = recipeIngredients;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "recipes")
|
||||
public class Recipe {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@NotBlank(message = "Please provide a recipe title")
|
||||
private String title;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
private String description;
|
||||
|
||||
@NotNull(message = "Please Provide a prep time amount in mintutes")
|
||||
@Positive(message = "This value cannot be negative")
|
||||
private Integer prepTimeMinutes;
|
||||
|
||||
@NotNull(message = "Please Provide a cook time amount in mintutes")
|
||||
@Positive(message = "This value cannot be negative")
|
||||
private Integer cookTimeMinutes;
|
||||
|
||||
@NotNull(message = "Please Provide a serving amount")
|
||||
@Positive(message = "This value cannot be negative")
|
||||
private Integer servings;
|
||||
|
||||
private String status;
|
||||
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
@NotNull(message = "Recipe must be associated with a user")
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "user_id", nullable = false)
|
||||
@EqualsAndHashCode.Include
|
||||
private User user;
|
||||
|
||||
// Recipe ingredients relationship
|
||||
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
@NotEmpty(message = "At least one ingredient is required")
|
||||
private Set<RecipeIngredient> recipeIngredients = new HashSet<>();
|
||||
|
||||
// Recipe Steps relationship
|
||||
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private Set<Step> steps = new HashSet<>();
|
||||
|
||||
// Recipe Images relationship
|
||||
@OneToMany(mappedBy = "recipe", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private Set<Image> images = new HashSet<>();
|
||||
|
||||
// Recipe Tag relationship and also junction table
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(name = "recipe_tags", joinColumns = { @JoinColumn(name = "recipe_id") }, inverseJoinColumns = {
|
||||
@JoinColumn(name = "tag_id") })
|
||||
private Set<Tag> tags = new HashSet<>();
|
||||
|
||||
// User is the manager for this relationship
|
||||
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "FavRecipes")
|
||||
private Set<User> users = new HashSet<>();
|
||||
|
||||
public Recipe() {
|
||||
}
|
||||
|
||||
public Recipe(String title, String description, Integer prepTimeMinutes, Integer cookTimeMinutes, Integer servings,
|
||||
User user, String status) {
|
||||
this.title = title;
|
||||
this.description = description;
|
||||
this.prepTimeMinutes = prepTimeMinutes;
|
||||
this.cookTimeMinutes = cookTimeMinutes;
|
||||
this.servings = servings;
|
||||
this.user = user;
|
||||
this.status = status;
|
||||
this.createdAt = LocalDateTime.now();
|
||||
this.updatedAt = LocalDateTime.now();
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public User getUser() {
|
||||
return user;
|
||||
}
|
||||
|
||||
public void setUser(User user) {
|
||||
this.user = user;
|
||||
}
|
||||
|
||||
public String getTitle() {
|
||||
return title;
|
||||
}
|
||||
|
||||
public void setTitle(String title) {
|
||||
this.title = title;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public Integer getPrepTimeMinutes() {
|
||||
return prepTimeMinutes;
|
||||
}
|
||||
|
||||
public void setPrepTimeMinutes(Integer prepTimeMinutes) {
|
||||
this.prepTimeMinutes = prepTimeMinutes;
|
||||
}
|
||||
|
||||
public Integer getCookTimeMinutes() {
|
||||
return cookTimeMinutes;
|
||||
}
|
||||
|
||||
public void setCookTimeMinutes(Integer cookTimeMinutes) {
|
||||
this.cookTimeMinutes = cookTimeMinutes;
|
||||
}
|
||||
|
||||
public Integer getServings() {
|
||||
return servings;
|
||||
}
|
||||
|
||||
public void setServings(Integer servings) {
|
||||
this.servings = servings;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getUpdatedAt() {
|
||||
return updatedAt;
|
||||
}
|
||||
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) {
|
||||
this.updatedAt = updatedAt;
|
||||
}
|
||||
|
||||
public Set<RecipeIngredient> getRecipeIngredients() {
|
||||
return recipeIngredients;
|
||||
}
|
||||
|
||||
public void setRecipeIngredients(Set<RecipeIngredient> recipeIngredients) {
|
||||
this.recipeIngredients = recipeIngredients;
|
||||
}
|
||||
|
||||
public Set<Step> getSteps() {
|
||||
return steps;
|
||||
}
|
||||
|
||||
public void setSteps(Set<Step> steps) {
|
||||
this.steps = steps;
|
||||
}
|
||||
|
||||
public Set<Image> getImages() {
|
||||
return images;
|
||||
}
|
||||
|
||||
public void setImages(Set<Image> images) {
|
||||
this.images = images;
|
||||
}
|
||||
|
||||
public Set<Tag> getTags() {
|
||||
return tags;
|
||||
}
|
||||
|
||||
public void setTags(Set<Tag> tags) {
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
public Set<User> getUsers() {
|
||||
return users;
|
||||
}
|
||||
|
||||
public void setUsers(Set<User> users) {
|
||||
this.users = users;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Positive;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Entity
|
||||
@Table(name = "recipe_ingredient_junction", uniqueConstraints = {
|
||||
@UniqueConstraint(columnNames = { "recipe_id", "ingredient_id" }) })
|
||||
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
|
||||
public class RecipeIngredient {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "recipe_id", nullable = false)
|
||||
@EqualsAndHashCode.Include
|
||||
private Recipe recipe;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "ingredient_id", nullable = false)
|
||||
@EqualsAndHashCode.Include
|
||||
private Ingredient ingredient;
|
||||
|
||||
@NotNull(message = "Please Provide a Quantity")
|
||||
@Positive(message = "Quantity cannot be negative")
|
||||
private BigDecimal quantity;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
@Size(max = 32, message = "Unit cannot be longer than 32 characters")
|
||||
private String unit;
|
||||
|
||||
@Column(columnDefinition = "TEXT")
|
||||
@Size(max = 128, message = "Note cannot be longer than 128 characters")
|
||||
private String notes;
|
||||
|
||||
public RecipeIngredient() {
|
||||
}
|
||||
|
||||
public RecipeIngredient(Recipe recipe, Ingredient ingredient, BigDecimal quantity, String unit, String notes) {
|
||||
this.recipe = recipe;
|
||||
this.ingredient = ingredient;
|
||||
this.quantity = quantity;
|
||||
this.unit = unit;
|
||||
this.notes = notes;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Recipe getRecipe() {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
public void setRecipe(Recipe recipe) {
|
||||
this.recipe = recipe;
|
||||
}
|
||||
|
||||
public Ingredient getIngredient() {
|
||||
return ingredient;
|
||||
}
|
||||
|
||||
public void setIngredient(Ingredient ingredient) {
|
||||
this.ingredient = ingredient;
|
||||
}
|
||||
|
||||
public BigDecimal getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(BigDecimal quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public String getUnit() {
|
||||
return unit;
|
||||
}
|
||||
|
||||
public void setUnit(String unit) {
|
||||
this.unit = unit;
|
||||
}
|
||||
|
||||
public String getNotes() {
|
||||
return notes;
|
||||
}
|
||||
|
||||
public void setNotes(String notes) {
|
||||
this.notes = notes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "recipe_tags")
|
||||
public class RecipeTag {
|
||||
|
||||
@EmbeddedId
|
||||
private RecipeTagId id;
|
||||
|
||||
@ManyToOne
|
||||
@MapsId("recipeId")
|
||||
@JoinColumn(name = "recipe_id", nullable = false)
|
||||
private Recipe recipe;
|
||||
|
||||
@ManyToOne
|
||||
@MapsId("tagId")
|
||||
@JoinColumn(name = "tag_id", nullable = false)
|
||||
private Tag tag;
|
||||
|
||||
public RecipeTag() {}
|
||||
|
||||
public RecipeTag(Recipe recipe, Tag tag) {
|
||||
this.recipe = recipe;
|
||||
this.tag = tag;
|
||||
this.id = new RecipeTagId(recipe.getId(), tag.getId());
|
||||
}
|
||||
|
||||
public RecipeTagId getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(RecipeTagId id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Recipe getRecipe() {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
public Tag getTag() {
|
||||
return tag;
|
||||
}
|
||||
|
||||
public void setRecipe(Recipe recipe) {
|
||||
this.recipe = recipe;
|
||||
}
|
||||
|
||||
public void setTag(Tag tag) {
|
||||
this.tag = tag;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Embeddable;
|
||||
import java.io.Serializable;
|
||||
import java.util.Objects;
|
||||
|
||||
@Embeddable
|
||||
public class RecipeTagId implements Serializable {
|
||||
|
||||
private static final long serialVersionUID = 5272431101708393749L;
|
||||
|
||||
@Column(name = "recipe_id")
|
||||
private Integer recipeId;
|
||||
|
||||
@Column(name = "tag_id")
|
||||
private Integer tagId;
|
||||
|
||||
public RecipeTagId() {
|
||||
}
|
||||
|
||||
public RecipeTagId(Integer recipeId, Integer tagId) {
|
||||
this.recipeId = recipeId;
|
||||
this.tagId = tagId;
|
||||
}
|
||||
|
||||
public Integer getRecipeId() {
|
||||
return recipeId;
|
||||
}
|
||||
|
||||
public void setRecipeId(Integer recipeId) {
|
||||
this.recipeId = recipeId;
|
||||
}
|
||||
|
||||
public Integer getTagId() {
|
||||
return tagId;
|
||||
}
|
||||
|
||||
public void setTagId(Integer tagId) {
|
||||
this.tagId = tagId;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o)
|
||||
return true;
|
||||
if (!(o instanceof RecipeTagId))
|
||||
return false;
|
||||
RecipeTagId that = (RecipeTagId) o;
|
||||
return Objects.equals(recipeId, that.recipeId) && Objects.equals(tagId, that.tagId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return Objects.hash(recipeId, tagId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
@Entity
|
||||
@Table(name = "steps")
|
||||
public class Step {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(name = "step_number", nullable = false)
|
||||
private Integer stepNumber;
|
||||
|
||||
@Column(name = "instruction", nullable = false, columnDefinition = "TEXT")
|
||||
@Size(max = 500, message = "Instruction cannot be longer than 500 characters")
|
||||
private String instruction;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "recipe_id", nullable = false)
|
||||
@EqualsAndHashCode.Include
|
||||
private Recipe recipe;
|
||||
|
||||
public Step() {
|
||||
}
|
||||
|
||||
public Step(Recipe recipe, Integer stepNumber, String instruction) {
|
||||
this.recipe = recipe;
|
||||
this.stepNumber = stepNumber;
|
||||
this.instruction = instruction;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public Recipe getRecipe() {
|
||||
return recipe;
|
||||
}
|
||||
|
||||
public void setRecipe(Recipe recipe) {
|
||||
this.recipe = recipe;
|
||||
}
|
||||
|
||||
public Integer getStepNumber() {
|
||||
return stepNumber;
|
||||
}
|
||||
|
||||
public void setStepNumber(Integer stepNumber) {
|
||||
this.stepNumber = stepNumber;
|
||||
}
|
||||
|
||||
public String getInstruction() {
|
||||
return instruction;
|
||||
}
|
||||
|
||||
public void setInstruction(String instruction) {
|
||||
this.instruction = instruction;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
|
||||
@Entity
|
||||
@Table(name = "tags")
|
||||
public class Tag {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String name;
|
||||
|
||||
// Recipe is the manager for this relationship
|
||||
@ManyToMany(fetch = FetchType.LAZY, mappedBy = "tags")
|
||||
private Set<Recipe> recipes = new HashSet<>();
|
||||
|
||||
public Tag() {
|
||||
}
|
||||
|
||||
public Tag(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
// Getters and setters
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public Set<Recipe> getRecipes() {
|
||||
return recipes;
|
||||
}
|
||||
|
||||
public void setRecipes(Set<Recipe> recipes) {
|
||||
this.recipes = recipes;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package com.example.demo.entity;
|
||||
|
||||
import jakarta.persistence.CascadeType;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.GenerationType;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.JoinTable;
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.Table;
|
||||
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
import org.springframework.security.core.authority.SimpleGrantedAuthority;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
@Entity
|
||||
@Table(name = "users")
|
||||
public class User implements UserDetails {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Integer id;
|
||||
|
||||
@Column(nullable = false, unique = true)
|
||||
private String username;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String role;
|
||||
|
||||
@Column(unique = true)
|
||||
private String email;
|
||||
|
||||
private String hashedpassword;
|
||||
|
||||
@Column(name = "created_at")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean banned = false;
|
||||
|
||||
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.LAZY)
|
||||
private Set<Recipe> recipes = new HashSet<>();
|
||||
|
||||
@ManyToMany(fetch = FetchType.LAZY)
|
||||
@JoinTable(
|
||||
name = "favorites",
|
||||
joinColumns = { @JoinColumn(name = "userId") },
|
||||
inverseJoinColumns = { @JoinColumn(name = "recipeId") }
|
||||
)
|
||||
private Set<Recipe> FavRecipes = new HashSet<>();
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return List.of(new SimpleGrantedAuthority(role));
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getPassword() {
|
||||
return hashedpassword;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getUsername() {
|
||||
return username;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAccountNonLocked() {
|
||||
return !banned;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isCredentialsNonExpired() {
|
||||
return true;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isEnabled() {
|
||||
return !banned;
|
||||
}
|
||||
|
||||
public User() {
|
||||
}
|
||||
|
||||
public User(String username, String role, String email, String hashedpassword, LocalDateTime createdAt) {
|
||||
this.username = username;
|
||||
this.role = role;
|
||||
this.email = email;
|
||||
this.hashedpassword = hashedpassword;
|
||||
this.createdAt = createdAt;
|
||||
this.banned = false;
|
||||
}
|
||||
|
||||
public Integer getId() {
|
||||
return id;
|
||||
}
|
||||
|
||||
public void setId(Integer id) {
|
||||
this.id = id;
|
||||
}
|
||||
|
||||
public void setUsername(String username) {
|
||||
this.username = username;
|
||||
}
|
||||
|
||||
public String getRole() {
|
||||
return role;
|
||||
}
|
||||
|
||||
public void setRole(String role) {
|
||||
this.role = role;
|
||||
}
|
||||
|
||||
public String getEmail() {
|
||||
return email;
|
||||
}
|
||||
|
||||
public void setEmail(String email) {
|
||||
this.email = email;
|
||||
}
|
||||
|
||||
public String getHashedpassword() {
|
||||
return hashedpassword;
|
||||
}
|
||||
|
||||
public void setHashedpassword(String hashedpassword) {
|
||||
this.hashedpassword = hashedpassword;
|
||||
}
|
||||
|
||||
public LocalDateTime getCreatedAt() {
|
||||
return createdAt;
|
||||
}
|
||||
|
||||
public void setCreatedAt(LocalDateTime createdAt) {
|
||||
this.createdAt = createdAt;
|
||||
}
|
||||
|
||||
public boolean isBanned() {
|
||||
return banned;
|
||||
}
|
||||
|
||||
public void setBanned(boolean banned) {
|
||||
this.banned = banned;
|
||||
}
|
||||
|
||||
public Set<Recipe> getRecipes() {
|
||||
return recipes;
|
||||
}
|
||||
|
||||
public void setRecipes(Set<Recipe> recipes) {
|
||||
this.recipes = recipes;
|
||||
}
|
||||
|
||||
public Set<Recipe> getFavRecipes() {
|
||||
return FavRecipes;
|
||||
}
|
||||
|
||||
public void setFavRecipes(Set<Recipe> favRecipes) {
|
||||
this.FavRecipes = favRecipes;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
public class BadRequestException {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
public class ErrorResponse {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package com.example.demo.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(value = HttpStatus.NOT_FOUND)
|
||||
public class NotFoundException extends RuntimeException {
|
||||
|
||||
private static final long serialVersionUID = 1l;
|
||||
private String resourceName;
|
||||
private String fieldName;
|
||||
private Object fieldValue;
|
||||
|
||||
public NotFoundException(String resourceName, String fieldName, Object fieldValue) {
|
||||
super(String.format("%s not found with %s : %s", resourceName, fieldName, fieldValue));
|
||||
this.resourceName = resourceName;
|
||||
this.fieldName = fieldName;
|
||||
this.fieldValue = fieldValue;
|
||||
}
|
||||
|
||||
public String getResourceName() {
|
||||
return resourceName;
|
||||
}
|
||||
|
||||
public String getFieldName() {
|
||||
return fieldName;
|
||||
}
|
||||
|
||||
public Object getFieldValue() {
|
||||
return fieldValue;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.example.demo.entity.Favorite;
|
||||
import com.example.demo.entity.FavoriteId;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface FavoriteRepo extends JpaRepository<Favorite, FavoriteId> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.example.demo.entity.Image;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface ImageRepo extends JpaRepository<Image, Integer> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.example.demo.entity.Ingredient;
|
||||
|
||||
public interface IngredientRepo extends JpaRepository<Ingredient, Integer> {
|
||||
Optional<Ingredient> findByNameIgnoreCase(String name);
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.example.demo.entity.Recipe;
|
||||
import com.example.demo.entity.RecipeIngredient;
|
||||
|
||||
public interface RecipeIngredientRepo extends JpaRepository<RecipeIngredient, Integer> {
|
||||
// Custom query: find all ingredients for a recipe
|
||||
List<RecipeIngredient> findByRecipeId(Integer recipeId);
|
||||
void deleteByRecipe(Recipe recipe);
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.example.demo.entity.Recipe;
|
||||
|
||||
public interface RecipeRepo extends JpaRepository<Recipe, Integer> {
|
||||
|
||||
List<Recipe> findByTitleContainingIgnoreCase(String name);
|
||||
List<Recipe> findByTitleContainingIgnoreCaseAndTags_NameIn(String title, List<String> tags);
|
||||
|
||||
long countByUserIdAndCreatedAtAfter(Integer userId, LocalDateTime after);
|
||||
|
||||
List<Recipe> findByUserId(Integer userId);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import com.example.demo.entity.RecipeTag;
|
||||
import com.example.demo.entity.RecipeTagId;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface RecipeTagRepo extends JpaRepository<RecipeTag, RecipeTagId> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.example.demo.entity.Step;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface StepRepo extends JpaRepository<Step, Integer> {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.example.demo.entity.Ingredient;
|
||||
import com.example.demo.entity.Tag;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
public interface TagRepo extends JpaRepository<Tag, Integer> {
|
||||
Optional<Tag> findByName(String name);
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.example.demo.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.example.demo.entity.User;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
public interface UserRepo extends JpaRepository<User, Integer> {
|
||||
|
||||
Optional<User> findByUsername(String username);
|
||||
|
||||
List<User> findByUsernameContainingIgnoreCase(String name);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
public class AuthService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import com.example.demo.repository.UserRepo;
|
||||
import org.jspecify.annotations.NonNull;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.core.userdetails.UserDetailsService;
|
||||
import org.springframework.security.core.userdetails.UsernameNotFoundException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
@Service
|
||||
public class CustomUserDetailsService implements UserDetailsService {
|
||||
|
||||
private final UserRepo userRepo;
|
||||
|
||||
public CustomUserDetailsService(UserRepo userRepo) {
|
||||
this.userRepo = userRepo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
|
||||
return userRepo.findByUsername(username)
|
||||
.orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package com.example.demo.service.Impl;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.dto.StepDto;
|
||||
import com.example.demo.dto.TagDto;
|
||||
import com.example.demo.dto.ImageDto;
|
||||
import com.example.demo.dto.RecipeIngredientDto;
|
||||
import com.example.demo.entity.Image;
|
||||
import com.example.demo.entity.Ingredient;
|
||||
import com.example.demo.entity.Recipe;
|
||||
import com.example.demo.entity.RecipeIngredient;
|
||||
import com.example.demo.entity.Step;
|
||||
import com.example.demo.entity.Tag;
|
||||
import com.example.demo.entity.User;
|
||||
import com.example.demo.exception.NotFoundException;
|
||||
import com.example.demo.repository.ImageRepo;
|
||||
import com.example.demo.repository.IngredientRepo;
|
||||
import com.example.demo.repository.RecipeIngredientRepo;
|
||||
import com.example.demo.repository.RecipeRepo;
|
||||
import com.example.demo.repository.StepRepo;
|
||||
import com.example.demo.repository.TagRepo;
|
||||
import com.example.demo.repository.UserRepo;
|
||||
import com.example.demo.service.RecipeService;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@Service
|
||||
public class RecipeServiceImpl implements RecipeService {
|
||||
|
||||
private RecipeRepo recipeRepository;
|
||||
private IngredientRepo ingredientRepository;
|
||||
private RecipeIngredientRepo recipeIngredientRepository;
|
||||
private UserRepo userRepository;
|
||||
private StepRepo stepRepository;
|
||||
private ImageRepo imageRepository;
|
||||
private TagRepo tagRepository;
|
||||
|
||||
public RecipeServiceImpl(RecipeRepo recipeRepository, IngredientRepo ingredientRepository,
|
||||
RecipeIngredientRepo recipeIngredientRepository, UserRepo userRepository, StepRepo stepRepository,
|
||||
ImageRepo imageRepository, TagRepo tagRepository) {
|
||||
super();
|
||||
this.recipeRepository = recipeRepository;
|
||||
this.ingredientRepository = ingredientRepository;
|
||||
this.recipeIngredientRepository = recipeIngredientRepository;
|
||||
this.userRepository = userRepository;
|
||||
this.stepRepository = stepRepository;
|
||||
this.imageRepository = imageRepository;
|
||||
this.tagRepository = tagRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecipeDto convertToDto(Recipe recipe) {
|
||||
List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
|
||||
.map(ri -> new RecipeIngredientDto(ri.getIngredient().getName(), ri.getQuantity(), ri.getUnit(),
|
||||
ri.getNotes()))
|
||||
.toList();
|
||||
|
||||
List<StepDto> stepDtos = recipe.getSteps().stream()
|
||||
.map(ri -> new StepDto(ri.getStepNumber(), ri.getInstruction())).toList();
|
||||
|
||||
List<ImageDto> imageDtos = recipe.getImages().stream().map(ri -> new ImageDto(ri.getImageUrl())).toList();
|
||||
|
||||
List<TagDto> tagDtos = recipe.getTags().stream().map(ri -> new TagDto(ri.getName())).toList();
|
||||
|
||||
UserDto userDto = new UserDto(recipe.getUser().getId(), recipe.getUser().getUsername(),
|
||||
recipe.getUser().getEmail());
|
||||
|
||||
RecipeDto dto = new RecipeDto(recipe.getTitle(), recipe.getDescription(), recipe.getPrepTimeMinutes(),
|
||||
recipe.getCookTimeMinutes(), recipe.getServings(), userDto, recipe.getStatus(), ingredientDtos,
|
||||
stepDtos, imageDtos, tagDtos);
|
||||
|
||||
dto.setId(recipe.getId());
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
private User getCurrentUser(String currentUsername) {
|
||||
return userRepository.findByUsername(currentUsername)
|
||||
.orElseThrow(() -> new NotFoundException("User", "username", currentUsername));
|
||||
}
|
||||
|
||||
private boolean isAdmin(User user) {
|
||||
return "ROLE_ADMIN".equals(user.getRole());
|
||||
}
|
||||
|
||||
private void ensureUserNotBanned(User user) {
|
||||
if (user.isBanned()) {
|
||||
throw new AccessDeniedException("Banned users cannot perform this action.");
|
||||
}
|
||||
}
|
||||
|
||||
private void enforceUploadLimit(User user) {
|
||||
if (isAdmin(user)) {
|
||||
return;
|
||||
}
|
||||
|
||||
LocalDateTime cutoff = LocalDateTime.now().minusHours(24);
|
||||
long uploadsInLast24Hours = recipeRepository.countByUserIdAndCreatedAtAfter(user.getId(), cutoff);
|
||||
|
||||
if (uploadsInLast24Hours >= 10) {
|
||||
throw new AccessDeniedException("Upload limit reached. Maximum is 10 recipes per 24 hours.");
|
||||
}
|
||||
}
|
||||
|
||||
private void enforceOwnerOrAdmin(User currentUser, Recipe recipe) {
|
||||
if (isAdmin(currentUser)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!recipe.getUser().getId().equals(currentUser.getId())) {
|
||||
throw new AccessDeniedException("You do not have permission to modify this recipe.");
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public RecipeDto saveRecipe(RecipeDto dto, String currentUsername) {
|
||||
|
||||
User currentUser = getCurrentUser(currentUsername);
|
||||
ensureUserNotBanned(currentUser);
|
||||
enforceUploadLimit(currentUser);
|
||||
|
||||
Recipe recipe = new Recipe(dto.getTitle(), dto.getDescription(), dto.getPrepTimeMinutes(),
|
||||
dto.getCookTimeMinutes(), dto.getServings(), currentUser, dto.getStatus());
|
||||
|
||||
if (dto.getIngredients() != null) {
|
||||
for (RecipeIngredientDto riDto : dto.getIngredients()) {
|
||||
|
||||
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
|
||||
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
|
||||
|
||||
if (ingredient.getId() == null) {
|
||||
ingredientRepository.save(ingredient);
|
||||
}
|
||||
|
||||
RecipeIngredient ri = new RecipeIngredient(recipe, ingredient, riDto.getQuantity(), riDto.getUnit(),
|
||||
riDto.getNotes());
|
||||
|
||||
recipe.getRecipeIngredients().add(ri);
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.getSteps() != null) {
|
||||
for (StepDto stepDto : dto.getSteps()) {
|
||||
Step step = new Step(recipe, stepDto.getStepNumber(), stepDto.getInstruction());
|
||||
recipe.getSteps().add(step);
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.getImages() != null) {
|
||||
for (ImageDto imageDto : dto.getImages()) {
|
||||
Image image = new Image(recipe, imageDto.getImageUrl());
|
||||
recipe.getImages().add(image);
|
||||
}
|
||||
}
|
||||
|
||||
if (dto.getTags() != null) {
|
||||
for (TagDto tDto : dto.getTags()) {
|
||||
|
||||
Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));
|
||||
|
||||
if (tag.getId() == null) {
|
||||
tagRepository.save(tag);
|
||||
}
|
||||
recipe.getTags().add(tag);
|
||||
}
|
||||
}
|
||||
|
||||
Recipe saved = recipeRepository.save(recipe);
|
||||
|
||||
return getRecipeById(saved.getId());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public List<RecipeDto> getAllRecipes() {
|
||||
|
||||
List<RecipeDto> list = new ArrayList<>();
|
||||
for (Recipe recipe : recipeRepository.findAll()) {
|
||||
RecipeDto recipeDto = convertToDto(recipe);
|
||||
list.add(recipeDto);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public RecipeDto getRecipeById(Integer Id) {
|
||||
return convertToDto(recipeRepository.findById(Id).orElseThrow(() -> new NotFoundException("Recipe", "id", Id)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public RecipeDto updateRecipe(RecipeDto recipeDto, Integer id, String currentUsername) {
|
||||
User currentUser = getCurrentUser(currentUsername);
|
||||
ensureUserNotBanned(currentUser);
|
||||
|
||||
Recipe existingRecipe = recipeRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Recipe", "id", id));
|
||||
|
||||
enforceOwnerOrAdmin(currentUser, existingRecipe);
|
||||
|
||||
existingRecipe.setTitle(recipeDto.getTitle());
|
||||
existingRecipe.setDescription(recipeDto.getDescription());
|
||||
existingRecipe.setPrepTimeMinutes(recipeDto.getPrepTimeMinutes());
|
||||
existingRecipe.setCookTimeMinutes(recipeDto.getCookTimeMinutes());
|
||||
existingRecipe.setServings(recipeDto.getServings());
|
||||
existingRecipe.setStatus(recipeDto.getStatus());
|
||||
|
||||
List<RecipeIngredientDto> updatedIngredients = recipeDto.getIngredients();
|
||||
List<RecipeIngredient> ingredientsToRemove = new ArrayList<>();
|
||||
|
||||
List<StepDto> updatedSteps = recipeDto.getSteps();
|
||||
List<Step> stepsToRemove = new ArrayList<>();
|
||||
|
||||
List<ImageDto> updatedImages = recipeDto.getImages();
|
||||
List<Image> imagesToRemove = new ArrayList<>();
|
||||
|
||||
List<TagDto> updatedTags = recipeDto.getTags();
|
||||
List<Tag> tagsToRemove = new ArrayList<>();
|
||||
|
||||
for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) {
|
||||
|
||||
boolean existsInUpdatedList = false;
|
||||
for (RecipeIngredientDto dto : updatedIngredients) {
|
||||
String updatedName = dto.getIngredientName();
|
||||
String existingName = ri.getIngredient().getName();
|
||||
|
||||
if (updatedName.equals(existingName)) {
|
||||
existsInUpdatedList = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!existsInUpdatedList) {
|
||||
ingredientsToRemove.add(ri);
|
||||
}
|
||||
}
|
||||
|
||||
existingRecipe.getRecipeIngredients().removeAll(ingredientsToRemove);
|
||||
|
||||
for (RecipeIngredientDto riDto : updatedIngredients) {
|
||||
|
||||
RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
|
||||
.filter(ri -> ri.getIngredient().getName().equals(riDto.getIngredientName())).findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (existingRI != null) {
|
||||
|
||||
existingRI.setQuantity(riDto.getQuantity());
|
||||
existingRI.setUnit(riDto.getUnit());
|
||||
existingRI.setNotes(riDto.getNotes());
|
||||
}
|
||||
|
||||
else {
|
||||
|
||||
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
|
||||
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
|
||||
|
||||
if (ingredient.getId() == null) {
|
||||
ingredientRepository.save(ingredient);
|
||||
}
|
||||
|
||||
RecipeIngredient newRI = new RecipeIngredient(existingRecipe, ingredient, riDto.getQuantity(),
|
||||
riDto.getUnit(), riDto.getNotes());
|
||||
|
||||
existingRecipe.getRecipeIngredients().add(newRI);
|
||||
}
|
||||
}
|
||||
|
||||
if (updatedSteps != null) {
|
||||
for (Step step : existingRecipe.getSteps()) {
|
||||
boolean existsInUpdatedList = updatedSteps.stream()
|
||||
.anyMatch(dto -> dto.getStepNumber().equals(step.getStepNumber()));
|
||||
|
||||
if (!existsInUpdatedList)
|
||||
stepsToRemove.add(step);
|
||||
}
|
||||
existingRecipe.getSteps().removeAll(stepsToRemove);
|
||||
|
||||
for (StepDto stepDto : updatedSteps) {
|
||||
|
||||
Step existingStep = existingRecipe.getSteps().stream()
|
||||
.filter(s -> s.getStepNumber().equals(stepDto.getStepNumber())).findFirst().orElse(null);
|
||||
|
||||
if (existingStep != null) {
|
||||
existingStep.setInstruction(stepDto.getInstruction());
|
||||
}
|
||||
|
||||
else {
|
||||
Step newStep = new Step(existingRecipe, stepDto.getStepNumber(), stepDto.getInstruction());
|
||||
existingRecipe.getSteps().add(newStep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updatedImages != null) {
|
||||
for (Image image : existingRecipe.getImages()) {
|
||||
boolean existsInUpdatedList = updatedImages.stream()
|
||||
.anyMatch(dto -> dto.getImageUrl().equals(image.getImageUrl()));
|
||||
if (!existsInUpdatedList)
|
||||
imagesToRemove.add(image);
|
||||
}
|
||||
|
||||
existingRecipe.getImages().removeAll(imagesToRemove);
|
||||
|
||||
for (ImageDto imageDto : updatedImages) {
|
||||
Image existingImage = existingRecipe.getImages().stream()
|
||||
.filter(img -> img.getImageUrl().equals(imageDto.getImageUrl())).findFirst().orElse(null);
|
||||
|
||||
if (existingImage != null) {
|
||||
existingImage.setImageUrl(imageDto.getImageUrl());
|
||||
} else {
|
||||
Image newImage = new Image(existingRecipe, imageDto.getImageUrl());
|
||||
existingRecipe.getImages().add(newImage);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updatedTags != null) {
|
||||
for (Tag tag : existingRecipe.getTags()) {
|
||||
boolean existsInUpdatedList = updatedTags.stream().anyMatch(dto -> dto.getName().equals(tag.getName()));
|
||||
if (!existsInUpdatedList)
|
||||
tagsToRemove.add(tag);
|
||||
}
|
||||
|
||||
existingRecipe.getTags().removeAll(tagsToRemove);
|
||||
|
||||
for (TagDto tagDto : updatedTags) {
|
||||
Tag existingTag = existingRecipe.getTags().stream()
|
||||
.filter(tag -> tag.getName().equals(tagDto.getName())).findFirst().orElse(null);
|
||||
|
||||
if (existingTag != null) {
|
||||
existingTag.setName(tagDto.getName());
|
||||
} else {
|
||||
Tag newTag = tagRepository.findByName(tagDto.getName())
|
||||
.orElseGet(() -> tagRepository.save(new Tag(tagDto.getName())));
|
||||
|
||||
existingRecipe.getTags().add(newTag);
|
||||
}
|
||||
}
|
||||
}
|
||||
recipeRepository.save(existingRecipe);
|
||||
return convertToDto(existingRecipe);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteRecipe(Integer id, String currentUsername) {
|
||||
User currentUser = getCurrentUser(currentUsername);
|
||||
ensureUserNotBanned(currentUser);
|
||||
|
||||
Recipe recipe = recipeRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("Recipe", "id", id));
|
||||
|
||||
enforceOwnerOrAdmin(currentUser, recipe);
|
||||
recipeRepository.delete(recipe);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public List<RecipeDto> getRecipes(String name, List<String> tags) {
|
||||
|
||||
List<Recipe> recipes;
|
||||
|
||||
if (!name.isBlank()) {
|
||||
recipes = recipeRepository.findByTitleContainingIgnoreCase(name);
|
||||
}
|
||||
|
||||
else {
|
||||
recipes = recipeRepository.findAll();
|
||||
}
|
||||
|
||||
if (!tags.isEmpty() && !recipes.isEmpty()) {
|
||||
recipes = recipes.stream()
|
||||
.filter(recipe -> recipe.getTags().stream().anyMatch(tag -> tags.contains(tag.getName())))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<RecipeDto> recipeList = new ArrayList<>();
|
||||
|
||||
for (Recipe recipe : recipes) {
|
||||
RecipeDto dto = convertToDto(recipe);
|
||||
recipeList.add(dto);
|
||||
}
|
||||
|
||||
return recipeList;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
package com.example.demo.service.Impl;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import com.example.demo.dto.ImageDto;
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.dto.RecipeIngredientDto;
|
||||
import com.example.demo.dto.StepDto;
|
||||
import com.example.demo.dto.TagDto;
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.entity.Recipe;
|
||||
import com.example.demo.entity.User;
|
||||
import com.example.demo.exception.NotFoundException;
|
||||
import com.example.demo.repository.RecipeRepo;
|
||||
import com.example.demo.repository.UserRepo;
|
||||
import com.example.demo.service.UserService;
|
||||
|
||||
import jakarta.transaction.Transactional;
|
||||
|
||||
@Service
|
||||
public class UserServiceImpl implements UserService {
|
||||
|
||||
private UserRepo userRepository;
|
||||
private RecipeRepo recipeRepository;
|
||||
|
||||
public UserServiceImpl(UserRepo userRepository, RecipeRepo recipeRepository) {
|
||||
super();
|
||||
this.userRepository = userRepository;
|
||||
this.recipeRepository = recipeRepository;
|
||||
}
|
||||
|
||||
public UserDto convertToDto(User user) {
|
||||
return new UserDto(user.getId(), user.getUsername(), user.getEmail());
|
||||
}
|
||||
|
||||
@Override
|
||||
public User saveUser(User user) {
|
||||
if (user.getRole() == null || user.getRole().isBlank()) {
|
||||
user.setRole("ROLE_USER");
|
||||
}
|
||||
user.setBanned(false);
|
||||
return userRepository.save(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserDto> getAllUsers() {
|
||||
|
||||
List<UserDto> list = new ArrayList<>();
|
||||
for (User user : userRepository.findAll()) {
|
||||
UserDto userDto = convertToDto(user);
|
||||
list.add(userDto);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto getUserById(Integer Id) {
|
||||
|
||||
return convertToDto(userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id)));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public UserDto saveFavorite(Integer userId, Integer recipeId) {
|
||||
User existingUser = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", userId));
|
||||
|
||||
Recipe existingRecipe = recipeRepository.findById(recipeId)
|
||||
.orElseThrow(() -> new NotFoundException("Recipe", "id", recipeId));
|
||||
|
||||
existingUser.getFavRecipes().add(existingRecipe);
|
||||
userRepository.save(existingUser);
|
||||
|
||||
return convertToDto(existingUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto updateUser(User user, Integer Id) {
|
||||
|
||||
User existingUser = userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id));
|
||||
|
||||
existingUser.setUsername(user.getUsername());
|
||||
existingUser.setEmail(user.getEmail());
|
||||
|
||||
userRepository.save(existingUser);
|
||||
|
||||
return convertToDto(existingUser);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteUser(Integer Id) {
|
||||
userRepository.findById(Id).orElseThrow(() -> new NotFoundException("User", "id", Id));
|
||||
userRepository.deleteById(Id);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void deleteFavorite(Integer userId, Integer recipeId) {
|
||||
User existingUser = userRepository.findById(userId)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", userId));
|
||||
|
||||
Recipe existingRecipe = recipeRepository.findById(recipeId)
|
||||
.orElseThrow(() -> new NotFoundException("Recipe", "id", recipeId));
|
||||
userRepository.save(existingUser);
|
||||
|
||||
existingUser.getFavRecipes().remove(existingRecipe);
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserDto> getUsersByName(String name) {
|
||||
List<User> users = userRepository.findByUsernameContainingIgnoreCase(name);
|
||||
|
||||
if (users.isEmpty()) {
|
||||
throw new NotFoundException("User", "username containing", name);
|
||||
}
|
||||
|
||||
List<UserDto> userList = new ArrayList<>();
|
||||
|
||||
for (User user : users) {
|
||||
UserDto dto = convertToDto(user);
|
||||
userList.add(dto);
|
||||
}
|
||||
return userList;
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto banUser(Integer id) {
|
||||
User user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", id));
|
||||
user.setBanned(true);
|
||||
userRepository.save(user);
|
||||
return convertToDto(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto unbanUser(Integer id) {
|
||||
User user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", id));
|
||||
user.setBanned(false);
|
||||
userRepository.save(user);
|
||||
return convertToDto(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto makeAdmin(Integer id) {
|
||||
User user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", id));
|
||||
user.setRole("ROLE_ADMIN");
|
||||
userRepository.save(user);
|
||||
return convertToDto(user);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserDto makeUser(Integer id) {
|
||||
User user = userRepository.findById(id)
|
||||
.orElseThrow(() -> new NotFoundException("User", "id", id));
|
||||
user.setRole("ROLE_USER");
|
||||
userRepository.save(user);
|
||||
return convertToDto(user);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
public class MapperService {
|
||||
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.entity.Recipe;
|
||||
import com.example.demo.entity.User;
|
||||
|
||||
public interface RecipeService {
|
||||
RecipeDto convertToDto(Recipe recipe);
|
||||
|
||||
RecipeDto saveRecipe(RecipeDto recipe, String currentUsername);
|
||||
|
||||
List<RecipeDto> getAllRecipes();
|
||||
|
||||
RecipeDto getRecipeById(Integer recipeId);
|
||||
|
||||
List<RecipeDto> getRecipes(String name, List<String> tags);
|
||||
|
||||
RecipeDto updateRecipe(RecipeDto recipedto, Integer Id, String currentUsername);
|
||||
|
||||
void deleteRecipe(Integer Id, String currentUsername);
|
||||
|
||||
}
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.example.demo.service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.example.demo.dto.UserDto;
|
||||
import com.example.demo.entity.User;
|
||||
|
||||
public interface UserService {
|
||||
UserDto convertToDto(User user);
|
||||
|
||||
User saveUser(User user);
|
||||
|
||||
List<UserDto> getAllUsers();
|
||||
|
||||
UserDto getUserById(Integer id);
|
||||
|
||||
List<UserDto> getUsersByName(String name);
|
||||
|
||||
UserDto saveFavorite(Integer userId, Integer recipeId);
|
||||
|
||||
UserDto updateUser(User user, Integer id);
|
||||
|
||||
void deleteUser(Integer id);
|
||||
|
||||
void deleteFavorite(Integer userId, Integer recipeId);
|
||||
|
||||
UserDto banUser(Integer id);
|
||||
|
||||
UserDto unbanUser(Integer id);
|
||||
|
||||
UserDto makeAdmin(Integer id);
|
||||
|
||||
UserDto makeUser(Integer id);
|
||||
}
|
||||
Reference in New Issue
Block a user