added pop up view ingredients + warnings for delete

This commit is contained in:
Aysegul 2026-01-09 21:42:57 +01:00
commit 9aae8f918f
9 changed files with 574 additions and 17 deletions

View file

@ -6,6 +6,7 @@ import commons.ws.Topics;
import commons.ws.messages.CreateIngredientMessage;
import commons.ws.messages.DeleteIngredientMessage;
import commons.ws.messages.UpdateIngredientMessage;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.DeleteMapping;
@ -115,6 +116,8 @@ public class IngredientController {
/**
* Update an existing ingredient by its ID.
* Maps to <code>PATCH /api/ingredients/{id}</code>
@ -165,17 +168,25 @@ public class IngredientController {
* @see Ingredient
*/
@PostMapping("/ingredients")
public ResponseEntity<Ingredient> createIngredient(@RequestBody Ingredient ingredient) {
if (ingredient.name == null || ingredient.name.isEmpty()) {
return ResponseEntity.badRequest().build();
public ResponseEntity<?> createIngredient(@RequestBody Ingredient ingredient) {
if (ingredient == null
|| ingredient.name == null
|| ingredient.name.trim().isEmpty()) {
return ResponseEntity.badRequest()
.body("Ingredient name cannot be empty.");
}
return ingredientService.create(ingredient)
.map(saved -> {
messagingTemplate.convertAndSend(Topics.INGREDIENTS, new CreateIngredientMessage(saved));
.<ResponseEntity<?>>map
(saved -> {
messagingTemplate.convertAndSend(Topics.INGREDIENTS,
new CreateIngredientMessage(saved));
return ResponseEntity.ok(saved);
})
.orElseGet(() -> ResponseEntity.badRequest().build());
.orElseGet(() ->
ResponseEntity.status(409)
.body("ingredient name already exists"));
}
/**
@ -194,13 +205,24 @@ public class IngredientController {
*/
@DeleteMapping("/ingredients/{id}")
public ResponseEntity<Boolean> deleteIngredient(@PathVariable Long id) {
//check if the ingredient is used in any recipe
long usageCount = ingredientService.countUsage(id);
if (usageCount > 0) {
// If used in recipes, return a warning response (HTTP 400)
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
.body(false); // Ingredient in use, don't delete
}
// delete if the ingredient is not in use
if (!ingredientService.delete(id)) {
return ResponseEntity.notFound().build();
}
messagingTemplate.convertAndSend(Topics.INGREDIENTS, new DeleteIngredientMessage(id));
return ResponseEntity.ok(true);
return ResponseEntity.ok(true); // deleted~
}
public record IngredientUsageResponse(Long ingredientId, long usedInRecipes){}
}