mirror of
https://gitlab.com/etc404/software-engineering-project.git
synced 2026-05-10 20:52:58 +00:00
Update 17 files
- /src/main/resources/application.properties - /src/main/resources/templates/view-recipe.html - /src/main/resources/templates/create-recipe.html - /src/main/resources/templates/home.html - /src/main/resources/templates/explore.html - /src/main/resources/templates/public-profile.html - /src/main/resources/templates/my-profile.html - /src/main/resources/templates/update-recipe.html - /src/main/resources/static/css/view-recipe.css - /src/main/java/com/example/demo/controller/SiteController.java - /src/main/java/com/example/demo/controller/RecipeUploadController.java - /src/main/java/com/example/demo/controller/RecipeUploadForm.java - /src/main/java/com/example/demo/config/WebConfig - /src/main/java/com/example/demo/config/SecurityConfig.java - /src/main/java/com/example/demo/config/WebConfig.java - /src/main/java/com/example/demo/service/Impl/RecipeServiceImpl.java - /src/main/java/com/example/demo/service/RecipeService.java
This commit is contained in:
@@ -19,15 +19,23 @@ public class SecurityConfig {
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/login", "/register", "/css/**", "/images/**").permitAll()
|
||||
// public pages and static files
|
||||
.requestMatchers("/", "/login", "/register", "/css/**", "/images/**").permitAll()
|
||||
.requestMatchers("/api/users").permitAll()
|
||||
.requestMatchers("/users/**").permitAll()
|
||||
.requestMatchers("/api/admin/**").hasRole("ADMIN")
|
||||
.anyRequest().authenticated()
|
||||
|
||||
// protected create recipe routes
|
||||
.requestMatchers("/create", "/api/recipes/upload").authenticated()
|
||||
|
||||
// protected my profile routes
|
||||
.requestMatchers("/my-profile", "/my-profile/update").authenticated()
|
||||
|
||||
// everything else public
|
||||
.anyRequest().permitAll()
|
||||
)
|
||||
.formLogin(form -> form
|
||||
.loginPage("/login")
|
||||
.defaultSuccessUrl("/", true)
|
||||
.defaultSuccessUrl("/")
|
||||
.permitAll()
|
||||
)
|
||||
.logout(logout -> logout.permitAll());
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.example.demo.config;
|
||||
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(ResourceHandlerRegistry registry) {
|
||||
Path uploadPath = Paths.get("uploads").toAbsolutePath().normalize();
|
||||
|
||||
registry.addResourceHandler("/uploads/**")
|
||||
.addResourceLocations("file:///" + uploadPath.toString().replace("\\", "/") + "/");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
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.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 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;
|
||||
|
||||
@RestController
|
||||
public class RecipeUploadController {
|
||||
|
||||
private final RecipeService recipeService;
|
||||
|
||||
public RecipeUploadController(RecipeService recipeService) {
|
||||
this.recipeService = recipeService;
|
||||
}
|
||||
|
||||
@PostMapping(value = "/api/recipes/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ResponseEntity<?> createRecipeWithUpload(@ModelAttribute RecipeUploadForm form, Principal principal) {
|
||||
try {
|
||||
System.out.println("UPLOAD ENDPOINT HIT");
|
||||
System.out.println("Title: " + form.getTitle());
|
||||
System.out.println("Image present: " + (form.getImage() != null && !form.getImage().isEmpty()));
|
||||
|
||||
RecipeDto dto = buildRecipeDto(form, true);
|
||||
|
||||
System.out.println("Image DTO count: " + (dto.getImages() == null ? 0 : dto.getImages().size()));
|
||||
|
||||
String currentUsername = principal.getName();
|
||||
RecipeDto saved = recipeService.saveRecipe(dto, currentUsername);
|
||||
|
||||
System.out.println("Saved recipe id: " + saved.getId());
|
||||
|
||||
return new ResponseEntity<>(saved, HttpStatus.CREATED);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body("Recipe creation failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping(value = "/api/recipes/{id}/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
|
||||
public ResponseEntity<?> updateRecipeWithUpload(
|
||||
@PathVariable Integer id,
|
||||
@ModelAttribute RecipeUploadForm form,
|
||||
Principal principal) {
|
||||
try {
|
||||
System.out.println("UPDATE UPLOAD ENDPOINT HIT");
|
||||
System.out.println("Recipe id: " + id);
|
||||
System.out.println("Title: " + form.getTitle());
|
||||
System.out.println("Image present: " + (form.getImage() != null && !form.getImage().isEmpty()));
|
||||
System.out.println("Remove image: " + form.getRemoveImage());
|
||||
|
||||
RecipeDto dto = buildRecipeDto(form, false);
|
||||
|
||||
String currentUsername = principal.getName();
|
||||
RecipeDto updated = recipeService.updateRecipe(dto, id, currentUsername);
|
||||
|
||||
System.out.println("Updated recipe id: " + updated.getId());
|
||||
|
||||
return new ResponseEntity<>(updated, HttpStatus.OK);
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body("Recipe update failed: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private RecipeDto buildRecipeDto(RecipeUploadForm form, boolean isCreate) throws IOException {
|
||||
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;
|
||||
}
|
||||
|
||||
String quantityString = getListValue(form.getIngredientQuantity(), i);
|
||||
BigDecimal quantity = null;
|
||||
if (quantityString != null && !quantityString.isBlank()) {
|
||||
quantity = new BigDecimal(quantityString.trim());
|
||||
}
|
||||
|
||||
String unit = getListValue(form.getIngredientUnit(), i);
|
||||
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);
|
||||
System.out.println("Saved file path: " + imageUrl);
|
||||
} else if (removeImage) {
|
||||
// Empty list means remove all images on update
|
||||
dto.setImages(new ArrayList<>());
|
||||
} else if (isCreate) {
|
||||
dto.setImages(new ArrayList<>());
|
||||
} else {
|
||||
// Null on update means keep the existing image as-is
|
||||
dto.setImages(null);
|
||||
}
|
||||
|
||||
return dto;
|
||||
}
|
||||
|
||||
private Integer parseInteger(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return Integer.valueOf(value.trim());
|
||||
}
|
||||
|
||||
private String getListValue(List<String> list, int index) {
|
||||
if (list == null || index >= list.size()) {
|
||||
return null;
|
||||
}
|
||||
return list.get(index);
|
||||
}
|
||||
|
||||
private String safeTrim(String value) {
|
||||
return value == null ? null : value.trim();
|
||||
}
|
||||
|
||||
private String saveUploadedFile(MultipartFile file) throws IOException {
|
||||
String originalFilename = StringUtils.cleanPath(file.getOriginalFilename());
|
||||
String extension = "";
|
||||
|
||||
int dotIndex = originalFilename.lastIndexOf('.');
|
||||
if (dotIndex >= 0) {
|
||||
extension = originalFilename.substring(dotIndex);
|
||||
}
|
||||
|
||||
String storedFilename = UUID.randomUUID() + extension;
|
||||
|
||||
Path uploadDir = Paths.get("uploads");
|
||||
if (!Files.exists(uploadDir)) {
|
||||
Files.createDirectories(uploadDir);
|
||||
}
|
||||
|
||||
Path destination = uploadDir.resolve(storedFilename);
|
||||
Files.copy(file.getInputStream(), destination, StandardCopyOption.REPLACE_EXISTING);
|
||||
|
||||
return "/uploads/" + storedFilename;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
package com.example.demo.controller;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
public class RecipeUploadForm {
|
||||
|
||||
private String title;
|
||||
private String description;
|
||||
private String prepTimeMinutes;
|
||||
private String cookTimeMinutes;
|
||||
private String servings;
|
||||
private String cost;
|
||||
|
||||
private List<String> ingredientName;
|
||||
private List<String> ingredientQuantity;
|
||||
private List<String> ingredientUnit;
|
||||
private List<String> ingredientNotes;
|
||||
|
||||
private List<String> stepInstruction;
|
||||
private List<String> tags;
|
||||
|
||||
private MultipartFile image;
|
||||
private Boolean removeImage;
|
||||
|
||||
public RecipeUploadForm() {
|
||||
}
|
||||
|
||||
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 String getPrepTimeMinutes() {
|
||||
return prepTimeMinutes;
|
||||
}
|
||||
|
||||
public void setPrepTimeMinutes(String prepTimeMinutes) {
|
||||
this.prepTimeMinutes = prepTimeMinutes;
|
||||
}
|
||||
|
||||
public String getCookTimeMinutes() {
|
||||
return cookTimeMinutes;
|
||||
}
|
||||
|
||||
public void setCookTimeMinutes(String cookTimeMinutes) {
|
||||
this.cookTimeMinutes = cookTimeMinutes;
|
||||
}
|
||||
|
||||
public String getServings() {
|
||||
return servings;
|
||||
}
|
||||
|
||||
public void setServings(String servings) {
|
||||
this.servings = servings;
|
||||
}
|
||||
|
||||
public String getCost() {
|
||||
return cost;
|
||||
}
|
||||
|
||||
public void setCost(String cost) {
|
||||
this.cost = cost;
|
||||
}
|
||||
|
||||
public List<String> getIngredientName() {
|
||||
return ingredientName;
|
||||
}
|
||||
|
||||
public void setIngredientName(List<String> ingredientName) {
|
||||
this.ingredientName = ingredientName;
|
||||
}
|
||||
|
||||
public List<String> getIngredientQuantity() {
|
||||
return ingredientQuantity;
|
||||
}
|
||||
|
||||
public void setIngredientQuantity(List<String> ingredientQuantity) {
|
||||
this.ingredientQuantity = ingredientQuantity;
|
||||
}
|
||||
|
||||
public List<String> getIngredientUnit() {
|
||||
return ingredientUnit;
|
||||
}
|
||||
|
||||
public void setIngredientUnit(List<String> ingredientUnit) {
|
||||
this.ingredientUnit = ingredientUnit;
|
||||
}
|
||||
|
||||
public List<String> getIngredientNotes() {
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,16 @@ import java.util.List;
|
||||
|
||||
import com.example.demo.service.RecipeService;
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.ui.Model;
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseBody;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
@Controller
|
||||
public class SiteController {
|
||||
@@ -55,6 +60,13 @@ public class SiteController {
|
||||
return "update-recipe";
|
||||
}
|
||||
|
||||
@GetMapping("/update-recipe/{id}")
|
||||
public String showUpdateRecipePage(@PathVariable Integer id, Model model) {
|
||||
RecipeDto recipe = recipeService.getRecipeById(id);
|
||||
model.addAttribute("recipe", recipe);
|
||||
return "update-recipe";
|
||||
}
|
||||
|
||||
@GetMapping("/explore")
|
||||
public String explore(
|
||||
@RequestParam(required = false) String q,
|
||||
@@ -70,4 +82,11 @@ public class SiteController {
|
||||
model.addAttribute("tags", tags);
|
||||
return "explore";
|
||||
}
|
||||
}
|
||||
|
||||
@PostMapping("/api/recipes/{id}/image")
|
||||
@ResponseBody
|
||||
public ResponseEntity<?> updateRecipeImage(@PathVariable Integer id,
|
||||
@RequestParam("image") MultipartFile image) {
|
||||
recipeService.updateRecipeImage(id, image);
|
||||
return ResponseEntity.ok().build();
|
||||
}}
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.dto.UserDto;
|
||||
@@ -57,6 +58,13 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
this.tagRepository = tagRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateRecipeImage(Integer id, MultipartFile image) {
|
||||
if (image == null || image.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public RecipeDto convertToDto(Recipe recipe) {
|
||||
List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
|
||||
@@ -236,6 +244,7 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
List<TagDto> updatedTags = recipeDto.getTags();
|
||||
List<Tag> tagsToRemove = new ArrayList<>();
|
||||
|
||||
if (updatedIngredients != null) {
|
||||
for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) {
|
||||
|
||||
boolean existsInUpdatedList = false;
|
||||
@@ -243,7 +252,7 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
String updatedName = dto.getIngredientName();
|
||||
String existingName = ri.getIngredient().getName();
|
||||
|
||||
if (updatedName.equals(existingName)) {
|
||||
if (java.util.Objects.equals(updatedName, existingName)) {
|
||||
existsInUpdatedList = true;
|
||||
break;
|
||||
}
|
||||
@@ -259,7 +268,8 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
for (RecipeIngredientDto riDto : updatedIngredients) {
|
||||
|
||||
RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
|
||||
.filter(ri -> ri.getIngredient().getName().equals(riDto.getIngredientName())).findFirst()
|
||||
.filter(ri -> java.util.Objects.equals(ri.getIngredient().getName(), riDto.getIngredientName()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (existingRI != null) {
|
||||
@@ -284,6 +294,7 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
existingRecipe.getRecipeIngredients().add(newRI);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (updatedSteps != null) {
|
||||
for (Step step : existingRecipe.getSteps()) {
|
||||
@@ -314,7 +325,7 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
if (updatedImages != null) {
|
||||
for (Image image : existingRecipe.getImages()) {
|
||||
boolean existsInUpdatedList = updatedImages.stream()
|
||||
.anyMatch(dto -> dto.getImageUrl().equals(image.getImageUrl()));
|
||||
.anyMatch(dto -> java.util.Objects.equals(dto.getImageUrl(), image.getImageUrl()));
|
||||
if (!existsInUpdatedList)
|
||||
imagesToRemove.add(image);
|
||||
}
|
||||
@@ -323,7 +334,9 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
|
||||
for (ImageDto imageDto : updatedImages) {
|
||||
Image existingImage = existingRecipe.getImages().stream()
|
||||
.filter(img -> img.getImageUrl().equals(imageDto.getImageUrl())).findFirst().orElse(null);
|
||||
.filter(img -> java.util.Objects.equals(img.getImageUrl(), imageDto.getImageUrl()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (existingImage != null) {
|
||||
existingImage.setImageUrl(imageDto.getImageUrl());
|
||||
@@ -336,7 +349,8 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
|
||||
if (updatedTags != null) {
|
||||
for (Tag tag : existingRecipe.getTags()) {
|
||||
boolean existsInUpdatedList = updatedTags.stream().anyMatch(dto -> dto.getName().equals(tag.getName()));
|
||||
boolean existsInUpdatedList = updatedTags.stream()
|
||||
.anyMatch(dto -> java.util.Objects.equals(dto.getName(), tag.getName()));
|
||||
if (!existsInUpdatedList)
|
||||
tagsToRemove.add(tag);
|
||||
}
|
||||
@@ -345,7 +359,9 @@ public class RecipeServiceImpl implements RecipeService {
|
||||
|
||||
for (TagDto tagDto : updatedTags) {
|
||||
Tag existingTag = existingRecipe.getTags().stream()
|
||||
.filter(tag -> tag.getName().equals(tagDto.getName())).findFirst().orElse(null);
|
||||
.filter(tag -> java.util.Objects.equals(tag.getName(), tagDto.getName()))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (existingTag != null) {
|
||||
existingTag.setName(tagDto.getName());
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.example.demo.service;
|
||||
import java.util.List;
|
||||
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.example.demo.dto.RecipeDto;
|
||||
import com.example.demo.entity.Recipe;
|
||||
@@ -23,5 +24,6 @@ public interface RecipeService {
|
||||
|
||||
void deleteRecipe(Integer Id, String currentUsername);
|
||||
|
||||
}
|
||||
void updateRecipeImage(Integer id, MultipartFile image);
|
||||
|
||||
}
|
||||
@@ -18,3 +18,8 @@ spring.jpa.open-in-view=false
|
||||
#spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
|
||||
|
||||
server.port=8080
|
||||
|
||||
spring.servlet.multipart.max-file-size=20MB
|
||||
spring.servlet.multipart.max-request-size=20MB
|
||||
server.tomcat.max-swallow-size=-1
|
||||
server.tomcat.max-part-count=100
|
||||
@@ -30,7 +30,8 @@ body, html {
|
||||
margin: 0;
|
||||
font-family: 'Mali', cursive;
|
||||
background-color: var(--pale-yellow);
|
||||
overflow: clip;
|
||||
overflow-x: hidden;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
/* =========================
|
||||
|
||||
@@ -73,9 +73,12 @@
|
||||
<div class="field">
|
||||
<label for="servings">Servings: <span class="required">*</span></label>
|
||||
<input type="text" id="servings" placeholder="0">
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="cost">Estimated Cost: <span class="required">*</span></label>
|
||||
<input type="text" id="cost" placeholder="0">
|
||||
<label>Estimated Cost: <span class="required">*</span></label>
|
||||
<div class="cost-selector" id="cost-selector">
|
||||
<span class="dollar" data-value="1">$</span>
|
||||
@@ -153,6 +156,7 @@ function addStep() {
|
||||
function renumberSteps() {
|
||||
stepsContainer.querySelectorAll('.step-bubble').forEach((bubble, i) => {
|
||||
bubble.textContent = i + 1;
|
||||
bubble.textContent = i + 1;
|
||||
});
|
||||
}
|
||||
// Cost display
|
||||
@@ -184,6 +188,7 @@ dollars.forEach(dollar => {
|
||||
|
||||
|
||||
// ---- Collecting on submit ----
|
||||
// Call this wherever you build your POST payload:
|
||||
function getIngredients() {
|
||||
return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => {
|
||||
qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
|
||||
<meta name="_csrf" th:content="${_csrf.token}"/>
|
||||
<title>Explore - Thyme Crunch</title>
|
||||
<title>Thyme Crunch Home</title>
|
||||
<link rel="stylesheet" th:href="@{css/explore.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 rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
|
||||
@@ -65,10 +65,11 @@
|
||||
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
|
||||
</div>
|
||||
<p class="card-cost" th:text="${recipe.cost}">Cost</p>
|
||||
<p th:text="${recipe.cost}">Cost</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
</main>
|
||||
|
||||
<!--Filter -->
|
||||
@@ -234,12 +235,6 @@
|
||||
window.location.href = '/explore?' + out.toString();
|
||||
}
|
||||
})();
|
||||
|
||||
// For cost display
|
||||
document.querySelectorAll('.card-cost').forEach(el => {
|
||||
const num = parseInt(el.textContent);
|
||||
el.textContent = num === 0 ? '' : '$'.repeat(num);
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Home - Thyme Crunch</title>
|
||||
<title>Thyme Crunch Home</title>
|
||||
<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">
|
||||
</head>
|
||||
@@ -38,7 +38,6 @@
|
||||
<!-- Main Content -->
|
||||
<main class="main-content">
|
||||
<div class="recipe-card">
|
||||
|
||||
<p th:if="${#lists.isEmpty(recipes)}">You have not saved any recipes.</p>
|
||||
|
||||
<div class="recipe-card" th:unless="${#lists.isEmpty(recipes)}">
|
||||
@@ -51,7 +50,7 @@
|
||||
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
|
||||
</div>
|
||||
<p class="card-cost" th:text="${recipe.cost}">Cost</p>
|
||||
<p th:text="${recipe.cost}">Cost</p>
|
||||
</div>
|
||||
</a>
|
||||
</div>
|
||||
@@ -64,13 +63,5 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.querySelectorAll('.card-cost').forEach(el => {
|
||||
const num = parseInt(el.textContent);
|
||||
el.textContent = num === 0 ? '' : '$'.repeat(num);
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -54,9 +54,9 @@
|
||||
</div>
|
||||
<div class="card-right">
|
||||
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
|
||||
</div>
|
||||
<p class="card-cost" th:text="${recipe.cost}"><b>Cost</b></p>
|
||||
<p th:text="${recipe.cost}">Cost</p>
|
||||
</div>
|
||||
</a>
|
||||
<a th:href="@{/recipes/{id}/edit(id=${recipe.id})}" class="edit-link">Edit</a>
|
||||
@@ -91,12 +91,5 @@
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
document.querySelectorAll('.card-cost').forEach(el => {
|
||||
const num = parseInt(el.textContent);
|
||||
el.textContent = num === 0 ? '' : '$'.repeat(num);
|
||||
});
|
||||
</script>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -4,16 +4,16 @@
|
||||
<meta charset="UTF-8">
|
||||
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
|
||||
<meta name="_csrf" th:content="${_csrf.token}"/>
|
||||
<title>My Profile - Thyme Crunch</title>
|
||||
<link rel="stylesheet" th:href="@{css/my-profile.css}">
|
||||
<title>Profile - Thyme Crunch</title>
|
||||
<link rel="stylesheet" th:href="@{/css/my-profile.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">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="top-header">
|
||||
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
|
||||
<img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
|
||||
<h1 class="site-name">Thyme Crunch</h1>
|
||||
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
|
||||
<img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
@@ -27,22 +27,22 @@
|
||||
<li><a th:href="@{/my-profile}">Profile</a></li>
|
||||
<li>
|
||||
<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>
|
||||
</li>
|
||||
</ul>
|
||||
</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.)">
|
||||
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.)">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Main Content — recipes -->
|
||||
<main class="main-content">
|
||||
|
||||
<h2>My Recipes</h2>
|
||||
<h2 th:text="${profile.effectiveDisplayName} + '\'s Recipes'">User's Recipes</h2>
|
||||
|
||||
<p th:if="${#lists.isEmpty(profile.recipes)}">You have not created any recipes yet.</p>
|
||||
<p th:if="${#lists.isEmpty(profile.recipes)}">This user has not created any recipes yet.</p>
|
||||
|
||||
<div class="recipe-card" th:unless="${#lists.isEmpty(profile.recipes)}">
|
||||
<th:block th:each="recipe : ${profile.recipes}">
|
||||
@@ -54,7 +54,7 @@
|
||||
</div>
|
||||
<div class="card-right">
|
||||
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image">
|
||||
<img th:src="${recipe.images[0].imageUrl}" alt="Recipe Image" style="max-width: 200px;">
|
||||
</div>
|
||||
<p th:text="${recipe.cost}">Cost</p>
|
||||
</div>
|
||||
@@ -65,27 +65,12 @@
|
||||
|
||||
</main>
|
||||
|
||||
<!-- Right Sidebar — profile info & edit -->
|
||||
<!-- Right Sidebar — public profile info only -->
|
||||
<div class="body-right">
|
||||
<div class="sidebar-right">
|
||||
|
||||
<p><strong th:text="${profile.effectiveDisplayName}">Display Name</strong></p>
|
||||
<p th:text="'@' + ${profile.username}">@username</p>
|
||||
<p th:if="${profile.bio != null}" th:text="${profile.bio}">Bio goes here.</p>
|
||||
<a th:href="@{/users/{id}(id=${profile.id})}" class="view-profile-btn">View public profile</a>
|
||||
|
||||
<form th:action="@{/my-profile/update}" method="post" th:object="${updateProfileDto}" class="profile-form">
|
||||
<div class="rows">
|
||||
<label for="displayName">Display Name</label>
|
||||
<input type="text" id="displayName" th:field="*{displayName}" maxlength="100">
|
||||
</div>
|
||||
<div class="rows">
|
||||
<label for="bio">Bio</label>
|
||||
<textarea id="bio" th:field="*{bio}" rows="6" maxlength="1000"></textarea>
|
||||
</div>
|
||||
<button type="submit">Save</button>
|
||||
</form>
|
||||
|
||||
<p th:if="${profile.bio != null and !#strings.isEmpty(profile.bio)}" th:text="${profile.bio}">Bio goes here.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,19 +1,19 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<<!DOCTYPE html>
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
|
||||
<meta name="_csrf" th:content="${_csrf.token}"/>
|
||||
<title>Create Thyme Crunch Recipe</title>
|
||||
<link rel="stylesheet" th:href="@{css/create-recipe.css}">
|
||||
<title>Update Thyme Crunch Recipe</title>
|
||||
<link rel="stylesheet" th:href="@{/css/create-recipe.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">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="top-header">
|
||||
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
|
||||
<img th:src="@{/images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
|
||||
<h1 class="site-name">Thyme Crunch</h1>
|
||||
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
|
||||
<img th:src="@{/images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
|
||||
</header>
|
||||
|
||||
<div class="form-wrap">
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
<!-- Main Content -->
|
||||
<div class="form-section">
|
||||
<div class="section-title">New Recipe</div>
|
||||
<div class="section-title">Update Recipe</div>
|
||||
|
||||
<div class="field">
|
||||
<label for="title">Title <span class="required">*</span></label>
|
||||
@@ -36,15 +36,14 @@
|
||||
<div class="field">
|
||||
<label>Ingredients <span class="required">*</span></label>
|
||||
<div id="ingredients-container"></div>
|
||||
<button class="btn-add" id="add-ingredient-btn">+ Add ingredient</button>
|
||||
<button class="btn-add" id="add-ingredient-btn" type="button">+ Add ingredient</button>
|
||||
</div>
|
||||
|
||||
<div class="field">
|
||||
<label>Instructions <span class="required">*</span></label>
|
||||
<div id="steps-container"></div>
|
||||
<button class="btn-add" id="add-step-btn">+ Add step</button>
|
||||
<button class="btn-add" id="add-step-btn" type="button">+ Add step</button>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
<!-- Cover image / Right -->
|
||||
@@ -53,9 +52,9 @@
|
||||
<div class="image-drop" id="drop-zone">
|
||||
<p class="upload-title">Click to upload or drag and drop an image.</p>
|
||||
</div>
|
||||
<div class="image-preview" id="preview">
|
||||
<div class="image-preview" id="preview" style="display: none;">
|
||||
<img id="preview-img" src="" alt="Cover preview">
|
||||
<button class="remove-img" id="remove-img-btn">Remove</button>
|
||||
<button class="remove-img" id="remove-img-btn" type="button">Remove</button>
|
||||
</div>
|
||||
<input type="file" id="img-input" accept="image/*" style="display: none;">
|
||||
</div>
|
||||
@@ -84,59 +83,76 @@
|
||||
|
||||
<!-- Tags -->
|
||||
<div class="form-section">
|
||||
|
||||
<div class="field">
|
||||
<label>Tags</label>
|
||||
<div class="tag-input-row">
|
||||
<input type="text" id="tag-input" placeholder="Type in a tag and click Add">
|
||||
<button class="btn" id="add-tag-btn">Add</button>
|
||||
<button class="btn" id="add-tag-btn" type="button">Add</button>
|
||||
</div>
|
||||
<div class="tag-wrap" id="tag-wrap"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="form-message" class="form-message" style="display:none;"></div>
|
||||
|
||||
<div class="actions">
|
||||
<button class="btn-create" id="publish-btn">CREATE</button>
|
||||
<button class="btn-create" id="publish-btn" type="button">UPDATE</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
<script th:inline="javascript">
|
||||
const existingRecipe = /*[[${recipe}]]*/ null;
|
||||
</script>
|
||||
|
||||
<script>
|
||||
// ---- DOM refs ----
|
||||
const ingredientContainer = document.getElementById('ingredients-container');
|
||||
const stepsContainer = document.getElementById('steps-container');
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const imgInput = document.getElementById('img-input');
|
||||
const previewImg = document.getElementById('preview-img');
|
||||
const previewBox = document.getElementById('preview');
|
||||
const tags = [];
|
||||
let imageRemoved = false;
|
||||
|
||||
// ---- Ingredients ----
|
||||
const ingredientContainer = document.getElementById('ingredients-container');
|
||||
document.getElementById('add-ingredient-btn').addEventListener('click', addIngredient);
|
||||
addIngredient(); // start with one
|
||||
document.getElementById('add-ingredient-btn').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
addIngredient();
|
||||
});
|
||||
|
||||
function addIngredient() {
|
||||
function addIngredient(data = {}) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'dynamic-row';
|
||||
row.innerHTML = `
|
||||
<input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)">
|
||||
<input type="text" class="ing-qty" placeholder="Qty (e.g. 3)">
|
||||
<input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)">
|
||||
<input type="text" class="ing-notes" placeholder="Notes (optional)">
|
||||
<button class="btn-remove" title="Remove">✕</button>`;
|
||||
row.querySelector('.btn-remove').addEventListener('click', () => {
|
||||
<input type="text" class="ing-name" placeholder="Ingredient (e.g. Sugar)" value="${escapeHtml(data.ingredientName || '')}">
|
||||
<input type="text" class="ing-qty" placeholder="Qty (e.g. 3)" value="${data.quantity ?? ''}">
|
||||
<input type="text" class="ing-unit" placeholder="Unit (e.g. tbsp)" value="${escapeHtml(data.unit || '')}">
|
||||
<input type="text" class="ing-notes" placeholder="Notes (optional)" value="${escapeHtml(data.notes || '')}">
|
||||
<button class="btn-remove" title="Remove" type="button">✕</button>`;
|
||||
row.querySelector('.btn-remove').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
row.remove();
|
||||
});
|
||||
ingredientContainer.appendChild(row);
|
||||
}
|
||||
|
||||
// ---- Steps ----
|
||||
const stepsContainer = document.getElementById('steps-container');
|
||||
document.getElementById('add-step-btn').addEventListener('click', addStep);
|
||||
addStep(); // start with one
|
||||
document.getElementById('add-step-btn').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
addStep();
|
||||
});
|
||||
|
||||
function addStep() {
|
||||
function addStep(data = {}) {
|
||||
const row = document.createElement('div');
|
||||
row.className = 'dynamic-row';
|
||||
row.innerHTML = `
|
||||
<div class="step-bubble">?</div>
|
||||
<textarea placeholder="Describe this step..."></textarea>
|
||||
<button class="btn-remove" title="Remove">✕</button>
|
||||
<textarea placeholder="Describe this step...">${escapeHtml(data.instruction || '')}</textarea>
|
||||
<button class="btn-remove" title="Remove" type="button">✕</button>
|
||||
`;
|
||||
row.querySelector('.btn-remove').addEventListener('click', () => {
|
||||
row.querySelector('.btn-remove').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
row.remove();
|
||||
renumberSteps();
|
||||
});
|
||||
@@ -150,52 +166,30 @@ function renumberSteps() {
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Collecting on submit ----
|
||||
// Call this wherever you build your POST payload:
|
||||
function getIngredients() {
|
||||
return [...ingredientContainer.querySelectorAll('.dynamic-row')].map(row => {
|
||||
qtyValue = row.querySelector('.ing-qty').value.trim(); // quantity should be a number NOT A STRING
|
||||
return {
|
||||
ingredient: {
|
||||
name: row.querySelector('.ing-name').value.trim()
|
||||
},
|
||||
quantity: Number(qtyValue),
|
||||
unit: row.querySelector('.ing-unit').value.trim(),
|
||||
notes: row.querySelector('.ing-notes').value.trim()
|
||||
};
|
||||
}).filter(item => item.ingredient.name);
|
||||
}
|
||||
|
||||
|
||||
function getSteps() {
|
||||
return [...stepsContainer.querySelectorAll('textarea')]
|
||||
.map((el, i) => ({ step_number: i + 1, instruction: el.value.trim() }))
|
||||
.filter(item => item.instruction);
|
||||
}
|
||||
|
||||
// --- Image upload ---
|
||||
const dropZone = document.getElementById('drop-zone');
|
||||
const imgInput = document.getElementById('img-input');
|
||||
|
||||
// ---- Image upload preview ----
|
||||
dropZone.addEventListener('click', () => imgInput.click());
|
||||
|
||||
imgInput.addEventListener('change', function () {
|
||||
if (!this.files || !this.files[0]) return;
|
||||
|
||||
imageRemoved = false;
|
||||
|
||||
const url = URL.createObjectURL(this.files[0]);
|
||||
document.getElementById('preview-img').src = url;
|
||||
previewImg.src = url;
|
||||
dropZone.style.display = 'none';
|
||||
document.getElementById('preview').style.display = 'block';
|
||||
previewBox.style.display = 'block';
|
||||
});
|
||||
|
||||
document.getElementById('remove-img-btn').addEventListener('click', function () {
|
||||
document.getElementById('remove-img-btn').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
imgInput.value = '';
|
||||
document.getElementById('preview').style.display = 'none';
|
||||
previewImg.src = '';
|
||||
previewBox.style.display = 'none';
|
||||
dropZone.style.display = 'block';
|
||||
imageRemoved = true;
|
||||
});
|
||||
|
||||
// --- Tags ---
|
||||
const tags = [];
|
||||
|
||||
// ---- Tags ----
|
||||
document.getElementById('tag-input').addEventListener('keydown', function (e) {
|
||||
if (e.key === 'Enter') {
|
||||
e.preventDefault();
|
||||
@@ -203,12 +197,18 @@ document.getElementById('tag-input').addEventListener('keydown', function (e) {
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById('add-tag-btn').addEventListener('click', addTag);
|
||||
document.getElementById('add-tag-btn').addEventListener('click', function (e) {
|
||||
e.preventDefault();
|
||||
addTag();
|
||||
});
|
||||
|
||||
function addTag() {
|
||||
const input = document.getElementById('tag-input');
|
||||
const val = input.value.trim().toLowerCase().replace(/\s+/g, '-');
|
||||
if (!val || tags.includes(val)) { input.value = ''; return; }
|
||||
if (!val || tags.includes(val)) {
|
||||
input.value = '';
|
||||
return;
|
||||
}
|
||||
tags.push(val);
|
||||
input.value = '';
|
||||
renderTags();
|
||||
@@ -221,7 +221,7 @@ function removeTag(t) {
|
||||
|
||||
function renderTags() {
|
||||
document.getElementById('tag-wrap').innerHTML = tags
|
||||
.map(t => `<div class="tag">${t} <span class="remove-tag" data-tag="${t}">✕</span></div>`)
|
||||
.map(t => `<div class="tag">${escapeHtml(t)} <span class="remove-tag" data-tag="${escapeHtml(t)}">✕</span></div>`)
|
||||
.join('');
|
||||
|
||||
document.querySelectorAll('.remove-tag').forEach(btn => {
|
||||
@@ -229,118 +229,248 @@ function renderTags() {
|
||||
});
|
||||
}
|
||||
|
||||
async function getLoggedInUser() {
|
||||
try {
|
||||
const res = await fetch('http://localhost:8080/api/users/me', {
|
||||
credentials: 'include'
|
||||
// ---- Helpers ----
|
||||
function escapeHtml(str) {
|
||||
return String(str ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"')
|
||||
.replace(/'/g, ''');
|
||||
}
|
||||
|
||||
function showMessage(message, isError = false) {
|
||||
const box = document.getElementById('form-message');
|
||||
box.textContent = message;
|
||||
box.style.display = 'block';
|
||||
box.style.backgroundColor = isError ? '#ffd7d7' : '#dff5dd';
|
||||
box.style.color = isError ? '#7a0000' : '#1f5c2c';
|
||||
box.style.border = isError ? '1px solid #d88' : '1px solid #8bc48b';
|
||||
box.style.padding = '12px';
|
||||
box.style.marginTop = '20px';
|
||||
box.style.borderRadius = '8px';
|
||||
}
|
||||
|
||||
function showSuccessAndRedirect(message) {
|
||||
showMessage(message, false);
|
||||
setTimeout(() => {
|
||||
window.location.href = '/explore';
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
function fillRecipeForm(recipe) {
|
||||
if (!recipe) return;
|
||||
|
||||
document.getElementById('title').value = recipe.title || '';
|
||||
document.getElementById('desc').value = recipe.description || '';
|
||||
document.getElementById('prep').value = recipe.prepTimeMinutes ?? '';
|
||||
document.getElementById('cooking').value = recipe.cookTimeMinutes ?? '';
|
||||
document.getElementById('servings').value = recipe.servings ?? '';
|
||||
document.getElementById('cost').value = recipe.cost ?? '';
|
||||
|
||||
ingredientContainer.innerHTML = '';
|
||||
if (recipe.ingredients && recipe.ingredients.length > 0) {
|
||||
recipe.ingredients.forEach(item => addIngredient(item));
|
||||
} else {
|
||||
addIngredient();
|
||||
}
|
||||
|
||||
stepsContainer.innerHTML = '';
|
||||
if (recipe.steps && recipe.steps.length > 0) {
|
||||
recipe.steps.forEach(step => addStep(step));
|
||||
} else {
|
||||
addStep();
|
||||
}
|
||||
|
||||
if (recipe.tags && recipe.tags.length > 0) {
|
||||
recipe.tags.forEach(tag => {
|
||||
if (tag.name && !tags.includes(tag.name.toLowerCase())) {
|
||||
tags.push(tag.name.toLowerCase());
|
||||
}
|
||||
});
|
||||
if (!res.ok) throw new Error('Failed to get logged-in user');
|
||||
return await res.json();
|
||||
} catch (err) {
|
||||
console.error('Error fetching user:', err);
|
||||
return null;
|
||||
renderTags();
|
||||
}
|
||||
|
||||
imageRemoved = false;
|
||||
|
||||
if (recipe.images && recipe.images.length > 0 && recipe.images[0].imageUrl) {
|
||||
previewImg.src = recipe.images[0].imageUrl;
|
||||
dropZone.style.display = 'none';
|
||||
previewBox.style.display = 'block';
|
||||
} else {
|
||||
previewImg.src = '';
|
||||
previewBox.style.display = 'none';
|
||||
dropZone.style.display = 'block';
|
||||
}
|
||||
}
|
||||
|
||||
function buildRecipeJSON(user) {
|
||||
const title = document.getElementById('title').value.trim();
|
||||
const description = document.getElementById('desc').value.trim();
|
||||
const prepTimeMinutes = Number(document.getElementById('prep').value);
|
||||
const cookTimeMinutes = Number(document.getElementById('cooking').value);
|
||||
const servings = Number(document.getElementById('servings').value);
|
||||
const status = "DRAFT";
|
||||
const cost = Number(document.getElementById('cost').value);
|
||||
// ---- Inline validation ----
|
||||
function showError(input, message) {
|
||||
input.classList.add('invalid');
|
||||
|
||||
// Ingredients
|
||||
const recipeIngredients = [...document.querySelectorAll('#ingredients-container .dynamic-row')]
|
||||
.map(row => {
|
||||
const qtyValue = Number(row.querySelector('.ing-qty').value.trim());
|
||||
return {
|
||||
ingredient: { name: row.querySelector('.ing-name').value.trim() },
|
||||
quantity: qtyValue,
|
||||
unit: row.querySelector('.ing-unit').value.trim(),
|
||||
notes: row.querySelector('.ing-notes').value.trim()
|
||||
};
|
||||
})
|
||||
.filter(item => item.ingredient.name);
|
||||
|
||||
// Steps
|
||||
const steps = [...document.querySelectorAll('#steps-container textarea')]
|
||||
.map((el, i) => ({ stepNumber: i + 1, instruction: el.value.trim() }))
|
||||
.filter(item => item.instruction);
|
||||
|
||||
// Images
|
||||
|
||||
|
||||
// Tags
|
||||
const tagsInput = tags;
|
||||
const tagsArray = tagsInput.map(t => ({ name: t }));
|
||||
|
||||
return {
|
||||
title,
|
||||
description,
|
||||
prepTimeMinutes,
|
||||
cookTimeMinutes,
|
||||
servings,
|
||||
status,
|
||||
cost,
|
||||
user,
|
||||
recipeIngredients,
|
||||
steps,
|
||||
//images,
|
||||
tags: tagsArray
|
||||
};
|
||||
let error = input.parentElement.querySelector('.error-message');
|
||||
if (!error) {
|
||||
error = document.createElement('p');
|
||||
error.className = 'error-message';
|
||||
error.style.color = 'red';
|
||||
error.style.fontSize = '0.9em';
|
||||
error.style.marginTop = '6px';
|
||||
input.parentElement.appendChild(error);
|
||||
}
|
||||
|
||||
error.textContent = message;
|
||||
}
|
||||
|
||||
function clearError(input) {
|
||||
input.classList.remove('invalid');
|
||||
const error = input.parentElement.querySelector('.error-message');
|
||||
if (error) error.remove();
|
||||
}
|
||||
|
||||
function validateForm() {
|
||||
let valid = true;
|
||||
|
||||
const title = document.getElementById('title');
|
||||
const desc = document.getElementById('desc');
|
||||
const prep = document.getElementById('prep');
|
||||
const cooking = document.getElementById('cooking');
|
||||
const servings = document.getElementById('servings');
|
||||
const cost = document.getElementById('cost');
|
||||
|
||||
[title, desc, prep, cooking, servings, cost].forEach(clearError);
|
||||
|
||||
if (!title.value.trim()) {
|
||||
showError(title, 'Title is required');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!desc.value.trim()) {
|
||||
showError(desc, 'Description is required');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!prep.value.trim() || isNaN(Number(prep.value)) || Number(prep.value) <= 0) {
|
||||
showError(prep, 'Enter a valid prep time');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!cooking.value.trim() || isNaN(Number(cooking.value)) || Number(cooking.value) <= 0) {
|
||||
showError(cooking, 'Enter a valid cook time');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!servings.value.trim() || isNaN(Number(servings.value)) || Number(servings.value) <= 0) {
|
||||
showError(servings, 'Enter valid servings');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!cost.value.trim() || isNaN(Number(cost.value)) || Number(cost.value) <= 0) {
|
||||
showError(cost, 'Enter a valid cost');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
const ingredientRows = [...document.querySelectorAll('#ingredients-container .dynamic-row')];
|
||||
const hasIngredient = ingredientRows.some(row => row.querySelector('.ing-name').value.trim() !== '');
|
||||
if (!hasIngredient && ingredientRows.length > 0) {
|
||||
showError(ingredientRows[0].querySelector('.ing-name'), 'Add at least one ingredient');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
const stepAreas = [...document.querySelectorAll('#steps-container textarea')];
|
||||
const hasStep = stepAreas.some(textarea => textarea.value.trim() !== '');
|
||||
if (!hasStep && stepAreas.length > 0) {
|
||||
showError(stepAreas[0], 'Add at least one instruction step');
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (!valid) {
|
||||
document.querySelector('.invalid')?.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'center'
|
||||
});
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
// ---- Initial fill ----
|
||||
fillRecipeForm(existingRecipe);
|
||||
|
||||
// ---- Update recipe with multipart upload ----
|
||||
document.getElementById('publish-btn').addEventListener('click', async function(e) {
|
||||
e.preventDefault();
|
||||
|
||||
const user = await getLoggedInUser();
|
||||
if (!user) {
|
||||
alert("Unable to fetch logged-in user. Please refresh and try again.");
|
||||
if (!existingRecipe || !existingRecipe.id) {
|
||||
showMessage('Recipe data was not loaded correctly.', true);
|
||||
return;
|
||||
}
|
||||
|
||||
console.log("Logged-in user:", user);
|
||||
const recipeJSON = buildRecipeJSON(user);
|
||||
console.log("Recipe JSON to submit:", JSON.stringify(recipeJSON, null, 2));
|
||||
if (!validateForm()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData();
|
||||
formData.append('title', document.getElementById('title').value.trim());
|
||||
formData.append('description', document.getElementById('desc').value.trim());
|
||||
formData.append('prepTimeMinutes', document.getElementById('prep').value.trim());
|
||||
formData.append('cookTimeMinutes', document.getElementById('cooking').value.trim());
|
||||
formData.append('servings', document.getElementById('servings').value.trim());
|
||||
formData.append('cost', document.getElementById('cost').value.trim());
|
||||
formData.append('removeImage', String(imageRemoved));
|
||||
|
||||
document.querySelectorAll('#ingredients-container .dynamic-row').forEach(row => {
|
||||
const ingredientName = row.querySelector('.ing-name').value.trim();
|
||||
if (!ingredientName) return;
|
||||
|
||||
formData.append('ingredientName', ingredientName);
|
||||
const qty = row.querySelector('.ing-qty').value.trim();
|
||||
const unit = row.querySelector('.ing-unit').value.trim();
|
||||
const notes = row.querySelector('.ing-notes').value.trim();
|
||||
|
||||
formData.append('ingredientQuantity', qty);
|
||||
if (unit) formData.append('ingredientUnit', unit);
|
||||
if (notes) formData.append('ingredientNotes', notes);
|
||||
});
|
||||
|
||||
document.querySelectorAll('#steps-container textarea').forEach(textarea => {
|
||||
const instruction = textarea.value.trim();
|
||||
if (instruction) {
|
||||
formData.append('stepInstruction', instruction);
|
||||
}
|
||||
});
|
||||
|
||||
tags.forEach(tag => formData.append('tags', tag));
|
||||
|
||||
if (imgInput.files && imgInput.files[0]) {
|
||||
formData.append('image', imgInput.files[0]);
|
||||
}
|
||||
|
||||
try {
|
||||
|
||||
const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
|
||||
const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
|
||||
|
||||
|
||||
|
||||
const res = await fetch('http://localhost:8080/api/recipes', {
|
||||
const res = await fetch(`/api/recipes/${existingRecipe.id}/upload`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
[csrfHeader]: csrfToken,
|
||||
'Content-Type': 'application/json'
|
||||
[csrfHeader]: csrfToken
|
||||
},
|
||||
body: JSON.stringify(recipeJSON),
|
||||
body: formData,
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
const responseText = await res.text();
|
||||
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
console.log("Recipe created:", data);
|
||||
alert("Recipe created successfully!");
|
||||
showSuccessAndRedirect('Recipe updated successfully!');
|
||||
} else {
|
||||
const errorData = await res.json();
|
||||
console.error("Validation errors:", errorData);
|
||||
|
||||
|
||||
const firstError = Object.values(errorData)[0];
|
||||
alert(firstError);
|
||||
console.error('Recipe update failed:', responseText);
|
||||
showMessage(responseText || 'Failed to update recipe.', true);
|
||||
}
|
||||
} catch (err) {
|
||||
console.error("Network error:", err);
|
||||
alert("Network error. Check console for details.");
|
||||
console.error('Network error:', err);
|
||||
showMessage('Network error. Check console for details.', true);
|
||||
}
|
||||
});
|
||||
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,64 +1,138 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<html lang="en" xmlns:th="http://www.thymeleaf.org">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>Thyme Crunch View Recipe</title>
|
||||
<meta name="_csrf_header" th:content="${_csrf.headerName}"/>
|
||||
<meta name="_csrf" th:content="${_csrf.token}"/>
|
||||
<title th:text="${recipe != null ? recipe.title : 'Recipe'}">Recipe</title>
|
||||
<link rel="stylesheet" th:href="@{/css/view-recipe.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">
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<header class="top-header">
|
||||
<img th:src="@{images/header_left.png}" alt="Violin f-hole shape to the left of header." class="swirl">
|
||||
<img th:src="@{/images/header_left.png}" alt="Left header swirl" class="swirl">
|
||||
<h1 class="site-name">Thyme Crunch</h1>
|
||||
<img th:src="@{images/header_right.png}" alt="Violin f-hole shape to the right of header." class="swirl">
|
||||
<img th:src="@{/images/header_right.png}" alt="Right header swirl" class="swirl">
|
||||
</header>
|
||||
|
||||
<div class="body">
|
||||
|
||||
<!--Navigation Bar -->
|
||||
<div class="body-left">
|
||||
<nav class="sidebar-left">
|
||||
<ul>
|
||||
<li><a href="#">Home</a></li>
|
||||
<li><a href="#">Explore</a></li>
|
||||
<li><a href="#">Profile</a></li>
|
||||
<li><a href="#">Saved</a></li>
|
||||
<li><a href="/">Home</a></li>
|
||||
<li><a th:href="@{/explore}">Explore</a></li>
|
||||
<li><a th:href="@{/my-profile}">Profile</a></li>
|
||||
<li>
|
||||
<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>
|
||||
</li>
|
||||
</ul>
|
||||
</nav>
|
||||
<a th:href="@{/create}" target="_blank" class="create_icon">
|
||||
<img th:src="@{images/create_icon.png}" alt="Description of the icon">
|
||||
<img th:src="@{/images/create_icon.png}" alt="Create New Recipe Icon (Red mixing bowl with a spoon and yellow addition symbol.">
|
||||
</a>
|
||||
</div>
|
||||
|
||||
|
||||
<!-- Main Content -->
|
||||
<main class="main-content">
|
||||
<div class="form-wrap">
|
||||
<h1 th:text="${recipe.title}"></h1>
|
||||
<p th:text="${recipe.description}"></p>
|
||||
<div th:if="${recipe != null}" style="width: 100%; max-width: 950px; margin: 35px auto;">
|
||||
|
||||
<div class="form-section">
|
||||
<div class="section-title">Ingredients</div>
|
||||
<ul>
|
||||
<li th:each="ingredient : ${recipe.ingredients}"
|
||||
th:text="${ingredient.name}"></li>
|
||||
<section style="background: var(--peach); border-radius: 20px; padding: 18px 24px; color: var(--dark);">
|
||||
<h1 style="margin-top: 0; font-size: 2.8em;" th:text="${recipe.title}">Recipe Title</h1>
|
||||
|
||||
<p th:if="${recipe.userDto != null}" style="font-size: 1.2em; margin-bottom: 20px;">
|
||||
<strong>Author:</strong>
|
||||
<a th:href="@{/users/{id}(id=${recipe.userDto.id})}"
|
||||
th:text="${recipe.userDto.displayName != null and !#strings.isEmpty(recipe.userDto.displayName) ? recipe.userDto.displayName : recipe.userDto.username}">
|
||||
Author Name
|
||||
</a>
|
||||
</p>
|
||||
|
||||
<div th:if="${recipe.images != null and !#lists.isEmpty(recipe.images)}" style="margin-bottom: 28px;">
|
||||
<img th:src="${recipe.images[0].imageUrl}"
|
||||
alt="Recipe Image"
|
||||
style="display:block; width:100%; max-width:700px; max-height:420px; object-fit:cover; border-radius:16px; margin:0 auto;">
|
||||
</div>
|
||||
|
||||
<p th:unless="${recipe.images != null and !#lists.isEmpty(recipe.images)}"
|
||||
style="margin-bottom: 28px; font-style: italic;">
|
||||
No image uploaded for this recipe.
|
||||
</p>
|
||||
|
||||
<div style="margin-bottom: 25px;">
|
||||
<h2>Description</h2>
|
||||
<p th:text="${recipe.description}">Recipe description</p>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; flex-wrap: wrap; gap: 20px; margin-bottom: 30px; font-size: 1.1em;">
|
||||
<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>Servings:</strong> <span th:text="${recipe.servings}">0</span></p>
|
||||
<p><strong>Cost:</strong> <span th:text="${recipe.cost}">0</span></p>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 30px;">
|
||||
<h2>Ingredients</h2>
|
||||
<ul th:if="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}" style="line-height: 1.8;">
|
||||
<li th:each="ingredient : ${recipe.ingredients}">
|
||||
<span th:text="${ingredient.quantity}">1</span>
|
||||
<span th:text="${ingredient.unit}">cup</span>
|
||||
<span th:text="${ingredient.ingredientName}">Ingredient</span>
|
||||
<span th:if="${ingredient.notes != null and !#strings.isEmpty(ingredient.notes)}"
|
||||
th:text="${'(' + ingredient.notes + ')'}">(notes)</span>
|
||||
</li>
|
||||
</ul>
|
||||
<p th:unless="${recipe.ingredients != null and !#lists.isEmpty(recipe.ingredients)}">No ingredients listed.</p>
|
||||
</div>
|
||||
|
||||
<div class="form-section">
|
||||
<div class="section-title">Instructions</div>
|
||||
<ol class="step-list">
|
||||
<li th:each="step : ${#lists.sort(recipe.steps, comparingInt(step -> step.stepNumber))}">
|
||||
</ol
|
||||
<div style="margin-bottom: 30px;">
|
||||
<h2>Steps</h2>
|
||||
<ol th:if="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}" style="line-height: 1.9;">
|
||||
<li th:each="step : ${recipe.steps}" th:text="${step.instruction}">Step instruction</li>
|
||||
</ol>
|
||||
<p th:unless="${recipe.steps != null and !#lists.isEmpty(recipe.steps)}">No steps listed.</p>
|
||||
</div>
|
||||
|
||||
<div style="margin-bottom: 25px;">
|
||||
<h2>Tags</h2>
|
||||
<div th:if="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}" style="display: flex; flex-wrap: wrap; gap: 10px;">
|
||||
<span th:each="tag : ${recipe.tags}"
|
||||
th:text="${tag.name}"
|
||||
style="background: var(--pale-yellow); padding: 8px 14px; border-radius: 999px; font-weight: 700;">
|
||||
Tag
|
||||
</span>
|
||||
</div>
|
||||
<p th:unless="${recipe.tags != null and !#lists.isEmpty(recipe.tags)}">No tags listed.</p>
|
||||
</div>
|
||||
|
||||
<div style="display: flex; gap: 20px; flex-wrap: wrap; margin-top: 25px;">
|
||||
<a th:if="${recipe.userDto != null}"
|
||||
th:href="@{/users/{id}(id=${recipe.userDto.id})}">
|
||||
View author's profile
|
||||
</a>
|
||||
<a th:href="@{/explore}">Back to Explore</a>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<div th:unless="${recipe != null}" style="width: 100%; max-width: 950px; margin: 35px auto;">
|
||||
<section style="background: var(--peach); border-radius: 20px; padding: 28px 32px; color: var(--dark);">
|
||||
<h1>Recipe not found</h1>
|
||||
<p><a th:href="@{/explore}">Back to Explore</a></p>
|
||||
</section>
|
||||
</div>
|
||||
</main>
|
||||
|
||||
<!-- Right spacer/sidebar -->
|
||||
<div class="body-right">
|
||||
<div class="sidebar-right"></div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user