Update 13 files

- /src/main/java/com/example/demo/service/Impl/UserServiceImpl.java
- /src/main/java/com/example/demo/service/Impl/RecipeServiceImpl.java
- /src/main/java/com/example/demo/service/UserService.java
- /src/main/java/com/example/demo/controller/SiteController.java
- /src/main/java/com/example/demo/controller/RecipeUploadForm.java
- /src/main/java/com/example/demo/controller/ProfileController.java
- /src/main/java/com/example/demo/config/SecurityConfig.java
- /src/main/java/com/example/demo/config/WebConfig.java
- /src/main/resources/templates/explore.html
- /src/main/resources/templates/view-recipe.html
- /src/main/resources/templates/public-profile.html
- /src/main/resources/templates/my-profile.html
- /src/main/resources/templates/home.html
This commit is contained in:
Madeleine Stamp
2026-04-23 12:33:42 -06:00
parent 2ed5f11b21
commit 339cbbdf6e
13 changed files with 556 additions and 304 deletions
@@ -19,18 +19,11 @@ public class SecurityConfig {
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http http
.authorizeHttpRequests(auth -> auth .authorizeHttpRequests(auth -> auth
// public pages and static files .requestMatchers("/", "/login", "/register", "/css/**", "/images/**", "/uploads/**").permitAll()
.requestMatchers("/", "/login", "/register", "/css/**", "/images/**").permitAll()
.requestMatchers("/api/users").permitAll() .requestMatchers("/api/users").permitAll()
.requestMatchers("/api/admin/**").hasRole("ADMIN") .requestMatchers("/api/admin/**").hasRole("ADMIN")
// protected create recipe routes
.requestMatchers("/create", "/api/recipes/upload").authenticated() .requestMatchers("/create", "/api/recipes/upload").authenticated()
// protected my profile routes
.requestMatchers("/my-profile", "/my-profile/update").authenticated() .requestMatchers("/my-profile", "/my-profile/update").authenticated()
// everything else public
.anyRequest().permitAll() .anyRequest().permitAll()
) )
.formLogin(form -> form .formLogin(form -> form
@@ -3,6 +3,7 @@ package com.example.demo.config;
import java.nio.file.Path; import java.nio.file.Path;
import java.nio.file.Paths; import java.nio.file.Paths;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@@ -10,11 +11,14 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration @Configuration
public class WebConfig implements WebMvcConfigurer { public class WebConfig implements WebMvcConfigurer {
@Value("${app.upload.dir}")
private String uploadDir;
@Override @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { public void addResourceHandlers(ResourceHandlerRegistry registry) {
Path uploadPath = Paths.get("uploads").toAbsolutePath().normalize(); Path uploadPath = Paths.get(uploadDir).toAbsolutePath().normalize();
registry.addResourceHandler("/uploads/**") registry.addResourceHandler("/uploads/**")
.addResourceLocations("file:///" + uploadPath.toString().replace("\\", "/") + "/"); .addResourceLocations(uploadPath.toUri().toString());
} }
} }
@@ -23,9 +23,10 @@ public class ProfileController {
} }
@GetMapping("/users/{id}") @GetMapping("/users/{id}")
public String viewPublicProfile(@PathVariable Integer id, Model model) { public String viewPublicProfile(@PathVariable Integer id, Model model, Principal principal) {
ProfileDto profile = userService.getProfileByUserId(id); ProfileDto profile = userService.getProfileByUserId(id);
model.addAttribute("profile", profile); model.addAttribute("profile", profile);
model.addAttribute("guest", principal == null);
return "public-profile"; return "public-profile";
} }
@@ -52,3 +53,18 @@ public class ProfileController {
return "redirect:/my-profile"; return "redirect:/my-profile";
} }
} }
updateProfileDto.setBio(profile.getBio());
model.addAttribute("profile", profile);
model.addAttribute("updateProfileDto", updateProfileDto);
return "my-profile";
}
@PostMapping("/my-profile/update")
public String updateMyProfile(@ModelAttribute UpdateProfileDto dto, Principal principal) {
String username = principal.getName();
userService.updateProfile(username, dto);
return "redirect:/my-profile";
}
}
@@ -1,141 +1,233 @@
package com.example.demo.controller; package com.example.demo.controller;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.Principal;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.UUID;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartFile;
public class RecipeUploadForm { 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.service.RecipeService;
private String title; @RestController
private String description; public class RecipeUploadController {
private String prepTimeMinutes;
private String cookTimeMinutes;
private String servings;
private String cost;
private List<String> ingredientName; private final RecipeService recipeService;
private List<String> ingredientQuantity;
private List<String> ingredientUnit;
private List<String> ingredientNotes;
private List<String> stepInstruction; public RecipeUploadController(RecipeService recipeService) {
private List<String> tags; this.recipeService = recipeService;
private MultipartFile image;
private Boolean removeImage;
public RecipeUploadForm() {
} }
public String getTitle() { @PostMapping(value = "/api/recipes/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
return title; public ResponseEntity<?> createRecipeWithUpload(@ModelAttribute RecipeUploadForm form, Principal principal) {
try {
RecipeDto dto = buildRecipeDto(form, true);
String currentUsername = principal.getName();
RecipeDto saved = recipeService.saveRecipe(dto, currentUsername);
return new ResponseEntity<>(saved, HttpStatus.CREATED);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe creation failed: " + e.getMessage());
}
} }
public void setTitle(String title) { @PostMapping(value = "/api/recipes/{id}/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
this.title = title; public ResponseEntity<?> updateRecipeWithUpload(
@PathVariable Integer id,
@ModelAttribute RecipeUploadForm form,
Principal principal) {
try {
RecipeDto dto = buildRecipeDto(form, false);
String currentUsername = principal.getName();
RecipeDto updated = recipeService.updateRecipe(dto, id, currentUsername);
return new ResponseEntity<>(updated, HttpStatus.OK);
} catch (IllegalArgumentException e) {
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body("Recipe update failed: " + e.getMessage());
}
} }
public String getDescription() { private RecipeDto buildRecipeDto(RecipeUploadForm form, boolean isCreate) throws IOException {
return description; RecipeDto dto = new RecipeDto();
dto.setTitle(safeTrim(form.getTitle()));
dto.setDescription(safeTrim(form.getDescription()));
dto.setPrepTimeMinutes(parseInteger(form.getPrepTimeMinutes()));
dto.setCookTimeMinutes(parseInteger(form.getCookTimeMinutes()));
dto.setServings(parseInteger(form.getServings()));
dto.setStatus("DRAFT");
dto.setCost(parseInteger(form.getCost()));
List<RecipeIngredientDto> ingredientDtos = new ArrayList<>();
if (form.getIngredientName() != null) {
for (int i = 0; i < form.getIngredientName().size(); i++) {
String ingredientName = getListValue(form.getIngredientName(), i);
if (ingredientName == null || ingredientName.isBlank()) {
continue;
} }
public void setDescription(String description) { String quantityString = getListValue(form.getIngredientQuantity(), i);
this.description = description; BigDecimal quantity = null;
if (quantityString != null && !quantityString.isBlank()) {
quantity = parseQuantity(quantityString.trim());
} }
public String getPrepTimeMinutes() { String unit = getListValue(form.getIngredientUnit(), i);
return prepTimeMinutes; String notes = getListValue(form.getIngredientNotes(), i);
ingredientDtos.add(new RecipeIngredientDto(
ingredientName.trim(),
quantity,
unit != null ? unit.trim() : "",
notes != null ? notes.trim() : ""));
}
}
dto.setIngredients(ingredientDtos);
List<StepDto> stepDtos = new ArrayList<>();
if (form.getStepInstruction() != null) {
for (int i = 0; i < form.getStepInstruction().size(); i++) {
String instruction = form.getStepInstruction().get(i);
if (instruction == null || instruction.isBlank()) {
continue;
}
stepDtos.add(new StepDto(i + 1, instruction.trim()));
}
}
dto.setSteps(stepDtos);
List<TagDto> tagDtos = new ArrayList<>();
if (form.getTags() != null) {
for (String tag : form.getTags()) {
if (tag != null && !tag.isBlank()) {
tagDtos.add(new TagDto(tag.trim()));
}
}
}
dto.setTags(tagDtos);
MultipartFile imageFile = form.getImage();
boolean removeImage = Boolean.TRUE.equals(form.getRemoveImage());
if (imageFile != null && !imageFile.isEmpty()) {
List<ImageDto> imageDtos = new ArrayList<>();
String imageUrl = saveUploadedFile(imageFile);
imageDtos.add(new ImageDto(imageUrl));
dto.setImages(imageDtos);
} else if (removeImage) {
dto.setImages(new ArrayList<>());
} else if (isCreate) {
dto.setImages(new ArrayList<>());
} else {
dto.setImages(null);
} }
public void setPrepTimeMinutes(String prepTimeMinutes) { return dto;
this.prepTimeMinutes = prepTimeMinutes;
} }
public String getCookTimeMinutes() { private Integer parseInteger(String value) {
return cookTimeMinutes; if (value == null || value.isBlank()) {
return null;
}
return Integer.valueOf(value.trim());
} }
public void setCookTimeMinutes(String cookTimeMinutes) { private String getListValue(List<String> list, int index) {
this.cookTimeMinutes = cookTimeMinutes; if (list == null || index >= list.size()) {
return null;
}
return list.get(index);
} }
public String getServings() { private String safeTrim(String value) {
return servings; return value == null ? null : value.trim();
} }
public void setServings(String servings) { private BigDecimal parseQuantity(String value) {
this.servings = servings; String cleaned = value.trim();
if (cleaned.matches("^\\d+(\\.\\d+)?$")) {
return new BigDecimal(cleaned);
} }
public String getCost() { if (cleaned.matches("^\\d+/\\d+$")) {
return cost; String[] parts = cleaned.split("/");
BigDecimal numerator = new BigDecimal(parts[0]);
BigDecimal denominator = new BigDecimal(parts[1]);
if (denominator.compareTo(BigDecimal.ZERO) == 0) {
throw new IllegalArgumentException("Ingredient quantity cannot have a zero denominator.");
} }
public void setCost(String cost) { return numerator.divide(denominator, 8, RoundingMode.HALF_UP).stripTrailingZeros();
this.cost = cost;
} }
public List<String> getIngredientName() { if (cleaned.matches("^\\d+\\s+\\d+/\\d+$")) {
return ingredientName; String[] mixed = cleaned.split("\\s+");
BigDecimal whole = new BigDecimal(mixed[0]);
String[] fraction = mixed[1].split("/");
BigDecimal numerator = new BigDecimal(fraction[0]);
BigDecimal denominator = new BigDecimal(fraction[1]);
if (denominator.compareTo(BigDecimal.ZERO) == 0) {
throw new IllegalArgumentException("Ingredient quantity cannot have a zero denominator.");
} }
public void setIngredientName(List<String> ingredientName) { BigDecimal fractionalPart = numerator.divide(denominator, 8, RoundingMode.HALF_UP);
this.ingredientName = ingredientName; return whole.add(fractionalPart).stripTrailingZeros();
} }
public List<String> getIngredientQuantity() { throw new IllegalArgumentException(
return ingredientQuantity; "Invalid ingredient quantity: " + value + ". Use values like 1, 1.5, 1/4, or 2 1/2.");
} }
public void setIngredientQuantity(List<String> ingredientQuantity) { private String saveUploadedFile(MultipartFile file) throws IOException {
this.ingredientQuantity = ingredientQuantity; String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
String extension = "";
int dotIndex = originalFilename.lastIndexOf('.');
if (dotIndex >= 0) {
extension = originalFilename.substring(dotIndex);
} }
public List<String> getIngredientUnit() { String storedFilename = UUID.randomUUID() + extension;
return ingredientUnit;
Path uploadDir = Paths.get("uploads");
if (!Files.exists(uploadDir)) {
Files.createDirectories(uploadDir);
} }
public void setIngredientUnit(List<String> ingredientUnit) { Path destination = uploadDir.resolve(storedFilename);
this.ingredientUnit = ingredientUnit; Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
}
public List<String> getIngredientNotes() { return "/uploads/" + storedFilename;
return ingredientNotes;
}
public void setIngredientNotes(List<String> ingredientNotes) {
this.ingredientNotes = ingredientNotes;
}
public List<String> getStepInstruction() {
return stepInstruction;
}
public void setStepInstruction(List<String> stepInstruction) {
this.stepInstruction = stepInstruction;
}
public List<String> getTags() {
return tags;
}
public void setTags(List<String> tags) {
this.tags = tags;
}
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public Boolean getRemoveImage() {
return removeImage;
}
public void setRemoveImage(Boolean removeImage) {
this.removeImage = removeImage;
} }
} }
@@ -1,9 +1,11 @@
package com.example.demo.controller; package com.example.demo.controller;
import java.security.Principal;
import java.util.List; import java.util.List;
import com.example.demo.service.RecipeService;
import com.example.demo.dto.RecipeDto; import com.example.demo.dto.RecipeDto;
import com.example.demo.service.RecipeService;
import com.example.demo.service.UserService;
import org.springframework.http.ResponseEntity; import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller; import org.springframework.stereotype.Controller;
@@ -19,22 +21,29 @@ import org.springframework.web.multipart.MultipartFile;
public class SiteController { public class SiteController {
private final RecipeService recipeService; private final RecipeService recipeService;
private final UserService userService;
public SiteController(RecipeService recipeService) { public SiteController(RecipeService recipeService, UserService userService) {
this.recipeService = recipeService; this.recipeService = recipeService;
this.userService = userService;
} }
@GetMapping("/") @GetMapping("/")
public String viewHomePage(Model model) { public String viewHomePage(Model model, Principal principal) {
List<RecipeDto> recipes = recipeService.getAllRecipes(); model.addAttribute("guest", principal == null);
List<RecipeDto> newest = recipeService.getNewestRecipes(5);
model.addAttribute("recipes", recipes); if (principal == null) {
model.addAttribute("newestRecipes", newest); model.addAttribute("recipes", List.of());
} else {
model.addAttribute("recipes", userService.getFavoriteRecipesByUsername(principal.getName()));
}
return "home"; return "home";
} }
@GetMapping("/login") @GetMapping("/login")
public String viewLoginPage(Model model) { public String viewLoginPage(@RequestParam(required = false) String redirect, Model model) {
model.addAttribute("redirect", redirect);
return "login"; return "login";
} }
@@ -76,12 +85,14 @@ public class SiteController {
@RequestParam(required = false) List<Integer> prices, @RequestParam(required = false) List<Integer> prices,
@RequestParam(required = false) List<Integer> cookTime, @RequestParam(required = false) List<Integer> cookTime,
@RequestParam(required = false) List<Integer> prepTime, @RequestParam(required = false) List<Integer> prepTime,
Model model Model model,
Principal principal
) { ) {
List<RecipeDto> recipes = recipeService.getRecipes(q, tags, prices, cookTime, prepTime); List<RecipeDto> recipes = recipeService.getRecipes(q, tags, prices, cookTime, prepTime);
model.addAttribute("recipes", recipes); model.addAttribute("recipes", recipes);
model.addAttribute("q", q); model.addAttribute("q", q);
model.addAttribute("tags", tags); model.addAttribute("tags", tags);
model.addAttribute("guest", principal == null);
return "explore"; return "explore";
} }
@@ -91,4 +102,5 @@ public class SiteController {
@RequestParam("image") MultipartFile image) { @RequestParam("image") MultipartFile image) {
recipeService.updateRecipeImage(id, image); recipeService.updateRecipeImage(id, image);
return ResponseEntity.ok().build(); return ResponseEntity.ok().build();
}} }
}
@@ -142,24 +142,56 @@ public class RecipeServiceImpl implements RecipeService {
ensureUserNotBanned(currentUser); ensureUserNotBanned(currentUser);
enforceUploadLimit(currentUser); enforceUploadLimit(currentUser);
Recipe recipe = new Recipe(dto.getTitle(), dto.getDescription(), dto.getPrepTimeMinutes(), Recipe recipe = new Recipe(
dto.getCookTimeMinutes(), dto.getServings(), currentUser, dto.getStatus(), dto.getCost()); dto.getTitle(),
dto.getDescription(),
dto.getPrepTimeMinutes(),
dto.getCookTimeMinutes(),
dto.getServings(),
currentUser,
dto.getStatus(),
dto.getCost()
);
if (dto.getIngredients() != null) { if (dto.getIngredients() != null) {
for (RecipeIngredientDto riDto : dto.getIngredients()) { java.util.Set<String> seenIngredientNames = new java.util.HashSet<>();
java.util.Set<Integer> seenIngredientIds = new java.util.HashSet<>();
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName()) for (int i = 0; i < dto.getIngredients().size(); i++) {
.orElseGet(() -> new Ingredient(riDto.getIngredientName())); RecipeIngredientDto riDto = dto.getIngredients().get(i);
String rawName = riDto.getIngredientName();
String normalizedName = rawName == null ? "" : rawName.trim().toLowerCase();
if (normalizedName.isBlank()) {
continue;
}
if (!seenIngredientNames.add(normalizedName)) {
throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
}
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(rawName.trim())
.orElseGet(() -> new Ingredient(rawName.trim()));
if (ingredient.getId() == null) { if (ingredient.getId() == null) {
ingredientRepository.save(ingredient); ingredientRepository.save(ingredient);
} }
RecipeIngredient ri = new RecipeIngredient(recipe, ingredient, riDto.getQuantity(), riDto.getUnit(), if (ingredient.getId() != null && !seenIngredientIds.add(ingredient.getId())) {
riDto.getNotes()); throw new IllegalArgumentException("Duplicate ingredient entry: " + rawName.trim());
}
RecipeIngredient ri = new RecipeIngredient(
recipe,
ingredient,
riDto.getQuantity(),
riDto.getUnit(),
riDto.getNotes()
);
ri.setOrderIndex(i);
recipe.getRecipeIngredients().add(ri); recipe.getRecipeIngredients().add(ri);
} }
} }
@@ -179,7 +211,6 @@ public class RecipeServiceImpl implements RecipeService {
if (dto.getTags() != null) { if (dto.getTags() != null) {
for (TagDto tDto : dto.getTags()) { for (TagDto tDto : dto.getTags()) {
Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName())); Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));
if (tag.getId() == null) { if (tag.getId() == null) {
@@ -423,7 +454,22 @@ public class RecipeServiceImpl implements RecipeService {
if (prices != null && !prices.isEmpty() && !recipes.isEmpty()) { if (prices != null && !prices.isEmpty() && !recipes.isEmpty()) {
recipes = recipes.stream() recipes = recipes.stream()
.filter(recipe -> prices.contains(recipe.getCost())) .filter(recipe -> {
Integer cost = recipe.getCost();
if (cost == null) {
return false;
}
for (Integer price : prices) {
if (price == 4 && cost >= 4) {
return true;
}
if (price != 4 && cost.equals(price)) {
return true;
}
}
return false;
})
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
@@ -7,9 +7,9 @@ import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.example.demo.dto.ProfileDto; import com.example.demo.dto.ProfileDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UpdateProfileDto; import com.example.demo.dto.UpdateProfileDto;
import com.example.demo.dto.UserDto; import com.example.demo.dto.UserDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.entity.Recipe; import com.example.demo.entity.Recipe;
import com.example.demo.entity.User; import com.example.demo.entity.User;
import com.example.demo.exception.NotFoundException; import com.example.demo.exception.NotFoundException;
@@ -220,4 +220,19 @@ public class UserServiceImpl implements UserService {
return getProfileByUserId(user.getId()); return getProfileByUserId(user.getId());
} }
@Override
@Transactional
public List<RecipeDto> getFavoriteRecipesByUsername(String username) {
User user = userRepository.findByUsername(username)
.orElseThrow(() -> new NotFoundException("User", "username", username));
List<RecipeDto> favoriteDtos = new ArrayList<>();
for (Recipe recipe : user.getFavRecipes()) {
favoriteDtos.add(recipeService.convertToDto(recipe));
}
return favoriteDtos;
}
} }
@@ -3,6 +3,7 @@ package com.example.demo.service;
import java.util.List; import java.util.List;
import com.example.demo.dto.ProfileDto; import com.example.demo.dto.ProfileDto;
import com.example.demo.dto.RecipeDto;
import com.example.demo.dto.UpdateProfileDto; import com.example.demo.dto.UpdateProfileDto;
import com.example.demo.dto.UserDto; import com.example.demo.dto.UserDto;
import com.example.demo.entity.User; import com.example.demo.entity.User;
@@ -39,4 +40,6 @@ public interface UserService {
ProfileDto getCurrentUserProfile(String username); ProfileDto getCurrentUserProfile(String username);
ProfileDto updateProfile(String username, UpdateProfileDto dto); ProfileDto updateProfile(String username, UpdateProfileDto dto);
List<RecipeDto> getFavoriteRecipesByUsername(String username);
} }
+28 -25
View File
@@ -19,40 +19,42 @@
</header> </header>
<div class="body"> <div class="body">
<!--Navigation Bar -->
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login(redirect='/explore')}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post"> <form th:action="@{/logout}" method="post">
<input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/> <input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
</form> </form>
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon"> <a th:href="@{/create}" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol."> <img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a> </a>
</div> </div>
<!-- Main Content -->
<main class="main-content"> <main class="main-content">
<div class="search-bar"> <div class="search-bar">
<form action="/explore" method="get" id="search-form"> <form action="/explore" method="get" id="search-form">
<label for="site-search">Search:</label> <label for="site-search">Search:</label>
<div class="search-btn"> <div class="search-btn">
<div id="tag-input-wrapper"> <div id="tag-input-wrapper">
<!-- <div id="chips-container"></div> -->
<input type="text" id="site-search" name="q" th:value="${q}" placeholder="Search for recipes..."> <input type="text" id="site-search" name="q" th:value="${q}" placeholder="Search for recipes...">
</div> </div>
<button type="submit"><i class="fa fa-search"></i></button> <button type="submit"><i class="fa fa-search"></i></button>
</div> </div>
</form> </form>
</div> </div>
<p th:if="${#lists.isEmpty(recipes)}">There are no recipes that fit this description.</p> <p th:if="${#lists.isEmpty(recipes)}">There are no recipes that fit this description.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}"> <div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -72,7 +74,6 @@
</main> </main>
<!--Filter -->
<div class="body-right"> <div class="body-right">
<div class="sidebar-right"> <div class="sidebar-right">
<h1> FILTER </h1> <h1> FILTER </h1>
@@ -97,6 +98,7 @@
<label> <label>
<input type="checkbox" name="prepTime" value="241">4+ hours <input type="checkbox" name="prepTime" value="241">4+ hours
</label> </label>
<h3>Cook Time</h3> <h3>Cook Time</h3>
<label> <label>
@@ -117,6 +119,7 @@
<label> <label>
<input type="checkbox" name="cookTime" value="121">2+ hours <input type="checkbox" name="cookTime" value="121">2+ hours
</label> </label>
<h3>Price</h3> <h3>Price</h3>
<label> <label>
@@ -138,43 +141,40 @@
</div> </div>
</div> </div>
</div> </div>
<script> <script>
(function () { (function () {
const input = document.getElementById('site-search'); const input = document.getElementById('site-search');
const tags = []; const tags = [];
// Restore price checkboxes from URL
const params = new URLSearchParams(window.location.search); const params = new URLSearchParams(window.location.search);
params.getAll('prices').forEach(p => { params.getAll('prices').forEach(p => {
const cb = document.querySelector(`input[name="price"][value="${p}"]`); const cb = document.querySelector(`input[name="price"][value="${p}"]`);
if (cb) cb.checked = true; if (cb) cb.checked = true;
}); });
// Restore cookTime checkboxes from URL
params.getAll('cookTime').forEach(p => { params.getAll('cookTime').forEach(p => {
const cb = document.querySelector(`input[name="cookTime"][value="${p}"]`); const cb = document.querySelector(`input[name="cookTime"][value="${p}"]`);
if (cb) cb.checked = true; if (cb) cb.checked = true;
}); });
// Restore prepTime checkboxes from URL
params.getAll('prepTime').forEach(p => { params.getAll('prepTime').forEach(p => {
const cb = document.querySelector(`input[name="prepTime"][value="${p}"]`); const cb = document.querySelector(`input[name="prepTime"][value="${p}"]`);
if (cb) cb.checked = true; if (cb) cb.checked = true;
}); });
// Restore tag chips from URL
params.getAll('tags').forEach(addChip); params.getAll('tags').forEach(addChip);
input.addEventListener('keydown', (e) => { input.addEventListener('keydown', (e) => {
if ((e.key === ' ' || e.key === 'Enter') && input.value.includes('#')) { if ((e.key === ' ' || e.key === 'Enter') && input.value.includes('#')) {
const val = input.value + ' '; const val = input.value + ' ';
const match = val.match(/(^|\s)(#\w+)(\s)/); // NASTY regex ): const match = val.match(/(^|\s)(#\w+)(\s)/);
if (match) { if (match) {
e.preventDefault(); e.preventDefault();
addChip(match[2].substring(1)); addChip(match[2].substring(1));
input.value = val.replace(match[0], ''); input.value = val.replace(match[0], '');
input.value += ' '; input.value += ' ';
} }
} }
}); });
@@ -193,7 +193,6 @@
document.getElementById('search-form').addEventListener('submit', (e) => { document.getElementById('search-form').addEventListener('submit', (e) => {
e.preventDefault(); e.preventDefault();
submitSearch(); submitSearch();
}); });
@@ -216,13 +215,12 @@
} }
function submitSearch() { function submitSearch() {
// Only use chips for tags, not strings!
const cleanedQuery = input.value.replace(/#\w+/g, '').trim(); const cleanedQuery = input.value.replace(/#\w+/g, '').trim();
const out = new URLSearchParams(); const out = new URLSearchParams();
if (cleanedQuery) out.set('q', cleanedQuery); if (cleanedQuery) out.set('q', cleanedQuery);
tags.forEach(t => out.append('tags', t)); tags.forEach(t => out.append('tags', t));
document.querySelectorAll('input[name="price"]:checked') document.querySelectorAll('input[name="price"]:checked')
.forEach(cb => out.append('prices', cb.value)); .forEach(cb => out.append('prices', cb.value));
@@ -234,12 +232,17 @@
window.location.href = '/explore?' + out.toString(); window.location.href = '/explore?' + out.toString();
} }
})(); })();
// For cost display function renderCost(cost) {
document.querySelectorAll('.card-cost').forEach(el => { const num = parseInt(cost, 10);
const num = parseInt(el.textContent); if (!num || num <= 0) return '';
el.textContent = num === 0 ? '' : '$'.repeat(num); if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
}); });
</script> </script>
+34 -25
View File
@@ -2,7 +2,7 @@
<html lang="en"> <html lang="en">
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<title>Thyme Crunch Home</title> <title>Thyme Crunch Favorites</title>
<link rel="stylesheet" th:href="@{css/home.css}"> <link rel="stylesheet" th:href="@{css/home.css}">
<link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Delius+Swash+Caps&family=Mali:ital,wght@0,200;0,300;0,400;0,500;0,600;0,700;1,200;1,300;1,400;1,500;1,600;1,700" rel="stylesheet">
</head> </head>
@@ -15,29 +15,40 @@
</header> </header>
<div class="body"> <div class="body">
<!--Navigation Bar -->
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post"> <form th:action="@{/logout}" method="post">
<input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/> <input type="image" th:src="@{images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
</form> </form>
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol."> <a th:href="@{/create}" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a> </a>
</div> </div>
<!-- Main Content -->
<main class="main-content"> <main class="main-content">
<div class="recipe-card"> <div class="recipe-card">
<div th:if="${guest}" style="text-align:center; padding: 20px 0;">
<p style="margin-bottom:16px;">Log in to view and save your favorite recipes.</p>
<a th:href="@{/login}" style="display:inline-block; padding:10px 18px; background:#850000; color:white; text-decoration:none; border-radius:8px;">
Login
</a>
</div>
<div th:unless="${guest}">
<p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p> <p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p>
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}"> <div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
@@ -54,33 +65,31 @@
</div> </div>
</a> </a>
</div> </div>
</div>
</div>
</main> </main>
<!--New Bar -->
<div class="body-right"> <div class="body-right">
<div class="sidebar-right"> <div class="sidebar-right">
<h1> NEW </h1> <h1>FAVES</h1>
<div class="new-recipes"> <p style="text-align:center; padding:0 16px;">
<a th:each="recipe : ${newestRecipes}" Your saved recipes appear here.
th:href="@{/recipes/{id}(id=${recipe.id})}" </p>
class="new-recipe-item">
<p th:text="${recipe.title}">Title</p>
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
</div>
</a>
</div>
</div> </div>
</div> </div>
</div> </div>
<script> <script>
// For cost display function renderCost(cost) {
document.querySelectorAll('.card-cost').forEach(el => { const num = parseInt(cost, 10);
const num = parseInt(el.textContent); if (!num || num <= 0) return '';
el.textContent = num === 0 ? '' : '$'.repeat(num); if (num >= 4) return '$$$$';
}); return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
});
</script> </script>
</body> </body>
+12 -6
View File
@@ -22,8 +22,8 @@
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a href="/">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li> <li>
<form th:action="@{/logout}" method="post"> <form th:action="@{/logout}" method="post">
@@ -32,7 +32,7 @@
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon"> <a th:href="@{/create}" class="create_icon">
<img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)"> <img th:src="@{images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a> </a>
</div> </div>
@@ -92,10 +92,16 @@
</div> </div>
<script> <script>
// For cost display // For cost display <!-- Cost change -->
document.querySelectorAll('.card-cost').forEach(el => { function renderCost(cost) {
const num = parseInt(el.textContent); const num = parseInt(cost, 10);
el.textContent = num === 0 ? '' : '$'.repeat(num); if (!num || num <= 0) return '';
if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
}); });
</script> </script>
@@ -18,28 +18,31 @@
<div class="body"> <div class="body">
<!-- Left Navigation -->
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a th:href="${guest} ? @{/login} : @{/}">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li>
<li th:if="${guest}">
<a th:href="@{/login}" class="login-link">Login</a>
</li>
<li th:unless="${guest}">
<form th:action="@{/logout}" method="post"> <form th:action="@{/logout}" method="post">
<input type="image" th:src="@{/images/logout_icon.png}" alt="Logout button" class="nav_icon"/> <input type="image" th:src="@{/images/logout_icon.png}" alt="Logout button" class="nav_icon"/>
</form> </form>
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon">
<a th:href="@{/create}" class="create_icon">
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)"> <img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a> </a>
</div> </div>
<!-- Main Content — recipes -->
<main class="main-content"> <main class="main-content">
<h2 th:text="${profile.effectiveDisplayName} + '\'s Recipes'">User's Recipes</h2> <h2 th:text="${profile.effectiveDisplayName} + '\'s Recipes'">User's Recipes</h2>
<p th:if="${#lists.isEmpty(profile.recipes)}">This user has not created any recipes yet.</p> <p th:if="${#lists.isEmpty(profile.recipes)}">This user has not created any recipes yet.</p>
@@ -62,10 +65,8 @@
</div> </div>
</th:block> </th:block>
</div> </div>
</main> </main>
<!-- Right Sidebar — public profile info only -->
<div class="body-right"> <div class="body-right">
<div class="sidebar-right"> <div class="sidebar-right">
<p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p> <p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p>
@@ -79,10 +80,15 @@
</div> </div>
<script> <script>
// For cost display function renderCost(cost) {
document.querySelectorAll('.card-cost').forEach(el => { const num = parseInt(cost, 10);
const num = parseInt(el.textContent); if (!num || num <= 0) return '';
el.textContent = num === 0 ? '' : '$'.repeat(num); if (num >= 4) return '$$$$';
return '$'.repeat(num);
}
document.querySelectorAll('.card-cost').forEach(el => {
el.textContent = renderCost(el.textContent);
}); });
</script> </script>
+56 -9
View File
@@ -18,12 +18,11 @@
<div class="body"> <div class="body">
<!--Navigation Bar -->
<div class="body-left"> <div class="body-left">
<nav class="sidebar-left"> <nav class="sidebar-left">
<ul> <ul>
<li><a href="/">Home</a></li>
<li><a th:href="@{/explore}">Explore</a></li> <li><a th:href="@{/explore}">Explore</a></li>
<li><a href="/">Favorites</a></li>
<li><a th:href="@{/my-profile}">Profile</a></li> <li><a th:href="@{/my-profile}">Profile</a></li>
<li> <li>
<form th:action="@{/logout}" method="post"> <form th:action="@{/logout}" method="post">
@@ -32,12 +31,11 @@
</li> </li>
</ul> </ul>
</nav> </nav>
<a th:href="@{/create}" target="_blank" class="create_icon"> <a th:href="@{/create}" class="create_icon">
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol."> <img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
</a> </a>
</div> </div>
<!-- Main Content -->
<main class="main-content"> <main class="main-content">
<div th:if="${recipe != null}" class="recipe-container"> <div th:if="${recipe != null}" class="recipe-container">
<section class="recipe-section"> <section class="recipe-section">
@@ -93,10 +91,9 @@
<p><strong>Prep Time:</strong> <span th:text="${recipe.prepTimeMinutes}">0</span> minutes</p> <p><strong>Prep Time:</strong> <span th:text="${recipe.prepTimeMinutes}">0</span> minutes</p>
<p><strong>Cook Time:</strong> <span th:text="${recipe.cookTimeMinutes}">0</span> minutes</p> <p><strong>Cook Time:</strong> <span th:text="${recipe.cookTimeMinutes}">0</span> minutes</p>
<p><strong>Servings:</strong> <span th:text="${recipe.servings}">0</span></p> <p><strong>Servings:</strong> <span th:text="${recipe.servings}">0</span></p>
<p><strong>Cost:</strong> <span th:text="${#strings.repeat('$', recipe.cost)}">$</span></p> <p><strong>Cost:</strong> <span th:text="${recipe.cost >= 4 ? '$$$$' : #strings.repeat('$', recipe.cost)}">$</span></p>
</div> </div>
<div class="recipe-tags"> <div class="recipe-tags">
<h2>Tags: </h2> <h2>Tags: </h2>
<div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" class="tag-list"> <div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" class="tag-list">
@@ -111,7 +108,7 @@
</div> </div>
</section> </section>
<button class="save-btn" th:data-recipe-id="${recipe.id}">Save Recipe</button> <button type="button" class="save-btn" th:data-recipe-id="${recipe.id}">Save Recipe</button>
</div> </div>
<div th:unless="${recipe != null}" class="recipe-not-found"> <div th:unless="${recipe != null}" class="recipe-not-found">
@@ -120,8 +117,58 @@
</section> </section>
</div> </div>
</main> </main>
</div>
</div> <script>
async function getCurrentUser() {
const response = await fetch('/api/users/me', {
credentials: 'same-origin'
});
if (!response.ok) {
return null;
}
const user = await response.json();
return user || null;
}
async function saveRecipe(recipeId, button) {
const csrfHeader = document.querySelector('meta[name="_csrf_header"]')?.content;
const csrfToken = document.querySelector('meta[name="_csrf"]')?.content;
const user = await getCurrentUser();
if (!user || !user.id) {
window.location.href = '/login';
return;
}
const response = await fetch(`/api/users/${user.id}/favorites/${recipeId}`, {
method: 'POST',
credentials: 'same-origin',
headers: {
...(csrfHeader && csrfToken ? { [csrfHeader]: csrfToken } : {})
}
});
if (!response.ok) {
const text = await response.text();
alert(text || 'Could not save recipe.');
return;
}
button.textContent = 'Saved';
button.disabled = true;
}
document.querySelectorAll('.save-btn').forEach(button => {
button.addEventListener('click', async () => {
const recipeId = button.dataset.recipeId;
await saveRecipe(recipeId, button);
});
});
</script>
</body> </body>
</html> </html>