Merge branch 'main' of gitlab.com:etc404/software-engineering-project

This commit is contained in:
kaipher7
2026-04-23 23:58:05 -06:00
7 changed files with 313 additions and 343 deletions
+3
View File
@@ -31,6 +31,9 @@ jobs:
- name: Build with Maven
run: mvn clean package -Dmaven.test.skip
- name: Sad Face Emoji
run: cat src/main/resources/static/css/create-recipe.css
- name: Log into Registry
uses: docker/login-action@v2
with:
@@ -1,11 +1,17 @@
package com.example.demo.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import com.example.demo.entity.Favorite;
import com.example.demo.entity.FavoriteId;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.transaction.annotation.Transactional;
import com.example.demo.entity.Favorite;
import com.example.demo.entity.FavoriteId;
public interface FavoriteRepo extends JpaRepository<Favorite, FavoriteId> {
@Transactional
void deleteById_RecipeId(Integer recipeId);
List<Favorite> findById_RecipeId(Integer recipeId);
}
@@ -30,6 +30,7 @@ import com.example.demo.repository.RecipeRepo;
import com.example.demo.repository.StepRepo;
import com.example.demo.repository.TagRepo;
import com.example.demo.repository.UserRepo;
import com.example.demo.repository.FavoriteRepo;
import com.example.demo.service.RecipeService;
import jakarta.transaction.Transactional;
@@ -44,11 +45,18 @@ public class RecipeServiceImpl implements RecipeService {
private StepRepo stepRepository;
private ImageRepo imageRepository;
private TagRepo tagRepository;
private FavoriteRepo favoriteRepo;
public RecipeServiceImpl(RecipeRepo recipeRepository, IngredientRepo ingredientRepository,
RecipeIngredientRepo recipeIngredientRepository, UserRepo userRepository, StepRepo stepRepository,
ImageRepo imageRepository, TagRepo tagRepository) {
super();
public RecipeServiceImpl(
RecipeRepo recipeRepository,
IngredientRepo ingredientRepository,
RecipeIngredientRepo recipeIngredientRepository,
UserRepo userRepository,
StepRepo stepRepository,
ImageRepo imageRepository,
TagRepo tagRepository,
FavoriteRepo favoriteRepo
) {
this.recipeRepository = recipeRepository;
this.ingredientRepository = ingredientRepository;
this.recipeIngredientRepository = recipeIngredientRepository;
@@ -56,6 +64,7 @@ public class RecipeServiceImpl implements RecipeService {
this.stepRepository = stepRepository;
this.imageRepository = imageRepository;
this.tagRepository = tagRepository;
this.favoriteRepo = favoriteRepo;
}
@Override
@@ -64,20 +73,26 @@ public class RecipeServiceImpl implements RecipeService {
return;
}
}
@Override
public RecipeDto convertToDto(Recipe recipe) {
List<RecipeIngredientDto> ingredientDtos = recipe.getRecipeIngredients().stream()
.map(ri -> new RecipeIngredientDto(ri.getIngredient().getName(), ri.getQuantity(), ri.getUnit(),
ri.getNotes()))
.toList();
List<StepDto> stepDtos = recipe.getSteps().stream()
.map(ri -> new StepDto(ri.getStepNumber(), ri.getInstruction())).toList();
.map(ri -> new StepDto(ri.getStepNumber(), ri.getInstruction()))
.toList();
List<ImageDto> imageDtos = recipe.getImages().stream().map(ri -> new ImageDto(ri.getImageUrl())).toList();
List<ImageDto> imageDtos = recipe.getImages().stream()
.map(ri -> new ImageDto(ri.getImageUrl()))
.toList();
List<TagDto> tagDtos = recipe.getTags().stream().map(ri -> new TagDto(ri.getName())).toList();
List<TagDto> tagDtos = recipe.getTags().stream()
.map(ri -> new TagDto(ri.getName()))
.toList();
UserDto userDto = new UserDto(
recipe.getUser().getId(),
@@ -87,12 +102,22 @@ public class RecipeServiceImpl implements RecipeService {
recipe.getUser().getBio()
);
RecipeDto dto = new RecipeDto(recipe.getTitle(), recipe.getDescription(), recipe.getPrepTimeMinutes(),
recipe.getCookTimeMinutes(), recipe.getServings(), userDto, recipe.getStatus(), ingredientDtos,
stepDtos, imageDtos, tagDtos, recipe.getCost());
RecipeDto dto = new RecipeDto(
recipe.getTitle(),
recipe.getDescription(),
recipe.getPrepTimeMinutes(),
recipe.getCookTimeMinutes(),
recipe.getServings(),
userDto,
recipe.getStatus(),
ingredientDtos,
stepDtos,
imageDtos,
tagDtos,
recipe.getCost()
);
dto.setId(recipe.getId());
return dto;
}
@@ -112,9 +137,7 @@ public class RecipeServiceImpl implements RecipeService {
}
private void enforceUploadLimit(User user) {
if (isAdmin(user)) {
return;
}
if (isAdmin(user)) return;
LocalDateTime cutoff = LocalDateTime.now().minusHours(24);
long uploadsInLast24Hours = recipeRepository.countByUserIdAndCreatedAtAfter(user.getId(), cutoff);
@@ -125,15 +148,30 @@ public class RecipeServiceImpl implements RecipeService {
}
private void enforceOwnerOrAdmin(User currentUser, Recipe recipe) {
if (isAdmin(currentUser)) {
return;
}
if (isAdmin(currentUser)) return;
if (!recipe.getUser().getId().equals(currentUser.getId())) {
throw new AccessDeniedException("You do not have permission to modify this recipe.");
}
}
@Override
@Transactional
public void deleteRecipe(Integer id, String currentUsername) {
User currentUser = getCurrentUser(currentUsername);
ensureUserNotBanned(currentUser);
Recipe recipe = recipeRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Recipe", "id", id));
enforceOwnerOrAdmin(currentUser, recipe);
favoriteRepo.deleteById_RecipeId(id);
recipeRepository.delete(recipe);
}
@Override
@Transactional
public RecipeDto saveRecipe(RecipeDto dto, String currentUsername) {
@@ -153,111 +191,33 @@ public class RecipeServiceImpl implements RecipeService {
dto.getCost()
);
if (dto.getIngredients() != null) {
java.util.Set<String> seenIngredientNames = new java.util.HashSet<>();
java.util.Set<Integer> seenIngredientIds = new java.util.HashSet<>();
for (int i = 0; i < dto.getIngredients().size(); i++) {
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) {
ingredientRepository.save(ingredient);
}
if (ingredient.getId() != null && !seenIngredientIds.add(ingredient.getId())) {
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);
}
}
if (dto.getSteps() != null) {
for (StepDto stepDto : dto.getSteps()) {
Step step = new Step(recipe, stepDto.getStepNumber(), stepDto.getInstruction());
recipe.getSteps().add(step);
}
}
if (dto.getImages() != null) {
for (ImageDto imageDto : dto.getImages()) {
Image image = new Image(recipe, imageDto.getImageUrl());
recipe.getImages().add(image);
}
}
if (dto.getTags() != null) {
for (TagDto tDto : dto.getTags()) {
Tag tag = tagRepository.findByName(tDto.getName()).orElseGet(() -> new Tag(tDto.getName()));
if (tag.getId() == null) {
tagRepository.save(tag);
}
recipe.getTags().add(tag);
}
}
Recipe saved = recipeRepository.save(recipe);
return getRecipeById(saved.getId());
}
@Override
@Transactional
public List<RecipeDto> getAllRecipes() {
List<RecipeDto> list = new ArrayList<>();
for (Recipe recipe : recipeRepository.findAll()) {
RecipeDto recipeDto = convertToDto(recipe);
list.add(recipeDto);
list.add(convertToDto(recipe));
}
return list;
}
@Override
@Transactional
public List<RecipeDto> getNewestRecipes(int limit) {
return recipeRepository.findAll().stream()
.filter(r -> r.getCreatedAt() != null)
.sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
.limit(limit)
.map(this::convertToDto)
.collect(Collectors.toList());
}
@Override
@Transactional
public RecipeDto getRecipeById(Integer Id) {
return convertToDto(recipeRepository.findById(Id).orElseThrow(() -> new NotFoundException("Recipe", "id", Id)));
return convertToDto(
recipeRepository.findById(Id)
.orElseThrow(() -> new NotFoundException("Recipe", "id", Id))
);
}
@Override
@Transactional
public RecipeDto updateRecipe(RecipeDto recipeDto, Integer id, String currentUsername) {
User currentUser = getCurrentUser(currentUsername);
ensureUserNotBanned(currentUser);
@@ -274,244 +234,36 @@ public class RecipeServiceImpl implements RecipeService {
existingRecipe.setStatus(recipeDto.getStatus());
existingRecipe.setCost(recipeDto.getCost());
List<RecipeIngredientDto> updatedIngredients = recipeDto.getIngredients();
List<RecipeIngredient> ingredientsToRemove = new ArrayList<>();
List<StepDto> updatedSteps = recipeDto.getSteps();
List<Step> stepsToRemove = new ArrayList<>();
List<ImageDto> updatedImages = recipeDto.getImages();
List<Image> imagesToRemove = new ArrayList<>();
List<TagDto> updatedTags = recipeDto.getTags();
List<Tag> tagsToRemove = new ArrayList<>();
if (updatedIngredients != null) {
for (RecipeIngredient ri : existingRecipe.getRecipeIngredients()) {
boolean existsInUpdatedList = false;
for (RecipeIngredientDto dto : updatedIngredients) {
String updatedName = dto.getIngredientName();
String existingName = ri.getIngredient().getName();
if (java.util.Objects.equals(updatedName, existingName)) {
existsInUpdatedList = true;
break;
}
}
if (!existsInUpdatedList) {
ingredientsToRemove.add(ri);
}
}
existingRecipe.getRecipeIngredients().removeAll(ingredientsToRemove);
for (RecipeIngredientDto riDto : updatedIngredients) {
RecipeIngredient existingRI = existingRecipe.getRecipeIngredients().stream()
.filter(ri -> java.util.Objects.equals(ri.getIngredient().getName(), riDto.getIngredientName()))
.findFirst()
.orElse(null);
if (existingRI != null) {
existingRI.setQuantity(riDto.getQuantity());
existingRI.setUnit(riDto.getUnit());
existingRI.setNotes(riDto.getNotes());
}
else {
Ingredient ingredient = ingredientRepository.findByNameIgnoreCase(riDto.getIngredientName())
.orElseGet(() -> new Ingredient(riDto.getIngredientName()));
if (ingredient.getId() == null) {
ingredientRepository.save(ingredient);
}
RecipeIngredient newRI = new RecipeIngredient(existingRecipe, ingredient, riDto.getQuantity(),
riDto.getUnit(), riDto.getNotes());
existingRecipe.getRecipeIngredients().add(newRI);
}
}
}
if (updatedSteps != null) {
for (Step step : existingRecipe.getSteps()) {
boolean existsInUpdatedList = updatedSteps.stream()
.anyMatch(dto -> dto.getStepNumber().equals(step.getStepNumber()));
if (!existsInUpdatedList)
stepsToRemove.add(step);
}
existingRecipe.getSteps().removeAll(stepsToRemove);
for (StepDto stepDto : updatedSteps) {
Step existingStep = existingRecipe.getSteps().stream()
.filter(s -> s.getStepNumber().equals(stepDto.getStepNumber())).findFirst().orElse(null);
if (existingStep != null) {
existingStep.setInstruction(stepDto.getInstruction());
}
else {
Step newStep = new Step(existingRecipe, stepDto.getStepNumber(), stepDto.getInstruction());
existingRecipe.getSteps().add(newStep);
}
}
}
if (updatedImages != null) {
for (Image image : existingRecipe.getImages()) {
boolean existsInUpdatedList = updatedImages.stream()
.anyMatch(dto -> java.util.Objects.equals(dto.getImageUrl(), image.getImageUrl()));
if (!existsInUpdatedList)
imagesToRemove.add(image);
}
existingRecipe.getImages().removeAll(imagesToRemove);
for (ImageDto imageDto : updatedImages) {
Image existingImage = existingRecipe.getImages().stream()
.filter(img -> java.util.Objects.equals(img.getImageUrl(), imageDto.getImageUrl()))
.findFirst()
.orElse(null);
if (existingImage != null) {
existingImage.setImageUrl(imageDto.getImageUrl());
} else {
Image newImage = new Image(existingRecipe, imageDto.getImageUrl());
existingRecipe.getImages().add(newImage);
}
}
}
if (updatedTags != null) {
for (Tag tag : existingRecipe.getTags()) {
boolean existsInUpdatedList = updatedTags.stream()
.anyMatch(dto -> java.util.Objects.equals(dto.getName(), tag.getName()));
if (!existsInUpdatedList)
tagsToRemove.add(tag);
}
existingRecipe.getTags().removeAll(tagsToRemove);
for (TagDto tagDto : updatedTags) {
Tag existingTag = existingRecipe.getTags().stream()
.filter(tag -> java.util.Objects.equals(tag.getName(), tagDto.getName()))
.findFirst()
.orElse(null);
if (existingTag != null) {
existingTag.setName(tagDto.getName());
} else {
Tag newTag = tagRepository.findByName(tagDto.getName())
.orElseGet(() -> tagRepository.save(new Tag(tagDto.getName())));
existingRecipe.getTags().add(newTag);
}
}
}
recipeRepository.save(existingRecipe);
return convertToDto(existingRecipe);
}
@Override
@Transactional
public void deleteRecipe(Integer id, String currentUsername) {
User currentUser = getCurrentUser(currentUsername);
ensureUserNotBanned(currentUser);
Recipe recipe = recipeRepository.findById(id)
.orElseThrow(() -> new NotFoundException("Recipe", "id", id));
enforceOwnerOrAdmin(currentUser, recipe);
recipeRepository.delete(recipe);
public List<RecipeDto> getNewestRecipes(int limit) {
return recipeRepository.findAll().stream()
.filter(r -> r.getCreatedAt() != null)
.sorted((a, b) -> b.getCreatedAt().compareTo(a.getCreatedAt()))
.limit(limit)
.map(this::convertToDto)
.collect(Collectors.toList());
}
@Override
@Transactional
public List<RecipeDto> getRecipes(String name, List<String> tags, List<Integer> prices, List<Integer> cookTime, List<Integer> prepTime) {
public List<RecipeDto> getRecipes(String name, List<String> tags, List<Integer> prices,
List<Integer> cookTime, List<Integer> prepTime) {
List<Recipe> recipes;
List<Recipe> recipes = recipeRepository.findAll();
if ((name != null) && (!name.isBlank())) {
if (name != null && !name.isBlank()) {
recipes = recipeRepository.findByTitleContainingIgnoreCase(name);
}
else {
recipes = recipeRepository.findAll();
List<RecipeDto> result = new ArrayList<>();
for (Recipe r : recipes) {
result.add(convertToDto(r));
}
if ((tags != null) && (!tags.isEmpty()) && !recipes.isEmpty()) {
recipes = recipes.stream()
.filter(recipe -> recipe.getTags().stream().anyMatch(tag -> tags.contains(tag.getName())))
.collect(Collectors.toList());
}
if (prices != null && !prices.isEmpty() && !recipes.isEmpty()) {
recipes = recipes.stream()
.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());
}
if (cookTime != null && !cookTime.isEmpty() && !recipes.isEmpty()) {
recipes = recipes.stream()
.filter(recipe -> {
int minutes = recipe.getCookTimeMinutes();
for (Integer ct : cookTime) {
if (ct == 15 && minutes <= 15) return true;
if (ct == 30 && minutes > 15 && minutes <= 30) return true;
if (ct == 60 && minutes > 30 && minutes <= 60) return true;
if (ct == 120 && minutes > 60 && minutes <= 120) return true;
if (ct == 121 && minutes > 120) return true;
}
return false;
})
.collect(Collectors.toList());
}
if (prepTime != null && !prepTime.isEmpty() && !recipes.isEmpty()) {
recipes = recipes.stream()
.filter(recipe -> {
int minutes = recipe.getPrepTimeMinutes();
for (Integer ct : prepTime) {
if (ct == 15 && minutes <= 15) return true;
if (ct == 30 && minutes > 15 && minutes <= 30) return true;
if (ct == 60 && minutes > 30 && minutes <= 60) return true;
if (ct == 240 && minutes > 60 && minutes <= 240) return true;
if (ct == 241 && minutes > 240) return true;
}
return false;
})
.collect(Collectors.toList());
}
List<RecipeDto> recipeList = new ArrayList<>();
for (Recipe recipe : recipes) {
RecipeDto dto = convertToDto(recipe);
recipeList.add(dto);
}
return recipeList;
return result;
}
}
@@ -420,3 +420,35 @@ a {
flex-shrink: 0;
width: 50%;
}
/* =========================
Top Row (My Recipes + Feedback)
========================= */
.profile-top-row {
width: 100%;
display: flex;
justify-content: space-between;
align-items: center;
}
.profile-top-row h2 {
margin: 0;
}
/* =========================
Feedback Button
========================= */
.feedback-btn {
background: var(--dark);
color: var(--dark-yellow) !important;
border-radius: 8px;
padding: 6px 14px;
font-weight: 700;
font-size: 0.7em;
text-decoration: none !important;
display: inline-block;
}
.feedback-btn:hover {
background: var(--dusty-red-hover);
}
@@ -8,6 +8,7 @@
<title>Create Thyme Crunch Account</title>
<link rel="stylesheet" th:href="@{css/create-account.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">
<script th:src="@{/js/bad-words-list.js}"></script>
</head>
<body>
@@ -58,6 +59,28 @@
</html>
<script>
function isProfane(str) {
const lower = str.toLowerCase();
return bannedWords.some(word => lower.includes(word));
}
function showError(input, message) {
input.classList.add('invalid');
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;
}
document.addEventListener("DOMContentLoaded", function () {
const form = document.getElementById("createUserForm");
@@ -68,9 +91,10 @@
function checkPasswords() {
if (confirmPasswordField.value === "") {
confirmPasswordField.classList.remove("invalid");
passwordError.textContent = "";
passwordError.textContent = "Password cannot be blank";
return;
}
if (passwordField.value !== confirmPasswordField.value) {
confirmPasswordField.classList.add("invalid");
@@ -89,12 +113,21 @@
const password = passwordField.value;
const confirmPassword = confirmPasswordField.value;
const name = document.getElementById("username").value;
const email = document.getElementById("email").value;
if (password !== confirmPassword) {
confirmPasswordField.classList.add("invalid");
passwordError.textContent = "Passwords do not match.";
return;
}
if (isProfane(document.getElementById("username").value)) {
showError(username, 'Username contains inappropriate language');
return;
}
const userData = {
username: document.getElementById("username").value,
+59 -2
View File
@@ -7,6 +7,7 @@
<title>My 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">
<script th:src="@{/js/bad-words-list.js}"></script>
</head>
<body>
@@ -45,7 +46,13 @@
<!-- Main Content — recipes -->
<main class="main-content">
<h2>My Recipes</h2>
<div class="profile-top-row">
<h2>My Recipes</h2>
<a href="https://forms.gle/qUx73EL7vjBDBXde7"
target="_blank"
rel="noopener noreferrer"
class="feedback-btn">Give Feedback</a>
</div>
<p th:if="${#lists.isEmpty(profile.recipes)}">You have not created any recipes yet.</p>
@@ -88,7 +95,7 @@
<label for="bio">Bio</label>
<textarea id="bio" th:field="*{bio}" rows="6" maxlength="1000"></textarea>
</div>
<button type="submit">Save</button>
<button type="submit" value='submit request' onclick='return btnClick();'>Save</button>
</form>
</div>
@@ -97,6 +104,56 @@
</div>
<script>
function isProfane(str) {
const lower = str.toLowerCase();
return bannedWords.some(word => lower.includes(word));
}
</script>
<script>
function btnClick() {
const displayNameEl = document.getElementById('displayName');
const bioEl = document.getElementById('bio');
clearError(displayNameEl);
clearError(bioEl);
if (isProfane(displayNameEl.value)) {
showError(displayNameEl, "Display name contains inappropriate language.");
return false;
}
if (isProfane(bioEl.value)) {
showError(bioEl, "Bio contains inappropriate language.");
return false;
}
return true;
function showError(input, message) {
input.classList.add('invalid');
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();
}
}
</script>
<script>
// For cost display <!-- Cost change -->
function renderCost(cost) {
const num = parseInt(cost, 10);
+97 -10
View File
@@ -8,6 +8,7 @@
<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">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css">
<script th:src="@{/js/bad-words-list.js}"></script>
</head>
<body>
@@ -115,6 +116,13 @@
<script>
// ---- DOM refs ----
function isProfane(str) {
const lower = str.toLowerCase();
return bannedWords.some(word => lower.includes(word));
}
const ingredientContainer = document.getElementById('ingredients-container');
const stepsContainer = document.getElementById('steps-container');
const dropZone = document.getElementById('drop-zone');
@@ -241,16 +249,16 @@ document.getElementById('add-tag-btn').addEventListener('click', function (e) {
});
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;
}
tags.push(val);
input.value = '';
renderTags();
}
const input = document.getElementById('tag-input');
const val = input.value.trim().toLowerCase().replace(/\s+/g, '-');
if (!val || tags.includes(val) || isProfane(val)) {
input.value = '';
return;
}
tags.push(val);
input.value = '';
renderTags();
}
function removeTag(t) {
tags.splice(tags.indexOf(t), 1);
@@ -381,11 +389,22 @@ function validateForm() {
showError(title, 'Title is required');
valid = false;
}
if (isProfane(title.value)) {
showError(title, 'Title contains inappropriate language');
valid = false;
}
if (!desc.value.trim()) {
showError(desc, 'Description is required');
valid = false;
}
if (isProfane(desc.value)) {
showError(desc, 'Description contains inappropriate language');
valid = false;
}
if (!prep.value.trim() || isNaN(Number(prep.value)) || Number(prep.value) <= 0) {
showError(prep, 'Enter a valid prep time');
@@ -409,17 +428,85 @@ function validateForm() {
const ingredientRows = [...document.querySelectorAll('#ingredients-container .dynamic-row')];
const hasIngredient = ingredientRows.some(row => row.querySelector('.ing-name').value.trim() !== '');
const filledIngredientRows = ingredientRows.filter(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;
}
filledIngredientRows.forEach(row => {
const nameInput = row.querySelector('.ing-name');
const qtyInput = row.querySelector('.ing-qty');
const unitInput = row.querySelector('.ing-unit');
const noteInput = row.querySelector('.ing-notes');
clearError(nameInput);
clearError(qtyInput);
if (!nameInput.value.trim()) {
showError(nameInput, 'Ingredient name is required');
valid = false;
}
if (isProfane(nameInput.value.trim())) {
showError(nameInput, 'Ingredient name contains inappropriate language');
valid = false;
}
if (isProfane(unitInput.value.trim())) {
showError(noteInput, 'Ingredient unit contains inappropriate language');
valid = false;
}
if (isProfane(noteInput.value.trim())) {
showError(noteInput, 'Ingredient note contains inappropriate language');
valid = false;
}
const qtyVal = qtyInput.value.trim();
if (!isValidQuantity(qtyVal)) {
showError(qtyInput, 'Enter a valid quantity (e.g. 2, 1.5, 1/2, 1 1/2) or leave blank');
valid = false;
}
});
function isValidQuantity(val) {
const cleaned = String(val ?? '').replace(/\s+/g, ' ').trim();
if (cleaned === '') return true;
if (/^\d+(\.\d+)?$/.test(cleaned)) {
return true;
}
if (/^\d+\/\d+$/.test(cleaned)) {
const [numerator, denominator] = cleaned.split('/');
return Number(numerator) >= 0 && Number(denominator) > 0;
}
if (/^\d+\s\d+\/\d+$/.test(cleaned)) {
const [whole, fraction] = cleaned.split(' ');
const [numerator, denominator] = fraction.split('/');
return Number(whole) >= 0 && Number(numerator) >= 0 && Number(denominator) > 0;
}
return false;
}
const stepAreas = [...document.querySelectorAll('#steps-container textarea')];
const filledSteps = stepAreas.filter(textarea => textarea.value.trim() !== '');
const hasStep = stepAreas.some(textarea => textarea.value.trim() !== '');
if (!hasStep && stepAreas.length > 0) {
showError(stepAreas[0], 'Add at least one instruction step');
valid = false;
}
filledSteps.forEach(textarea => {
if (isProfane(textarea.value)) {
showError(textarea, 'Step contains inappropriate language');
valid = false;
}});
if (!valid) {
document.querySelector('.invalid')?.scrollIntoView({