Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9f28d96533 |
No files matched your search
@@ -1,6 +1,5 @@
|
||||
package de.timaldinger.einkaufsliste.Controller;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
@@ -41,7 +40,7 @@ public class PageController {
|
||||
*/
|
||||
@GetMapping("/list/{id}")
|
||||
public String list(Model model, @PathVariable UUID id){
|
||||
ShoppingList list = shoppingListRepository.findById(id).orElseThrow(() -> new ResourceNotFoundException("Seite",id));
|
||||
ShoppingList list = shoppingListRepository.findById(id).orElseThrow();
|
||||
List<ShoppingList> lists = shoppingListRepository.findAll();
|
||||
model.addAttribute("lists", lists);
|
||||
model.addAttribute("list", list);
|
||||
|
||||
+6
-19
@@ -3,23 +3,18 @@ package de.timaldinger.einkaufsliste.Controller;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingCategoryPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingCategoryPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingCategoryResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingCategory;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -33,27 +28,21 @@ public class ShoppingCategoryController {
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
|
||||
@PostMapping("/api/categories")
|
||||
public ResponseEntity<ShoppingCategoryResponseDTO> addCategory(@Valid @RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
public ShoppingCategoryResponseDTO addCategory(@RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
|
||||
String name = newCategory.categoryName();
|
||||
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow(() -> new ResourceNotFoundException("listID",newCategory.listID()));
|
||||
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow();
|
||||
|
||||
ShoppingCategory category = new ShoppingCategory(name, List.of(),list);
|
||||
|
||||
shoppingCategoryRepository.save(category);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(category.getId())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingCategoryResponseDTO(name, category.getId()));
|
||||
return new ShoppingCategoryResponseDTO(name, category.getId());
|
||||
}
|
||||
|
||||
@PatchMapping("/api/categories/{categoryID}")
|
||||
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID,@Valid @RequestBody ShoppingCategoryPatchDTO toChange){
|
||||
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID",categoryID));
|
||||
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID,@RequestBody ShoppingCategoryPatchDTO toChange){
|
||||
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow();
|
||||
|
||||
if(toChange.categoryName() != null) category.setCategoryName(toChange.categoryName());
|
||||
|
||||
@@ -67,11 +56,9 @@ public class ShoppingCategoryController {
|
||||
public ResponseEntity<Void> deleteCategory(@PathVariable UUID categoryID, @RequestParam(required = false) Boolean deleteAllItems){
|
||||
|
||||
if(deleteAllItems == null){
|
||||
throw new BadRequestException("Missing required parameter deleteAllItems (can be either true or false)");
|
||||
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Missing required parameter deleteAllItems (can be either true or false)");
|
||||
}
|
||||
|
||||
shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID", categoryID));
|
||||
|
||||
List<ShoppingItem> itemList = shoppingItemRepository.findAllByCategory_Id(categoryID);
|
||||
if(deleteAllItems){
|
||||
itemList.forEach((item) -> shoppingItemRepository.deleteById(item.getId()));
|
||||
|
||||
@@ -3,24 +3,16 @@ package de.timaldinger.einkaufsliste.Controller;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingItemPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingItemPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingItemResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingCategory;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import jakarta.annotation.Resource;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -34,37 +26,30 @@ public class ShoppingItemController {
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
|
||||
@PostMapping("/api/items")
|
||||
public ResponseEntity<ShoppingItemResponseDTO> addItem(@Valid @RequestBody ShoppingItemPostDTO newItem){
|
||||
public ShoppingItemResponseDTO addItem(@RequestBody ShoppingItemPostDTO newItem){
|
||||
String name = newItem.itemName();
|
||||
String amount = newItem.itemAmount();
|
||||
ShoppingCategory c;
|
||||
if(newItem.categoryID() != null){
|
||||
c = shoppingCategoryRepository.findById(newItem.categoryID()).orElseThrow(() -> new ResourceNotFoundException("categoryID", newItem.categoryID()));
|
||||
c = shoppingCategoryRepository.findById(newItem.categoryID()).orElseThrow();
|
||||
}else{
|
||||
c = null;
|
||||
}
|
||||
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow(() -> new ResourceNotFoundException("listID", newItem.listID()));
|
||||
|
||||
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow();
|
||||
ShoppingItem item = new ShoppingItem(name, amount, false, c, list);
|
||||
shoppingItemRepository.save(item);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(item.getId())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingItemResponseDTO(name,amount,item.getId(),c != null ? c.getId() : null));
|
||||
return new ShoppingItemResponseDTO(name, amount, item.getId(), c != null? c.getId() : null);
|
||||
}
|
||||
|
||||
@PatchMapping("/api/items/{itemID}")
|
||||
public ResponseEntity<Void> editItem(@PathVariable UUID itemID , @Valid @RequestBody ShoppingItemPatchDTO toChange){
|
||||
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID",itemID));
|
||||
public ResponseEntity<Void> editItem(@PathVariable UUID itemID ,@RequestBody ShoppingItemPatchDTO toChange){
|
||||
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow();
|
||||
|
||||
if(toChange.itemName() != null) item.setItemName(toChange.itemName());
|
||||
if(toChange.itemAmount() != null) item.setItemAmount(toChange.itemAmount());
|
||||
if(toChange.isDone() != null) item.setDone(toChange.isDone());
|
||||
if(toChange.categoryID() != null) item.setCategory(shoppingCategoryRepository.findById(toChange.categoryID()).orElseThrow(() -> new ResourceNotFoundException("categoryID",toChange.categoryID())));
|
||||
if(toChange.categoryID() != null) item.setCategory(shoppingCategoryRepository.findById(toChange.categoryID()).orElseThrow());
|
||||
|
||||
shoppingItemRepository.save(item);
|
||||
|
||||
@@ -73,7 +58,9 @@ public class ShoppingItemController {
|
||||
|
||||
@DeleteMapping("/api/items/{itemID}")
|
||||
public ResponseEntity<Void> deleteItem(@PathVariable UUID itemID){
|
||||
shoppingItemRepository.findById(itemID).orElseThrow(() ->new ResourceNotFoundException("itemID",itemID));
|
||||
if(!shoppingItemRepository.existsById(itemID)){
|
||||
return ResponseEntity.notFound().build();
|
||||
}
|
||||
shoppingItemRepository.deleteById(itemID);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
@@ -81,8 +68,7 @@ public class ShoppingItemController {
|
||||
|
||||
@DeleteMapping("/api/lists/{listID}/items")
|
||||
public ResponseEntity<Void> deleteAllDoneItems(@PathVariable UUID listID, @RequestParam boolean done){
|
||||
if(!done) throw new BadRequestException("Parameter \"done\" must be true!");
|
||||
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
if(!done) return ResponseEntity.badRequest().build();
|
||||
|
||||
List<ShoppingItem> items = shoppingItemRepository.findByList_IdAndIsDoneIsTrue(listID);
|
||||
shoppingItemRepository.deleteAll(items);
|
||||
|
||||
@@ -3,22 +3,16 @@ package de.timaldinger.einkaufsliste.Controller;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingListPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingListPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Response.ShoppingListResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
import de.timaldinger.einkaufsliste.Service.ShoppingListService;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import org.springframework.web.server.ResponseStatusException;
|
||||
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
|
||||
|
||||
import java.net.URI;
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@@ -35,31 +29,22 @@ public class ShoppingListController {
|
||||
private ShoppingListService shoppingListService;
|
||||
|
||||
@PostMapping("/api/lists")
|
||||
public ResponseEntity<ShoppingListResponseDTO> addList(@Valid @RequestBody ShoppingListPostDTO newList){
|
||||
public ShoppingListResponseDTO addList(@RequestBody ShoppingListPostDTO newList){
|
||||
ShoppingList list = new ShoppingList(newList.listName(), null, null, 0, 0);
|
||||
|
||||
shoppingListRepository.save(list);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(list.getId())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingListResponseDTO(list.getListName(), list.getId()));
|
||||
return new ShoppingListResponseDTO(list.getListName(), list.getId());
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/lists/{listID}")
|
||||
public ResponseEntity<Void> deleteList(@PathVariable UUID listID){
|
||||
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID",listID));
|
||||
|
||||
shoppingListService.deleteList(listID);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@PatchMapping("/api/lists/{listID}")
|
||||
public ResponseEntity<Void> editList(@PathVariable UUID listID,@Valid @RequestBody ShoppingListPatchDTO toChange){
|
||||
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
public ResponseEntity<Void> editList(@PathVariable UUID listID,@RequestBody ShoppingListPatchDTO toChange){
|
||||
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow();
|
||||
|
||||
if(toChange.newListName() != null) list.setListName(toChange.newListName());
|
||||
|
||||
|
||||
@@ -1,6 +1,4 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingCategoryPatchDTO(@NotBlank(message = "categoryName can't be blank") String categoryName) {
|
||||
public record ShoppingCategoryPatchDTO(String categoryName) {
|
||||
}
|
||||
@@ -1,15 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPatchDTO(String itemName, String itemAmount, Boolean isDone, UUID categoryID) {
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount both cant be blank!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
return n || a || isDone != null || categoryID != null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingListPatchDTO(@NotBlank(message = "listName must not be blank!") String newListName) {
|
||||
public record ShoppingListPatchDTO(String newListName) {
|
||||
}
|
||||
@@ -1,8 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryPostDTO(@NotBlank String categoryName, UUID listID) {
|
||||
public record ShoppingCategoryPostDTO(String categoryName, UUID listID) {
|
||||
}
|
||||
@@ -1,20 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPostDTO(String itemName,
|
||||
String itemAmount,
|
||||
UUID categoryID,
|
||||
@NotNull(message = "listID must not be empty!")
|
||||
UUID listID){
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount cant both be blank!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
return n || a;
|
||||
}
|
||||
public record ShoppingItemPostDTO(String itemName, String itemAmount, UUID categoryID, UUID listID){
|
||||
}
|
||||
@@ -1,6 +1,4 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
public record ShoppingListPostDTO(@NotBlank(message = "listName must not be blank!") String listName) {
|
||||
public record ShoppingListPostDTO(String listName) {
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public class BadRequestException extends RuntimeException {
|
||||
public BadRequestException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
public record ErrorResponse(int status, String msg, String path) {
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import org.jspecify.annotations.Nullable;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.context.support.DefaultMessageSourceResolvable;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.HttpStatusCode;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.context.request.ServletWebRequest;
|
||||
import org.springframework.web.context.request.WebRequest;
|
||||
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {
|
||||
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
|
||||
@ExceptionHandler(BadRequestException.class)
|
||||
public ResponseEntity<ErrorResponse> handleBadRequest(BadRequestException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(new ErrorResponse(400, e.getMessage(), req.getRequestURI()));
|
||||
}
|
||||
@ExceptionHandler(ResourceNotFoundException.class)
|
||||
public ResponseEntity<ErrorResponse> handleResourceNotFound(ResourceNotFoundException e, HttpServletRequest req) {
|
||||
return ResponseEntity.status(HttpStatus.NOT_FOUND)
|
||||
.body(new ErrorResponse(404, e.getMessage(), req.getRequestURI()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
public ResponseEntity<ErrorResponse> handleAll(Exception e, HttpServletRequest req){
|
||||
log.error("{}",req.getRequestURI(), e);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ErrorResponse(500,"Internal error", req.getRequestURI()));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @Nullable ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatusCode statusCode, WebRequest request) {
|
||||
var error = new ErrorResponse(statusCode.value(), ex.getMessage(),((ServletWebRequest) request).getRequest().getRequestURI());
|
||||
return new ResponseEntity<>(error,headers,statusCode);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected @Nullable ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
|
||||
String msg = ex.getBindingResult().getFieldErrors().stream()
|
||||
.map(DefaultMessageSourceResolvable::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
var error = new ErrorResponse(status.value(), msg ,((ServletWebRequest) request).getRequest().getRequestURI());
|
||||
return new ResponseEntity<>(error,headers,status);
|
||||
}
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Exceptions;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public class ResourceNotFoundException extends RuntimeException {
|
||||
public ResourceNotFoundException(String resource, Object value){ super("Resource " + resource + ":"+value.toString()+" not found");}
|
||||
}
|
||||
@@ -16,6 +16,7 @@ import java.util.List;
|
||||
@NoArgsConstructor
|
||||
public class ShoppingCategory extends ShoppingElement{
|
||||
|
||||
@NotBlank
|
||||
private String categoryName;
|
||||
@OneToMany(mappedBy = "category") //eine Liste hat mehrere Kategorien, diese sind mappedBy category (Feld in ShoppingItem) damit keine extra Tabelle erzeugt wird
|
||||
private List<ShoppingItem> itemsInCategory;
|
||||
|
||||
@@ -14,6 +14,7 @@ import lombok.*;
|
||||
@ToString
|
||||
public class ShoppingItem extends ShoppingElement {
|
||||
|
||||
@NotBlank
|
||||
private String itemName;
|
||||
private String itemAmount;
|
||||
private boolean isDone;
|
||||
|
||||
@@ -15,6 +15,7 @@ import java.sql.Date;
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ShoppingList extends ShoppingElement {
|
||||
@NotBlank
|
||||
private String listName;
|
||||
private Date dateCreated;
|
||||
private Date lastChanged;
|
||||
|
||||
@@ -3,5 +3,3 @@ spring.application.name=einkaufsliste
|
||||
spring.datasource.url=jdbc:h2:file:./data/einkaufsliste
|
||||
spring.jpa.hibernate.ddl-auto=update
|
||||
spring.h2.console.enabled=true
|
||||
|
||||
server.error.include-stacktrace=never
|
||||
@@ -6,7 +6,7 @@
|
||||
font-size : 1.5rem;
|
||||
}
|
||||
|
||||
shopping-item[is-checked="true"] .item__text{
|
||||
.item:has(.item__markAsDone:checked) .item__text{
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,58 +1,40 @@
|
||||
export class ShoppingCategory extends HTMLElement {
|
||||
|
||||
static get observedAttributes() { return ["category-name"] }
|
||||
|
||||
constructor() {
|
||||
super();
|
||||
this._rendered = false;
|
||||
export class ShoppingCategory {
|
||||
constructor(categoryName) {
|
||||
this.categoryName = categoryName;
|
||||
this.categoryID = null;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (this._rendered) return;
|
||||
static fromJSON(categoryAsJSON) {
|
||||
const category = new ShoppingCategory(categoryAsJSON.categoryName);
|
||||
category.categoryID = categoryAsJSON.categoryID;
|
||||
return category;
|
||||
}
|
||||
|
||||
render() {
|
||||
const li = document.createElement("li");
|
||||
const categoryHeaderDiv = document.createElement("div");
|
||||
const span = document.createElement("span");
|
||||
const deleteCategoryButton = document.createElement("button");
|
||||
const labelDeleteAllItems = document.createElement("label");
|
||||
const deleteAllItemsCheckbox = document.createElement("input");
|
||||
const ul = document.createElement("ul");
|
||||
const innerUl = document.createElement("ul");
|
||||
li.id = this.categoryID;
|
||||
li.classList.add("category");
|
||||
|
||||
|
||||
categoryHeaderDiv.classList.add("category__div");
|
||||
|
||||
categoryHeaderDiv.classList.add("category__header");
|
||||
|
||||
span.textContent = this.getAttribute("category-name");
|
||||
span.textContent = this.categoryName;
|
||||
span.classList.add("category__name", "category__name--bold", "category__name--big");
|
||||
|
||||
labelDeleteAllItems.classList.add("category__labelDeleteAll");
|
||||
labelDeleteAllItems.textContent = "Gegenstände mit Kategorie löschen?";
|
||||
|
||||
deleteCategoryButton.classList.add("category__deleteButton");
|
||||
deleteCategoryButton.textContent = "Kategorie löschen";
|
||||
|
||||
deleteAllItemsCheckbox.setAttribute("type", "checkbox");
|
||||
|
||||
labelDeleteAllItems.append(deleteAllItemsCheckbox);
|
||||
categoryHeaderDiv.append(span, deleteCategoryButton, deleteAllItemsCheckbox);
|
||||
|
||||
categoryHeaderDiv.append(span, deleteCategoryButton, labelDeleteAllItems);
|
||||
li.append(categoryHeaderDiv, innerUl);
|
||||
|
||||
this.prepend(categoryHeaderDiv);
|
||||
|
||||
if (!this.querySelector("ul")) this.append(ul);
|
||||
|
||||
this._rendered = true;
|
||||
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldVal, newVal) {
|
||||
if (!this._rendered) return;
|
||||
if (newVal == oldVal) return;
|
||||
switch (name) {
|
||||
case "category-name":
|
||||
this.querySelector(".category__name").textContent = newVal;
|
||||
break;
|
||||
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return li;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,55 @@
|
||||
export class ShoppingItem extends HTMLElement {
|
||||
export class ShoppingItem {
|
||||
|
||||
static get observedAttributes() { return ["item-name", "item-amount"] }
|
||||
constructor() {
|
||||
super();
|
||||
this._rendered = false;
|
||||
constructor(itemName, itemAmount) {
|
||||
this.itemName = itemName;
|
||||
this.itemAmount = itemAmount;
|
||||
this.itemID = null;
|
||||
this.isEditing = true;
|
||||
}
|
||||
|
||||
connectedCallback() {
|
||||
if (this._rendered) return;
|
||||
|
||||
console.log(`rendering element shopping-item`);
|
||||
static fromJSON(itemAsJSON) {
|
||||
const item = new ShoppingItem(itemAsJSON.itemName, itemAsJSON.itemAmount);
|
||||
item.itemID = itemAsJSON.itemID;
|
||||
return item;
|
||||
}
|
||||
|
||||
// gibt das darzustellende <li> zurück
|
||||
render() {
|
||||
const li = document.createElement("li");
|
||||
|
||||
const checkboxDone = document.createElement("input");
|
||||
const spanText = document.createElement("span");
|
||||
const span = document.createElement("span");
|
||||
const spanName = document.createElement("span");
|
||||
const spanAmount = document.createElement("span");
|
||||
const buttonDelete = document.createElement("button");
|
||||
|
||||
const deleteItemButton = document.createElement("button");
|
||||
|
||||
li.id = this.itemID;
|
||||
li.classList.add("item");
|
||||
|
||||
checkboxDone.classList.add("item__checkboxDone");
|
||||
checkboxDone.setAttribute("type", "checkbox");
|
||||
checkboxDone.setAttribute("autocomplete", "off");
|
||||
checkboxDone.checked = this.getAttribute("is-checked") === "true";
|
||||
checkboxDone.classList.add("item__markAsDone");
|
||||
|
||||
spanText.classList.add("item__text");
|
||||
span.classList.add("item__text");
|
||||
spanName.classList.add("item__textName");
|
||||
spanAmount.classList.add("item__textAmount");
|
||||
|
||||
spanName.classList.add("item__itemName");
|
||||
spanAmount.classList.add("item__itemAmount");
|
||||
spanName.textContent = this.itemName;
|
||||
spanAmount.textContent = this.itemAmount;
|
||||
|
||||
spanName.textContent = this.getAttribute("item-name");
|
||||
spanAmount.textContent = this.getAttribute("item-amount");
|
||||
deleteItemButton.classList.add("item__deleteButton");
|
||||
deleteItemButton.textContent = "Löschen";
|
||||
|
||||
buttonDelete.classList.add("item__buttonDeleteItem");
|
||||
buttonDelete.setAttribute("type", "button ");
|
||||
buttonDelete.textContent = "Löschen";
|
||||
span.appendChild(spanName);
|
||||
span.appendChild(spanAmount);
|
||||
|
||||
spanText.append(spanName, spanAmount);
|
||||
li.appendChild(checkboxDone)
|
||||
li.appendChild(span);
|
||||
li.appendChild(deleteItemButton);
|
||||
|
||||
this.append(checkboxDone, spanText, buttonDelete);
|
||||
this._rendered = true;
|
||||
|
||||
}
|
||||
|
||||
attributeChangedCallback(name, oldVal, newVal) {
|
||||
if (!this._rendered) return;
|
||||
if (newVal == oldVal) return;
|
||||
switch (name) {
|
||||
case "item-name":
|
||||
this.querySelector(".item__itemName").textContent = newVal;
|
||||
break;
|
||||
case "item-amount":
|
||||
this.querySelector(".item__itemAmount").textContent = newVal;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return li;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
|
||||
|
||||
|
||||
export function addList(listName) {
|
||||
return fetch(`/api/lists`,
|
||||
export async function addList(listName) {
|
||||
const response = await fetch(`/api/lists`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({ listName: listName }),
|
||||
@@ -10,19 +10,24 @@ export function addList(listName) {
|
||||
}
|
||||
);
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
export function deleteList(id) {
|
||||
return fetch(`/api/lists/${id}`, { method: "DELETE" });
|
||||
export async function deleteList(id) {
|
||||
const response = await fetch(`/api/lists/${id}`, { method: "DELETE" });
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
|
||||
|
||||
export function editList(listID, toChange) {
|
||||
return fetch(`/api/lists/${listID}`,
|
||||
export async function editList(listID, toChange) {
|
||||
const response = await fetch(`/api/lists/${listID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
@@ -29,10 +29,9 @@ export function createEditListForm(textElement) {
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
saveButton.classList.add("editForm__saveButton");
|
||||
abortButton.classList.add("editForm__abortButton");
|
||||
|
||||
editForm.append(inputName, saveButton, abortButton);
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
@@ -47,6 +46,5 @@ export function editList(id, formElement, formData, listLi) {
|
||||
listLi.querySelector(".list__name").textContent = newName;
|
||||
listLi.setAttribute("href", `/list/${id}`);
|
||||
formElement.replaceWith(listLi);
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import { initErrors } from "../../shared/error.js";
|
||||
import { handleResponse } from "../../shared/helper.js";
|
||||
import { abortEditing } from "../../shared/sharedUI.js";
|
||||
import { ShoppingList } from "../../models/ShoppingList.js";
|
||||
import * as api from "./api/indexAPI.js";
|
||||
import * as ui from "./frontend/indexUI.js"
|
||||
|
||||
const addListForm = document.querySelector(".addListForm");
|
||||
|
||||
async function addList(listName) {
|
||||
const json = await handleResponse(api.addList(listName), `error creating list`);
|
||||
if (json) ui.addList(json);
|
||||
const listAsJson = await api.addList(listName);
|
||||
console.log(`${listAsJson}`);
|
||||
if (listAsJson) ui.addList(listAsJson);
|
||||
}
|
||||
|
||||
function editList(listLi) {
|
||||
@@ -20,33 +19,36 @@ function editList(listLi) {
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
formElement.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
function save() {
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
const result = await handleResponse(api.editList(id, { newListName: formData.newListName }), `error editing list`);
|
||||
if (result) ui.editList(id, formElement, formData, listLi);
|
||||
ui.editList(id, formElement, formData, listLi);
|
||||
|
||||
console.log(`editing catogory ${id} with ${formData}`)
|
||||
api.editList(id, { newListName: formData.newListName });
|
||||
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
});
|
||||
|
||||
formElement.querySelector(".editForm__abortButton").addEventListener("click", () => {
|
||||
abortEditing(formElement, listLi);
|
||||
})
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") abortEditing(formElement, listLi);
|
||||
if (e.key == "Escape") formElement.replaceWith(listLi);
|
||||
})
|
||||
|
||||
|
||||
}
|
||||
|
||||
async function deleteList(listElement) {
|
||||
const json = await handleResponse(api.deleteList(listElement.dataset.id), `error deleting list`);
|
||||
if (json) ui.deleteList(listElement);
|
||||
|
||||
const response = await api.deleteList(listElement.dataset.id);
|
||||
|
||||
if (response.status == 204) ui.deleteList(listElement);
|
||||
}
|
||||
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
addListForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const formData = Object.fromEntries(new FormData(addListForm));
|
||||
|
||||
@@ -1,21 +1,30 @@
|
||||
export function addCategory(listID, categoryName) {
|
||||
return fetch(`/api/categories`,
|
||||
export async function addCategory(listID, categoryName) {
|
||||
const newCategory = await fetch(`/api/categories`,
|
||||
{
|
||||
method: "POST"
|
||||
, body: JSON.stringify({ "categoryName": categoryName, "listID": listID })
|
||||
, headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
return await newCategory.json();
|
||||
}
|
||||
|
||||
export function editCategory(categoryID, toChange) {
|
||||
return fetch(`/api/categories/${categoryID}`,
|
||||
|
||||
export async function editCategory(categoryID, toChange) {
|
||||
const response = await fetch(`/api/categories/${categoryID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
export function deleteCategory(deleteAllItems, categoryID) {
|
||||
return fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
|
||||
export async function deleteCategory(deleteAllItems, categoryID) {
|
||||
const response = await fetch(`/api/categories/${categoryID}?deleteAllItems=${deleteAllItems}`, { method: "DELETE" });
|
||||
|
||||
if (response.status == 204) {
|
||||
console.log(`deleted item ${categoryID}`);
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
export function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
return fetch(`/api/items`,
|
||||
|
||||
|
||||
export async function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
const newItem = await fetch(`/api/items`,
|
||||
{
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
@@ -10,24 +12,43 @@ export function addItem(listID, itemName, itemAmount, categoryID) {
|
||||
}),
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
|
||||
|
||||
return await newItem.json();
|
||||
}
|
||||
|
||||
export function deleteItem(itemID) {
|
||||
|
||||
return fetch(`/api/items/${itemID}`, { method: "DELETE" });
|
||||
export async function deleteItem(itemID) {
|
||||
|
||||
const response = await fetch(`/api/items/${itemID}`, { method: "DELETE" });
|
||||
|
||||
if (response.status == 204) {
|
||||
console.log(`deleted item ${itemID}`);
|
||||
}
|
||||
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
export function editItem(itemID, toChange) {
|
||||
return fetch(`/api/items/${itemID}`,
|
||||
export async function editItem(itemID, toChange) {
|
||||
const response = await fetch(`/api/items/${itemID}`,
|
||||
{
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(toChange),
|
||||
headers: { "Content-Type": "application/json" }
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
|
||||
export function deleteAllDoneItems(listID) {
|
||||
return fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
|
||||
export async function deleteAllDoneItems(listID) {
|
||||
|
||||
const response = await fetch(`/api/lists/${listID}/items?done=true`, { method: "DELETE" });
|
||||
|
||||
if (response.status == 204) {
|
||||
console.log(`items have been deleted`);
|
||||
}
|
||||
return response;
|
||||
|
||||
}
|
||||
|
||||
@@ -1,30 +1,58 @@
|
||||
|
||||
import { ShoppingCategory } from "../../../models/ShoppingCategory.js";
|
||||
|
||||
export function addCategory(categoryAsJSON) {
|
||||
const list = document.querySelector(".displayedList");
|
||||
const category = document.createElement("shopping-category");
|
||||
const li = document.createElement("li");
|
||||
const category = ShoppingCategory.fromJSON(categoryAsJSON);
|
||||
|
||||
li.classList.add("category");
|
||||
li.dataset.id = categoryAsJSON.categoryID;
|
||||
category.setAttribute("category-name", categoryAsJSON.categoryName);
|
||||
|
||||
li.append(category); //fügt Kategorie der Liste hinzu
|
||||
|
||||
list.append(li);
|
||||
list.appendChild(category.render()); //fügt Kategorie der Liste hinzu
|
||||
|
||||
const categorySelect = document.querySelector(".addItemForm__categorySelect");
|
||||
const newCategoryOption = document.createElement("option");
|
||||
newCategoryOption.setAttribute("value", categoryAsJSON.categoryID);
|
||||
newCategoryOption.textContent = categoryAsJSON.categoryName;
|
||||
newCategoryOption.setAttribute("value", category.categoryID);
|
||||
newCategoryOption.textContent = category.categoryName;
|
||||
|
||||
categorySelect.append(newCategoryOption);
|
||||
categorySelect.appendChild(newCategoryOption);
|
||||
}
|
||||
|
||||
export function deleteCategory(deleteAllItems, categoryID) {
|
||||
const category = document.querySelector(`li[data-id='${categoryID}']`);
|
||||
const category = document.getElementById(categoryID);
|
||||
if (!deleteAllItems) {
|
||||
const ul = category.querySelector("ul");
|
||||
if (ul) document.querySelector(".displayedList").append(...ul.children);
|
||||
}
|
||||
category.remove()
|
||||
document.querySelector(`option[value='${categoryID}']`).remove();
|
||||
|
||||
}
|
||||
|
||||
export function createEditCategoryForm(textElement) {
|
||||
const editForm = document.createElement("form");
|
||||
const inputName = document.createElement("input");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
inputName.setAttribute("name", "newCategoryName");
|
||||
inputName.setAttribute("value", textElement.querySelector(".category__name").textContent);
|
||||
inputName.classList.add("editForm__name");
|
||||
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function editCategory(id, formElement, formData, categoryDiv) {
|
||||
|
||||
let newName = formData.newCategoryName;
|
||||
|
||||
categoryDiv.querySelector(".category__name").textContent = newName;
|
||||
formElement.replaceWith(categoryDiv);
|
||||
|
||||
document.querySelector(`option[value='${id}']`).textContent = newName;
|
||||
|
||||
}
|
||||
@@ -1,21 +1,44 @@
|
||||
import { ShoppingItem } from "../../../models/ShoppingItem.js";
|
||||
|
||||
export function addItem(itemAsJSON) {
|
||||
let list;
|
||||
if (!itemAsJSON.categoryID) {
|
||||
list = document.querySelector(".displayedList");
|
||||
} else {
|
||||
list = document.querySelector(`li[data-id='${itemAsJSON.categoryID}']`).querySelector("ul");
|
||||
list = document.getElementById(`${itemAsJSON.categoryID}`).querySelector("ul");
|
||||
}
|
||||
const li = document.createElement("li");
|
||||
const item = document.createElement("shopping-item");
|
||||
|
||||
li.dataset.id = itemAsJSON.itemID;
|
||||
li.classList.add("item");
|
||||
const item = ShoppingItem.fromJSON(itemAsJSON);
|
||||
|
||||
item.setAttribute("item-name", itemAsJSON.itemName);
|
||||
item.setAttribute("item-amount", itemAsJSON.itemAmount);
|
||||
list.appendChild(item.render());
|
||||
}
|
||||
|
||||
li.append(item);
|
||||
list.append(li);
|
||||
export function createEditItemForm(textElement) {
|
||||
const editForm = document.createElement("form");
|
||||
const inputName = document.createElement("input");
|
||||
const inputAmount = document.createElement("input");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
inputName.setAttribute("name", "newItemName");
|
||||
inputName.setAttribute("value", textElement.querySelector(".item__textName").textContent);
|
||||
inputName.classList.add("editForm__name");
|
||||
|
||||
inputAmount.setAttribute("name", "newItemAmount");
|
||||
inputAmount.setAttribute("value", textElement.querySelector(".item__textAmount").textContent);
|
||||
inputAmount.classList.add("editForm__amount");
|
||||
|
||||
|
||||
abortButton.textContent = "Abbrechen";
|
||||
saveButton.textContent = "Speichern";
|
||||
|
||||
|
||||
editForm.appendChild(inputName);
|
||||
editForm.appendChild(inputAmount);
|
||||
editForm.appendChild(saveButton);
|
||||
editForm.appendChild(abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function deleteItem(li) {
|
||||
|
||||
@@ -1,11 +1,9 @@
|
||||
|
||||
export * from "./itemUI.js";
|
||||
export * from "./categoryUI.js";
|
||||
|
||||
export function deleteAllDoneItems() {
|
||||
const doneItems = document.querySelectorAll("li.item:has(shopping-item[is-checked=true])");
|
||||
const doneItems = document.querySelectorAll("li.item:has(input[type=checkbox]:checked)");
|
||||
doneItems.forEach((li) => {
|
||||
li.remove();
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1,11 +1,6 @@
|
||||
import { ShoppingCategory } from "../../models/ShoppingCategory.js";
|
||||
import { ShoppingItem } from "../../models/ShoppingItem.js";
|
||||
import { initErrors } from "../../shared/error.js";
|
||||
import * as api from "./api/listAPI.js"
|
||||
import * as ui from "./frontend/listUI.js"
|
||||
import { handleResponse } from "../../shared/helper.js";
|
||||
import { editElement } from "../../shared/editing.js";
|
||||
import * as sharedUI from "../../shared/sharedUI.js";
|
||||
|
||||
|
||||
const addCategoryForm = document.querySelector(".addCategoryForm");
|
||||
const addItemForm = document.querySelector(".addItemForm");
|
||||
@@ -13,47 +8,106 @@ const currentList = document.querySelector(".list");
|
||||
const deleteAllDoneItemsButton = document.querySelector(".deleteAllDoneItemsButton");
|
||||
|
||||
async function addItem(itemName, itemAmount, categoryID) {
|
||||
console.log(` adding item with id:${currentList.dataset.id}, name: ${itemName}, amount: ${itemAmount}, category: ${categoryID}`)
|
||||
|
||||
const json = await handleResponse(api.addItem(currentList.dataset.id, itemName, itemAmount, categoryID), `item couldnt be created!`);
|
||||
if (json) ui.addItem(json);
|
||||
console.log(` adding item with id:${currentList.id}, name: ${itemName}, amount: ${itemAmount}, category: ${categoryID}`)
|
||||
const itemAsJSON = await api.addItem(currentList.id, itemName, itemAmount, categoryID);
|
||||
console.log(`rendering frointend item: ${itemAsJSON}`);
|
||||
ui.addItem(itemAsJSON);
|
||||
}
|
||||
|
||||
async function addCategory(categoryName) {
|
||||
console.log(`adding category ${categoryName}`)
|
||||
const categoryAsJSON = await api.addCategory(currentList.id, categoryName);
|
||||
console.log(categoryAsJSON);
|
||||
ui.addCategory(categoryAsJSON);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//textElement ist immer das li mit der id
|
||||
async function editItem(textElement) {
|
||||
|
||||
|
||||
//erstellen das Forms
|
||||
const formElement = ui.createEditItemForm(textElement)
|
||||
let id = textElement.id;
|
||||
|
||||
textElement.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
function save() {
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
|
||||
let newName = formData.newItemName;
|
||||
let newAmount = formData.newItemAmount;
|
||||
textElement.querySelector(".item__textName").textContent = newName;
|
||||
textElement.querySelector(".item__textAmount").textContent = newAmount;
|
||||
formElement.replaceWith(textElement);
|
||||
|
||||
console.log(`editing item ${id} with ${formData}`)
|
||||
api.editItem(id, { itemName: newName, itemAmount: newAmount });
|
||||
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
});
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") formElement.replaceWith(textElement);
|
||||
})
|
||||
|
||||
const json = await handleResponse(api.addCategory(currentList.dataset.id, categoryName), `category couldnt be added!`);
|
||||
if (json) ui.addCategory(json);
|
||||
|
||||
}
|
||||
|
||||
async function deleteItem(li) {
|
||||
console.log(`deleting item ${li.dataset.id}`)
|
||||
async function editCategory(categoryElement) {
|
||||
//erstellen das Forms
|
||||
//wir nutzen für das Element nur das div, weil sonst alle items mitgelöscht werden würden
|
||||
const categoryDiv = categoryElement.querySelector(".category__div");
|
||||
const formElement = ui.createEditCategoryForm(categoryDiv);
|
||||
let id = categoryElement.id;
|
||||
|
||||
const json = await handleResponse(api.deleteItem(li.dataset.id), `error deleting item`);
|
||||
if (json) ui.deleteItem(li);
|
||||
categoryDiv.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector(".editForm__name").focus();
|
||||
|
||||
function save() {
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
ui.editCategory(id, formElement, formData, categoryDiv);
|
||||
|
||||
console.log(`editing catogory ${id} with ${formData}`)
|
||||
api.editCategory(id, { categoryName: formData.newCategoryName });
|
||||
|
||||
}
|
||||
|
||||
formElement.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
save();
|
||||
});
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") formElement.replaceWith(categoryDiv);
|
||||
})
|
||||
}
|
||||
|
||||
async function deleteCategory(deleteAllItems, categoryID) {
|
||||
function deleteItem(li) {
|
||||
api.deleteItem(li.id);
|
||||
ui.deleteItem(li);
|
||||
}
|
||||
|
||||
function deleteCategory(deleteAllItems, categoryID) {
|
||||
console.log(`deleting category with allItems: ${deleteAllItems} id: ${categoryID}`);
|
||||
const json = await handleResponse(api.deleteCategory(deleteAllItems, categoryID), `error deleting category`);
|
||||
|
||||
if (json) ui.deleteCategory(deleteAllItems, categoryID);
|
||||
api.deleteCategory(deleteAllItems, categoryID);
|
||||
ui.deleteCategory(deleteAllItems, categoryID);
|
||||
}
|
||||
|
||||
async function deleteAllDoneItems() {
|
||||
function deleteAllDoneItems() {
|
||||
console.log(`deleting all done items...`)
|
||||
const json = await handleResponse(api.deleteAllDoneItems(currentList.dataset.id), `error deleting all done items`);
|
||||
if (json) ui.deleteAllDoneItems();
|
||||
api.deleteAllDoneItems(currentList.id);
|
||||
ui.deleteAllDoneItems();
|
||||
}
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
|
||||
customElements.define("shopping-item", ShoppingItem);
|
||||
customElements.define("shopping-category", ShoppingCategory);
|
||||
|
||||
addCategoryForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
let formData = Object.fromEntries(new FormData(addCategoryForm));
|
||||
@@ -72,70 +126,31 @@ function init() {
|
||||
|
||||
//event delegation ist schon geil
|
||||
document.querySelector(".displayedList").addEventListener("click", (event) => {
|
||||
if (event.target.matches(".item__buttonDeleteItem")) {
|
||||
if (event.target.matches(".item__deleteButton")) {
|
||||
deleteItem(event.target.closest("li"));
|
||||
|
||||
} else if (event.target.matches(".category__deleteButton")) {
|
||||
|
||||
const li = event.target.closest("li");
|
||||
const checkbox = li.querySelector("input[type=checkbox]");
|
||||
deleteCategory(checkbox.checked, li.dataset.id);
|
||||
deleteCategory(checkbox.checked, li.id);
|
||||
|
||||
} else if (event.target.closest(".item__text")) {
|
||||
|
||||
const shoppingItemElement = event.target.closest("shopping-item");
|
||||
const id = event.target.closest("li").dataset.id;
|
||||
|
||||
let itemName = shoppingItemElement.querySelector(".item__itemName").textContent;
|
||||
let itemAmount = shoppingItemElement.querySelector(".item__itemAmount").textContent;
|
||||
/*
|
||||
* { name: "", value: "", class: "", attr: ""}
|
||||
*/
|
||||
|
||||
editElement({
|
||||
element: shoppingItemElement, apiCall: api.editItem, id: id,
|
||||
fields: [
|
||||
{ name: "itemName", value: itemName, class: "editForm__name", attr: "item-name" },
|
||||
{ name: "itemAmount", value: itemAmount, class: "editForm__amount", attr: "item-amount" }
|
||||
]
|
||||
, onSuccess: (f) => { sharedUI.setElementAttributes(shoppingItemElement, { "item-name": f.itemName, "item-amount": f.itemAmount }) }
|
||||
, errmsg: `konnte Item nicht bearbeiten`
|
||||
});
|
||||
|
||||
editItem(event.target.closest("li"));
|
||||
} else if (event.target.closest(".category__name")) {
|
||||
|
||||
const categoryElement = event.target.closest("shopping-category");
|
||||
const categoryHeader = event.target.closest(".category__header");
|
||||
const id = event.target.closest("li").dataset.id;
|
||||
|
||||
let categoryName = categoryElement.querySelector(".category__name").textContent;
|
||||
|
||||
editElement({
|
||||
element: categoryHeader, apiCall: api.editCategory, id: id,
|
||||
fields: [
|
||||
{ name: "categoryName", value: categoryName, class: "editForm__name", attr: "category-name" },
|
||||
]
|
||||
, onSuccess: (f) => {
|
||||
sharedUI.setElementAttributes(categoryElement, { "category-name": f.categoryName })
|
||||
document.querySelector(`option[value='${id}']`).textContent = f.categoryName;
|
||||
}
|
||||
, errmsg: `konnte Kategorie nicht bearbeiten`
|
||||
});
|
||||
|
||||
editCategory(event.target.closest("li"));
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector(".displayedList").addEventListener("change", (e) => {
|
||||
if (e.target.matches(".item__checkboxDone")) {
|
||||
if (e.target.matches(".item__markAsDone")) {
|
||||
const item = e.target.closest("li");
|
||||
e.target.closest("shopping-item").setAttribute("is-checked", e.target.checked);
|
||||
api.editItem(item.dataset.id, { isDone: e.target.checked });
|
||||
api.editItem(item.id, { isDone: e.target.checked });
|
||||
}
|
||||
});
|
||||
|
||||
console.log("javascript initialized!");
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
@@ -1,29 +0,0 @@
|
||||
import { abortEditing, createEditForm } from "./sharedUI.js";
|
||||
import { handleResponse } from "./helper.js";
|
||||
|
||||
export async function editElement({ element, fields, apiCall, id, onSuccess, errmsg }) {
|
||||
const formElement = createEditForm(fields);
|
||||
|
||||
element.replaceWith(formElement);
|
||||
|
||||
formElement.querySelector("input").focus();
|
||||
|
||||
formElement.addEventListener("submit", async (event) => {
|
||||
event.preventDefault();
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
let result = await handleResponse(apiCall(id, formData), errmsg);
|
||||
|
||||
abortEditing(formElement, element);
|
||||
|
||||
if (result) onSuccess(formData);
|
||||
});
|
||||
|
||||
formElement.addEventListener("click", (e) => {
|
||||
if (e.target.matches(".editForm__buttonAbort")) abortEditing(formElement, element);
|
||||
})
|
||||
|
||||
formElement.addEventListener("keydown", (e) => {
|
||||
if (e.key == "Escape") abortEditing(formElement, element);
|
||||
});
|
||||
}
|
||||
@@ -1,22 +0,0 @@
|
||||
const errorDiv = document.createElement("div");
|
||||
const errorSpan = document.createElement("span");
|
||||
let errorTimer;
|
||||
|
||||
export function showError(msg) {
|
||||
errorSpan.textContent = msg;
|
||||
errorDiv.hidden = false
|
||||
|
||||
clearTimeout(errorTimer);
|
||||
errorTimer = (setTimeout(() => {
|
||||
errorDiv.hidden = true;
|
||||
errorSpan.textContent = "";
|
||||
}, 3000));
|
||||
}
|
||||
|
||||
|
||||
export function initErrors(element) {
|
||||
errorDiv.hidden = true;
|
||||
errorDiv.append(errorSpan);
|
||||
|
||||
element.append(errorDiv);
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import { showError } from "./error.js";
|
||||
|
||||
export async function handleResponse(promise, errorMsg) {
|
||||
const response = await promise;
|
||||
|
||||
//weil 204 kein body ist un damit unparsbar, geben wir vorab true zurück
|
||||
if (response.status == 204) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
showError(json.msg);
|
||||
console.error(errorMsg);
|
||||
return false;
|
||||
}
|
||||
|
||||
return json;
|
||||
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
export function abortEditing(formElement, old) {
|
||||
formElement.replaceWith(old);
|
||||
}
|
||||
|
||||
export function createEditForm(fields) {
|
||||
const editForm = document.createElement("form");
|
||||
const abortButton = document.createElement("button");
|
||||
const saveButton = document.createElement("button");
|
||||
|
||||
const inputs = fields.map(f => {
|
||||
const input = document.createElement("input");
|
||||
input.setAttribute("name", f.name);
|
||||
input.setAttribute("value", f.value);
|
||||
input.classList.add(f.class);
|
||||
return input;
|
||||
});
|
||||
|
||||
abortButton.setAttribute("type", "button");
|
||||
abortButton.classList.add("editForm__buttonAbort");
|
||||
abortButton.textContent = "Abbrechen";
|
||||
|
||||
saveButton.textContent = "Speichern";
|
||||
saveButton.classList.add("editForm__buttonSave");
|
||||
saveButton.setAttribute("type", "submit");
|
||||
|
||||
|
||||
editForm.append(...inputs, saveButton, abortButton);
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
export function setElementAttributes(element, attributes) {
|
||||
|
||||
for (const [attr, val] of Object.entries(attributes)) element.setAttribute(attr, val);
|
||||
|
||||
}
|
||||
@@ -27,7 +27,7 @@
|
||||
<h1 th:text="${list.listName}"></h1>
|
||||
</div>
|
||||
|
||||
<div class="list" th:data-id="${list.id}">
|
||||
<div class="list" th:id="${list.id}">
|
||||
<form class="addCategoryForm">
|
||||
<span>Neue Kategorie hinzufügen:</span>
|
||||
<input type="text" class="addCategoryForm__nameInput" name="categoryName" placeholder="Neue Kategorie hinzufügen...">
|
||||
@@ -52,18 +52,32 @@
|
||||
|
||||
<ul class="displayedList">
|
||||
<!-- Es werden erste alle Kategorien erstellt, jede Kategorie muss ein ul in einem li sein um Verschachtelung zu ermöglichen -->
|
||||
<li th:each="category: ${categories}" th:data-id="${category.id}" class="category">
|
||||
<shopping-category th:attr="category-name=${category.categoryName}">
|
||||
<ul>
|
||||
<li th:each="item: ${category.itemsInCategory}" th:data-id="${item.id}" class="item">
|
||||
<shopping-item th:attr="item-name=${item.itemName}, item-amount=${item.itemAmount}, is-checked=${item.isDone}"></shopping-item>
|
||||
<li th:each="category: ${categories}" th:id="${category.id}" class="category">
|
||||
<div class="category__div">
|
||||
<span class="category__name category__name--big category__name--bold" th:text="${category.categoryName}"></span>
|
||||
<button class="category__deleteButton">Kategorie löschen</button>
|
||||
<input type="checkbox">
|
||||
</div>
|
||||
<!-- Items der Kategorie -->
|
||||
<ul>
|
||||
<li th:each="item: ${category.itemsInCategory}" th:id="${item.id}" class="item"> <!-- erstellung von einem Item -->
|
||||
<input type="checkbox" class="item__markAsDone" th:checked="${item.isDone}" autocomplete="off">
|
||||
<span class="item__text">
|
||||
<span th:text="${item.itemName}" class="item__textName"></span>
|
||||
<span th:text="${item.itemAmount}" class="item__textAmount"></span>
|
||||
</span>
|
||||
<button class="item__deleteButton">Löschen</button>
|
||||
</li>
|
||||
</ul>
|
||||
</shopping-category>
|
||||
</ul>
|
||||
</li>
|
||||
|
||||
<li th:each="item: ${items}" th:data-id="${item.id}" class="item"> <!-- erstellung items ohne Kategorie -->
|
||||
<shopping-item th:attr="item-name=${item.itemName}, item-amount=${item.itemAmount}, is-checked=${item.isDone}"></shopping-item>
|
||||
<li th:each="item: ${items}" th:id="${item.id}" class="item"> <!-- erstellung items ohne Kategorie -->
|
||||
<input type="checkbox" class="item__markAsDone" th:checked="${item.isDone}" autocomplete="off">
|
||||
<span class="item__text">
|
||||
<span th:text="${item.itemName}" class="item__textName"></span>
|
||||
<span th:text="${item.itemAmount}" class="item__textAmount"></span>
|
||||
</span>
|
||||
<button class="item__deleteButton">Löschen</button>
|
||||
</li>
|
||||
</ul>
|
||||
|
||||
|
||||
Reference in new issue
Block a user