Compare commits
84
Commits
37cf02dae5
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aef3ead025 | ||
|
|
9b18eb0f0f | ||
|
|
af63723f3c | ||
|
|
f122372f5d | ||
|
|
d8b5c64cf7 | ||
|
|
1d155c25fd | ||
|
|
a6e77fc107 | ||
|
|
c9132be067 | ||
|
|
bcf735af2f | ||
|
|
5c996a8a77 | ||
|
|
012c8b83a6 | ||
|
|
43588852f4 | ||
|
|
7f74c97c4d | ||
|
|
e611b98a9b | ||
|
|
179ec1206b | ||
|
|
e22cd8c650 | ||
|
|
bb60da6aaa | ||
|
|
af46c19651 | ||
|
|
c551b21701 | ||
|
|
6ae4a1d1f6 | ||
|
|
6508f589b3 | ||
|
|
110e5d415e | ||
|
|
3a1c954023 | ||
|
|
ea6a330fab | ||
|
|
27ebe17be5 | ||
|
|
84bf7b9129 | ||
|
|
d9d511ae29 | ||
|
|
e5dbf649f8 | ||
|
|
1bbff06760 | ||
|
|
8e3c6b8c36 | ||
|
|
57c541bbb7 | ||
|
|
d5389af958 | ||
|
|
ad4a9d12d5 | ||
|
|
3abf47e2ea | ||
|
|
fb5052d43d | ||
|
|
c0cbc5a49c | ||
|
|
16775b45ee | ||
|
|
0ac781114f | ||
|
|
d373ecce2b | ||
|
|
ea8ebf79b2 | ||
|
|
966705ec90 | ||
|
|
4bbc1b73d5 | ||
|
|
4f387d2b7f | ||
|
|
1c1d3f6571 | ||
|
|
7db358721d | ||
|
|
c1bd997e33 | ||
|
|
df20f8c426 | ||
|
|
c0cddc3ef8 | ||
|
|
e8d35385ca | ||
|
|
d4b5382f70 | ||
|
|
75d9591f2d | ||
|
|
3d01278a62 | ||
|
|
f38b8b547f | ||
|
|
083dfa6e7b | ||
|
|
ce55b3b2c8 | ||
|
|
a63ecc4de5 | ||
|
|
433445290c | ||
|
|
a5f0fa9ba3 | ||
|
|
0109a65d0b | ||
|
|
5a1bac447e | ||
|
|
d79be68bed | ||
|
|
719c63862e | ||
|
|
3962a58bc9 | ||
|
|
921d7aef72 | ||
|
|
4b83562e7b | ||
|
|
3b2de4a2e4 | ||
|
|
f2538a39bc | ||
|
|
c20841e475 | ||
|
|
003fba3a49 | ||
|
|
5b6a8e67bf | ||
|
|
569e5223f2 | ||
|
|
ea36b16a87 | ||
|
|
882c4d2707 | ||
|
|
719f633615 | ||
|
|
9f63b689fc | ||
|
|
1c796e4bad | ||
|
|
c8cddd01df | ||
|
|
1afabf80ce | ||
|
|
774212f63a | ||
|
|
3a5064f52f | ||
|
|
0a0a48233e | ||
|
|
3d82b3561d | ||
|
|
90be6ce76e | ||
|
|
b2c741510c |
No files matched your search
@@ -0,0 +1,79 @@
|
||||
# Einkaufsliste
|
||||
|
||||
Repository für das Webapp-Projekt, was eine Einkaufsliste zur Verfügung stellt.
|
||||
Es ist möglich, mehrere Listen anzulegen. In einer Liste kann man
|
||||
Gegenstände und Kategorien erstellen.
|
||||
Gegenständen können, aber müssen nicht Kategorien gehören.
|
||||
|
||||
## Dokumentation
|
||||
|
||||
### Entwicklungsverlauf und User Stories
|
||||
|
||||
Dieses Projekt hat seine Dokumentation über Gitea vorgenommen.
|
||||
Die Entwicklungshistorie ist über die Commitliste einsehbar,
|
||||
User-Stories, Erweiterungen/Änderungen am Projekt und andere
|
||||
Entwicklungsentscheidungen wurden über Issues abgewickelt.
|
||||
Es wurden auch Meilensteine verwendet um die Issues zu organisieren.
|
||||
|
||||
Bugs und Fehler wurden nicht mit Issues dokumentiert, da
|
||||
sie entweder während der Entwicklung auf einem anderen Branch beseitigt worden sind
|
||||
(wenn der Fehler von der Entwicklung des Branches kam) oder spontan gefixt.
|
||||
Die Commits, welche Bugs fixen sind mit `bug:` bzw. `bugfix:`
|
||||
gekennzeichnet und in der Commit-Historie auffindbar.
|
||||
|
||||
## Architektur
|
||||
|
||||
Die Seite verfolgt einen hybriden Ansatz. Das Backend schickt dem Browser eine HTML-Datei,
|
||||
welche in Teilen mit Attributen bei Custom Elementen und Daten befüllt sind.
|
||||
Der Client rendert dann die Custom Elemente.
|
||||
Die Webseite selbst ist so ziemlich im Frontend benutzbar.
|
||||
Ein Neuladen der Seite ist nicht nötig, mit Ausnahme wenn man
|
||||
zwischen Listen und der Listenübersicht wechselt.
|
||||
|
||||
Mehr über die Architektur findet sich unter [`docs/`](docs/DATENMODELL-ARCHITEKTUR.md)
|
||||
|
||||
### Backend
|
||||
|
||||
Für das Backend wurde Spring mit Thymeleaf für das Bereitstellen von Seiten genutzt (`src/main/java/de/timaldinger/einkaufsliste`).
|
||||
Das Backend ist über eine RESTful-API ansprechbar. Die Datenbank ist H2.
|
||||
|
||||
### Frontend
|
||||
|
||||
Für das Frontend wurde Vanilla-JS und CSS benutzt.
|
||||
Hinweis: Kategorien und Gegenstände können bearbeitet werden indem man auf sie drückt!
|
||||
|
||||
## API Übersicht
|
||||
|
||||
| Pfad | Zugelassene Methoden | Angesprochene Modelle |
|
||||
| ----------------- | ------------------------ | --------------------- |
|
||||
| `/api/lists` | GET, POST, DELETE, PATCH | Einkaufslisten |
|
||||
| `/api/categories` | GET, POST, DELETE, PATCH | Kategorien |
|
||||
| `/api/items` | GET, POST, DELETE, PATCH | Gegenstände |
|
||||
|
||||
Die vollständige API-Dokumentation befindet sich unter [`docs/`](/docs/API.md)
|
||||
|
||||
## Aufsetzen
|
||||
|
||||
Auf der Maschine muss Java 25 und Maven installiert sein.
|
||||
|
||||
```
|
||||
# Repo clonen
|
||||
git clone https://gitea.von.timaldinger.de/Technoir/einkaufsliste-web.git
|
||||
# Im Ordner
|
||||
mvn spring-boot:run
|
||||
```
|
||||
|
||||
Nun kann man im Browser `localhost:8080` aufrufen.
|
||||
|
||||
## Sonstiges
|
||||
|
||||
### Weitere Dokumentation
|
||||
|
||||
Weitere Dokumentation befindet sich unter [`docs/`](/docs)
|
||||
|
||||
### Nutzung von KI
|
||||
|
||||
Es wurde Claude Code Opus 4.8 genutzt. Die KI wurde zum Debuggen,
|
||||
bei scheinbar nicht erkennbaren Fehlern, großen Refactors, Hilfe beim Stylen der Seite und als Nachschlagewerk genutzt.
|
||||
Konzept-, Architekturentscheidungen und Umsetzung des Projekts liegen an mir.
|
||||
Vorschläge von KI wurden geprüft und bewusst übernommen oder verworfen.
|
||||
+297
@@ -0,0 +1,297 @@
|
||||
# API
|
||||
|
||||
Die API versucht möglichst RESTful zu sein. Es hat:
|
||||
|
||||
- Ressourcen im Plural
|
||||
- Client-Server Trennung, Änderung der Daten auf der Oberfläche geschieht über `fetch()` an die API
|
||||
- Einheitliche Schnittstelle
|
||||
|
||||
Die Schnittstelle erfolgt vollständig über JSON.
|
||||
|
||||
Es wurde auf Cache-fähigkeit verzichtet aus Zeitgründen. HATEOAS ist auch nicht vorhanden,
|
||||
da Zeitgründe und fragwürdig, ob es für ein Projekt diesen Umfangs nötig ist.
|
||||
|
||||
## API Pfade
|
||||
|
||||
IDs sind im UUID Format
|
||||
|
||||
### Listen `/api/lists`
|
||||
|
||||
| Pfad | Methoden | Beschreibung | Parameter | Codes Erfolg |
|
||||
| ------------ | -------- | --------------------------------------------------- | ----------------------------------------- | ------------ |
|
||||
| `/api/lists` | `GET` | Gibt alle vorhandenen Listen zurück mit Name und ID | / | 200 |
|
||||
| | `POST` | Erlaubt es eine neue Liste zu erstellen | `listName` für den gewünschten Listenname | 201 |
|
||||
|
||||
#### `GET /api/lists` - Alle Listen
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
Leer
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
[
|
||||
{
|
||||
"listName": "Liste 1",
|
||||
"listID": "ddb3ac36-8213-4f9d-bf1e-39c836768e57"
|
||||
},
|
||||
{
|
||||
"listName": "Liste 2",
|
||||
"listID": "8937a2fa-2ab1-4b1e-8ee2-17bb0358dc1f"
|
||||
},
|
||||
...
|
||||
]
|
||||
```
|
||||
|
||||
#### `POST /api/lists` - Erstellen einer Liste
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"listName": "Listenname"
|
||||
}
|
||||
```
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"listName": "Listenname",
|
||||
"listID": "ddb3ac36-8213-4f9d-bf1e-39c836768e57"
|
||||
}
|
||||
```
|
||||
|
||||
### Liste `/api/lists`
|
||||
|
||||
| Pfad | Methoden | Beschreibung | Parameter | Codes Erfolg |
|
||||
| ----------------- | -------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- | ------------ |
|
||||
| `/api/lists/{id}` | GET | Gibt alle Gegenstände und Kategorien (mit ihren Gegenständen) in der Liste mit der UUID id zurück | `id`: UUID der Liste in der URL | 200 |
|
||||
| | PATCH | Verändert den Namen der Liste | `id`: UUID der Liste in der URL. Im Body `listName` für den neuen Namen | 204 |
|
||||
| | DELETE | löscht eine Liste | `id`: UUID Der Liste in der URL | 204 |
|
||||
|
||||
#### GET `/api/lists/{id}` - Inhalt der Liste
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
/
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"categories": [
|
||||
{
|
||||
"categoryName": "testkategorie",
|
||||
"items": [
|
||||
{
|
||||
"status": false,
|
||||
"itemName": "test",
|
||||
"itemAmount": "1",
|
||||
"itemID": "99403d02-4771-4a5a-b6a7-6f3af0a5ee84",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
},
|
||||
{
|
||||
"status": true,
|
||||
"itemName": "test",
|
||||
"itemAmount": "2",
|
||||
"itemID": "fc2806f6-d430-49f8-8c56-a6e2bc9792a7",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
],
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4"
|
||||
}
|
||||
],
|
||||
"itemsNoCategory": [ //Gegenstände ohne Kategorie
|
||||
{
|
||||
"status": false,
|
||||
"itemName": "test",
|
||||
"itemAmount": "3",
|
||||
"itemID": "38a0991e-4b51-42d7-b12c-0ddbcf6f583e",
|
||||
"categoryID": null,
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### `PATCH /api/lists/{id}` - Bearbeiten der Liste
|
||||
|
||||
##### Body
|
||||
|
||||
```json
|
||||
{
|
||||
"listName": "neuer Listname"
|
||||
}
|
||||
```
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
|
||||
#### `DELETE /api/lists/{id}` - Löschen einer Liste
|
||||
|
||||
##### Body
|
||||
|
||||
/
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
|
||||
### Kategorien `/api/categories`
|
||||
|
||||
| Pfad | Methoden | Beschreibung | Parameter | Codes Erfolg |
|
||||
| ---------------------- | -------- | ------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||
| `/api/categories/{id}` | `GET` | Gibt den Inhalt der Kategorie zurück | / | 200 |
|
||||
| | `POST` | Erlaubt es eine neue Kategorie zu erstellen | `categoryName` im Body für den gewünschten Kategorienamen | 201 |
|
||||
| | `PATCH` | Ändern vom Namen der Liste | `categoryName` im Body für neuen Kategorienamen | 204 |
|
||||
| | `DELETE` | Löschen einer Liste | `deleteAllItems=(true\|false)` als Queryparameter. Entscheidet, ob Gegenstände in der Kategorie mitgelöscht werden sollen | 204 |
|
||||
|
||||
#### `GET /api/categories/{id}` - Inhalt der Kategorie
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
/
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"categoryName": "testkategorie",
|
||||
"items": [
|
||||
{
|
||||
"status": false,
|
||||
"itemName": "test",
|
||||
"itemAmount": "1",
|
||||
"itemID": "99403d02-4771-4a5a-b6a7-6f3af0a5ee84",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
],
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4"
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST /api/categories` - Erstellen einer Kategorie
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"categoryName": "testKategorie",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
```
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"categoryName": "testKategorie",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4"
|
||||
}
|
||||
```
|
||||
|
||||
#### `PATCH /api/categories/{id}` - Bearbeiten der Kategorie
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"categoryName": "Gemüse"
|
||||
}
|
||||
```
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
|
||||
#### `DELETE /api/categories/{id}?deleteAllItems=(true|false)`
|
||||
|
||||
##### Body
|
||||
|
||||
/
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
|
||||
### Gegenstände `/api/items`
|
||||
|
||||
| Pfad | Methoden | Beschreibung | Parameter | Codes Erfolg |
|
||||
| ----------------- | -------- | ----------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ------------ |
|
||||
| `/api/items/{id}` | `GET` | Gibt den Inhalt des Gegenstands zurück | / | 200 |
|
||||
| | `POST` | Erlaubt es einen neuen Gegenstand zu erstellen | `itemName,itemAmount,categoryID?,listID` im Body, für den Namen und Menge (entweder beide oder mindst einer muss vorhanden sein). | 201 |
|
||||
| | `PATCH` | Ändern vom Namen, Menge oder Status eines Gegenstands | `itemName, itemAmount, isDone, categoryID` im Body. | 204 |
|
||||
| | `DELETE` | Löschen eines Gegenstands | / | 204 |
|
||||
|
||||
#### `GET /api/items/{id}` - Inhalt des Gegenstands
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
/
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"status": false,
|
||||
"itemName": "Milch",
|
||||
"itemAmount": "1L",
|
||||
"itemID": "38a0991e-4b51-42d7-b12c-0ddbcf6f583e",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST /api/items` - Erstellen eines Gegenstands
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"itemName": "Milch",
|
||||
"itemAmount": "1L",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4",
|
||||
"listID": "9038b8ef-7be8-4dcb-9229-6f51b11be137"
|
||||
}
|
||||
```
|
||||
|
||||
##### Response Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"itemName": "Milch",
|
||||
"itemAmount": "1L",
|
||||
"itemID": "38a0991e-4b51-42d7-b12c-0ddbcf6f583e",
|
||||
"categoryID": "08bedce1-9b25-4fe6-9ede-4d9ee3a904d4"
|
||||
}
|
||||
```
|
||||
|
||||
#### `PATCH /api/items/{id}` - Bearbeiten eines Gegenstands
|
||||
|
||||
##### Body Beispiel
|
||||
|
||||
```json
|
||||
{
|
||||
"isDone": true
|
||||
}
|
||||
```
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
|
||||
#### `DELETE /api/items/{id}` - Löschen eines Gegenstands
|
||||
|
||||
##### Body
|
||||
|
||||
/
|
||||
|
||||
##### Response
|
||||
|
||||
/
|
||||
@@ -0,0 +1,168 @@
|
||||
# Datenmodell und Architektur
|
||||
|
||||
Das Projekt nutzt die Modelle `ShoppingList`, `ShoppingItem` und `ShoppingCategory`.
|
||||
Neben den Spring und Thymeleaf Bibliotheken wurde noch zusätzlich `lombok` genutzt.
|
||||
Lombok stellt Annotationen bereit um Boilerplatecode zu vermeiden.
|
||||
|
||||
## Diagramm
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
ShoppingList ||--o{ ShoppingCategory : hat
|
||||
ShoppingList ||--o{ ShoppingItem : hat
|
||||
ShoppingCategory ||--o{ ShoppingItem : enthält
|
||||
```
|
||||
|
||||
## Modelle
|
||||
|
||||
### ShoppingList
|
||||
|
||||
Eine ShoppingList hat beliebig viele ShoppingCategory und ShoppingItem.
|
||||
Der Name darf nicht leer sein.
|
||||
|
||||
### ShoppingCategory
|
||||
|
||||
Eine ShoppingCategory hat beliebig viele ShoppingItem.
|
||||
Der Name darf nicht leer sein.
|
||||
|
||||
### ShoppingItem
|
||||
|
||||
Ein ShoppingItem hat sowohl einen Namen als auch eine Menge.
|
||||
Der Nutzer hat und sollte die Freiheit haben,
|
||||
die Felder so zu befüllen wie er will.
|
||||
Es findet deshalb keine Eingabevalidierung in dem Sinne statt,
|
||||
dass bei Menge nur Mengeneinheiten stehen dürfen oder im Namen keine Zahlen.
|
||||
Die einzige Anforderung ist es, dass der Nutzer einen der beiden Felder
|
||||
ausfüllen muss.
|
||||
|
||||
## Architektur Backend (`src/main/java/de/timaldinger/einkaufsliste/`)
|
||||
|
||||
### Controller (`Controller/`)
|
||||
|
||||
Hier liegen die Controller welche HTTP-Anfragen abwickeln.
|
||||
`PageController` ist zuständig für das Bereitstellen von den einzelnen Seiten.
|
||||
Die restlichen Controller sind RESTController, welche die API-Schnittstelle
|
||||
behandeln. Sie sind nach der betroffenen Ressource aufgeteilt.
|
||||
|
||||
### Data Transfer Objects (`Dto/`)
|
||||
|
||||
Die Webapp nutzt sogenannte DTOs (Data transfer objects)
|
||||
um die geschickten JSON-Daten auf das Model abzubilden. Diese liegen unter `Dto/`.
|
||||
Dort sind die DTOs nochmal nach den HTTP-Methoden aufgeteilt, da je nach Methode
|
||||
der Nutzer unterschiedliche Daten mitschicken tut.
|
||||
|
||||
### Exceptions (`Exceptions/`)
|
||||
|
||||
Hier liegen benutzerdefinierte Fehlermeldungen, die an das Frontend geschickt werden
|
||||
(hauptsächlich für 400 und 404)
|
||||
und ein eigener Exception Handler `GlobalExceptionHandler.java`.
|
||||
Dieser wurde erstellt damit Fehlermeldungen
|
||||
besser dargestellt werden können und keine Spring-Fehlermeldungen an das Frontend
|
||||
geschickt werden.
|
||||
Er ist mit `@RestControllerAdvice` annotiert, das heißt,
|
||||
dass er für alle anderen Controller gilt. Er greift, wenn ein Fehler von
|
||||
einer Controllerklasse aus propagiert. Er implementiert Methoden annotiert
|
||||
mit `@ExceptionHandler`, welche angibt, für welche Funktion ein geworfener Fehler
|
||||
in einer Funktion des Controllers greift. Es werden in den Controllern die
|
||||
Custom Exceptions geworfen.
|
||||
|
||||
Die CustomException-Klassen erben von `RuntimeException`.
|
||||
|
||||
Das Record `ErrorResponse.java` stellt einen JSON-Body dar um daraus die Fehlermeldung
|
||||
zu bauen die an das Frontend geschickt wird.
|
||||
|
||||
### Mapper (`Mapper/`)
|
||||
|
||||
Klassen, welche die Models aus der Datenbank zu DTOs mappen. Nötig um GET
|
||||
Anfragen zu nutzen.
|
||||
|
||||
### Models (`Models/`)
|
||||
|
||||
Unter `Models/` liegen die Modelle. Die Modelle werden in der Datenbank
|
||||
so abgebildet wie sie in der Klasse definiert sind. Auch sind Relationen
|
||||
der Entities wie sie in der Datenbank seien sollen abgebildet mit
|
||||
Annotationen wie `@ManyToOne`. Es gibt eine abstrakte Klasse `ShoppingElement`,
|
||||
von welcher alle anderen Entities erben. Die Klasse hat eine Variable `id`,
|
||||
welche ihre Unterklassen dann auch haben. Die Klasse selbst wird nicht
|
||||
in der Datenbank abgebildet.
|
||||
|
||||
### Repository (`Repository/`)
|
||||
|
||||
Interfaces, die das JpaRepositories-Interface implementieren. Das JPARep wurde genommen,
|
||||
da man dort Bulkfunktionen wie `saveAll` und `findAll` nutzen kann,
|
||||
Rückgabetypen wie `List` erlaubt sind und diese auch eine `h2`-db
|
||||
Implementierung aufweist.
|
||||
|
||||
### Services (`Service/`)
|
||||
|
||||
Serviceklassen, welche Methoden für die Controller zur Verfügung stellen,
|
||||
um die jeweile HTTP-Request erfüllen zu können. Sie kapseln die Logik von den Controllern.
|
||||
|
||||
### Templating (`src/main/resources/templates`)
|
||||
|
||||
Da die Webapp einen Hybridansatz beim Rendering verfolgt, wurden Thymeleaf-Templates
|
||||
genutzt um die Seite beim Aufrufen bereitzustellen. Die `PageController` Klasse
|
||||
stellt diese bereit.
|
||||
|
||||
## Architektur Frontend (`src/main/resources/static`)
|
||||
|
||||
Genutzt wurde Vanilla-JS und CSS. Das CSS liegt unter `static/css` und das JS unter `static/js`.
|
||||
Jede aufrufbare Seite (`/` und `/list`) hat seinen eigenen Ordner, wo für die Seite
|
||||
spezifische JS Dateien liegen. Hier finden sich zwei Unterordner: `api/` und `frontend/`.
|
||||
Unter jenen Ordner befinden sich Funktionen die jeweils API und UI abwickeln.
|
||||
Die `.js` Datei die in dem Ordnerroot liegt, nutzt und bündelt diese.
|
||||
Die Trennung wurde getätigt um bessere Übersicht und
|
||||
sauberere Entwicklung zu ermöglichen.
|
||||
Unter `shared/` liegen Dateien, die von alle Seiten
|
||||
genutzt werden. Unter Models liegen die Implementierungen der CustomHTML-Elemente.
|
||||
|
||||
### Custom Elemente (`/static/js/models`)
|
||||
|
||||
Im Laufe der Entwicklung wurden CustomHTML Elemente genommen, um die ShoppingList,
|
||||
ShoppingCategory und ShoppingItems darzustellen und besser zu handhaben. Es wurde
|
||||
sich für ein LightDOM Ansatz entschieden, da zum einen die Eventpropagation einfacher
|
||||
zu gestalten ist (EventListener auf `div`) und zum anderen die CSS Klassen greifen.
|
||||
Mit einem Shadow-DOM Ansatz mit zB `templates` wäre das umständlicher.
|
||||
|
||||
### Index Seite (`/static/js/pages/index`)
|
||||
|
||||
Hier liegen nötige Javascriptdateien für die Root Seite `/`.
|
||||
Unter `/api` liegen die API Methoden, unter `/frontend` UI Methoden
|
||||
|
||||
### List Seite (`static/js/pages/list`)
|
||||
|
||||
Hier liegen nötige Javascriptdateien für die Seite `/list/{id}`.
|
||||
Unter `/api` liegen die API Methoden, unter `/frontend` UI Methoden.
|
||||
Da die Seite sowohl Kategorien als auch Gegenstände
|
||||
behandelt sind in den Ordnern jeweils API und UI Dateien für die beiden Elemente.
|
||||
Die Imports sind dann in den jeweilen `listUI.js` und `listAPI.js` gebündelt
|
||||
welche dann in die `list.js` importiert wird.
|
||||
|
||||
### Shared Module (`static/js/shared`)
|
||||
|
||||
#### editing.js
|
||||
|
||||
Hier liegt die Logik, welche genutzt wird um eines
|
||||
der Elemente (Liste, Kategorie, Gegenstand) zu bearbeiten.
|
||||
Zusammen mit `sharedUI.js` bildet sie den Ablauf ab.
|
||||
Die beiden Dateien sind bewusst getrennt,
|
||||
da die Funktion `editElement()` eine Mischung aus UI und API Aufrufe hat.
|
||||
Das Muster, dass API und UI Funktionen in getrennten Dateien leben,
|
||||
sollte beibehalten werden. Es wurde nur die editElement() Funktion
|
||||
generalisiert, da die Bearbeitung eines Elementes für alle drei Models
|
||||
gleich abläuft im Gegensatz zu dem Hinzufügen und Löschen dieser.
|
||||
|
||||
#### error.js
|
||||
|
||||
Globale Fehlermeldungsdarstellung. Eine Clientseitige Validierung findet
|
||||
nicht statt, da sie serverseitig behandelt werden.
|
||||
|
||||
#### helper.js
|
||||
|
||||
Hilfsfunktion für das Abwickeln von `fetch()` Anfragen.
|
||||
Zur Vereinheitlichung der Funktionen die API calls nutzen.
|
||||
|
||||
#### sharedUI.js
|
||||
|
||||
Stellt UI-Funktionen bereit, die alle Seiten nutzen. Momentan nur für
|
||||
Bearbeitung der Elemente.
|
||||
+18
-55
@@ -1,89 +1,52 @@
|
||||
package de.timaldinger.einkaufsliste.Controller;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingCategoryPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingCategoryGetDTO;
|
||||
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 de.timaldinger.einkaufsliste.Dto.Post.ShoppingCategoryPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.Response.ShoppingCategoryPostResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Service.ShoppingCategoryService;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
public class ShoppingCategoryController {
|
||||
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
@Autowired
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
private ShoppingCategoryService shoppingCategoryService;
|
||||
|
||||
@GetMapping("/api/categories/{categoryID}")
|
||||
public ResponseEntity<ShoppingCategoryGetDTO> getCategory(@PathVariable UUID categoryID){
|
||||
return ResponseEntity.ok().body(shoppingCategoryService.getCategory(categoryID));
|
||||
}
|
||||
|
||||
@PostMapping("/api/categories")
|
||||
public ResponseEntity<ShoppingCategoryResponseDTO> addCategory(@Valid @RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
|
||||
String name = newCategory.categoryName();
|
||||
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow(() -> new ResourceNotFoundException("listID",newCategory.listID()));
|
||||
|
||||
ShoppingCategory category = new ShoppingCategory(name, List.of(),list);
|
||||
|
||||
shoppingCategoryRepository.save(category);
|
||||
public ResponseEntity<ShoppingCategoryPostResponseDTO> addCategory(@Valid @RequestBody ShoppingCategoryPostDTO newCategory){
|
||||
ShoppingCategoryPostResponseDTO created = shoppingCategoryService.addCategory(newCategory);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(category.getId())
|
||||
.buildAndExpand(created.categoryID())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingCategoryResponseDTO(name, category.getId()));
|
||||
return ResponseEntity.created(location).body(created);
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
if(toChange.categoryName() != null) category.setCategoryName(toChange.categoryName());
|
||||
|
||||
shoppingCategoryRepository.save(category);
|
||||
|
||||
public ResponseEntity<Void> editCategory(@PathVariable UUID categoryID, @Valid @RequestBody ShoppingCategoryPatchDTO toChange){
|
||||
shoppingCategoryService.editCategory(categoryID, toChange);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
@DeleteMapping("/api/categories/{categoryID}")
|
||||
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)");
|
||||
}
|
||||
|
||||
shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID", categoryID));
|
||||
|
||||
List<ShoppingItem> itemList = shoppingItemRepository.findAllByCategory_Id(categoryID);
|
||||
if(deleteAllItems){
|
||||
itemList.forEach((item) -> shoppingItemRepository.deleteById(item.getId()));
|
||||
}else{
|
||||
itemList.forEach((item) -> item.setCategory(null));
|
||||
shoppingItemRepository.saveAll(itemList);
|
||||
}
|
||||
|
||||
shoppingCategoryRepository.deleteById(categoryID);
|
||||
|
||||
shoppingCategoryService.deleteCategory(categoryID, deleteAllItems);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
@@ -1,92 +1,58 @@
|
||||
package de.timaldinger.einkaufsliste.Controller;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingItemPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingItemGetDTO;
|
||||
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 de.timaldinger.einkaufsliste.Dto.Post.ShoppingItemPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.Response.ShoppingItemPostResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Service.ShoppingItemService;
|
||||
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;
|
||||
|
||||
@RestController
|
||||
public class ShoppingItemController {
|
||||
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
@Autowired
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
private ShoppingItemService shoppingItemService;
|
||||
|
||||
@GetMapping("/api/items/{itemID}")
|
||||
public ResponseEntity<ShoppingItemGetDTO> getItem(@PathVariable UUID itemID){
|
||||
return ResponseEntity.ok().body(shoppingItemService.getItem(itemID));
|
||||
}
|
||||
|
||||
@PostMapping("/api/items")
|
||||
public ResponseEntity<ShoppingItemResponseDTO> addItem(@Valid @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()));
|
||||
}else{
|
||||
c = null;
|
||||
}
|
||||
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow(() -> new ResourceNotFoundException("listID", newItem.listID()));
|
||||
|
||||
ShoppingItem item = new ShoppingItem(name, amount, false, c, list);
|
||||
shoppingItemRepository.save(item);
|
||||
public ResponseEntity<ShoppingItemPostResponseDTO> addItem(@Valid @RequestBody ShoppingItemPostDTO newItem){
|
||||
ShoppingItemPostResponseDTO created = shoppingItemService.addItem(newItem);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(item.getId())
|
||||
.buildAndExpand(created.itemID())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingItemResponseDTO(name,amount,item.getId(),c != null ? c.getId() : null));
|
||||
return ResponseEntity.created(location).body(created);
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
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())));
|
||||
|
||||
shoppingItemRepository.save(item);
|
||||
|
||||
public ResponseEntity<Void> editItem(@PathVariable UUID itemID, @Valid @RequestBody ShoppingItemPatchDTO toChange){
|
||||
shoppingItemService.editItem(itemID, toChange);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
@DeleteMapping("/api/items/{itemID}")
|
||||
public ResponseEntity<Void> deleteItem(@PathVariable UUID itemID){
|
||||
shoppingItemRepository.findById(itemID).orElseThrow(() ->new ResourceNotFoundException("itemID",itemID));
|
||||
shoppingItemRepository.deleteById(itemID);
|
||||
shoppingItemService.deleteItem(itemID);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
|
||||
|
||||
@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));
|
||||
|
||||
List<ShoppingItem> items = shoppingItemRepository.findByList_IdAndIsDoneIsTrue(listID);
|
||||
shoppingItemRepository.deleteAll(items);
|
||||
|
||||
shoppingItemService.deleteAllDoneItems(listID, done);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -1,21 +1,15 @@
|
||||
package de.timaldinger.einkaufsliste.Controller;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingListGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingListsGetDTO;
|
||||
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.Dto.Post.Response.ShoppingListPostResponseDTO;
|
||||
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;
|
||||
@@ -25,46 +19,41 @@ import java.util.UUID;
|
||||
@RestController
|
||||
public class ShoppingListController {
|
||||
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
@Autowired
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
@Autowired
|
||||
private ShoppingListService shoppingListService;
|
||||
|
||||
@PostMapping("/api/lists")
|
||||
public ResponseEntity<ShoppingListResponseDTO> addList(@Valid @RequestBody ShoppingListPostDTO newList){
|
||||
ShoppingList list = new ShoppingList(newList.listName(), null, null, 0, 0);
|
||||
@GetMapping("/api/lists")
|
||||
public ResponseEntity<List<ShoppingListsGetDTO>> getLists(){
|
||||
return ResponseEntity.ok().body(shoppingListService.getLists());
|
||||
}
|
||||
|
||||
shoppingListRepository.save(list);
|
||||
@GetMapping("/api/lists/{listID}")
|
||||
public ResponseEntity<ShoppingListGetDTO> getList(@PathVariable UUID listID){
|
||||
return ResponseEntity.ok().body(shoppingListService.getList(listID));
|
||||
}
|
||||
|
||||
@PostMapping("/api/lists")
|
||||
public ResponseEntity<ShoppingListPostResponseDTO> addList(@Valid @RequestBody ShoppingListPostDTO newList){
|
||||
ShoppingListPostResponseDTO created = shoppingListService.addList(newList);
|
||||
|
||||
URI location = ServletUriComponentsBuilder
|
||||
.fromCurrentRequest()
|
||||
.path("/{id}")
|
||||
.buildAndExpand(list.getId())
|
||||
.buildAndExpand(created.listID())
|
||||
.toUri();
|
||||
|
||||
return ResponseEntity.created(location).body(new ShoppingListResponseDTO(list.getListName(), list.getId()));
|
||||
return ResponseEntity.created(location).body(created);
|
||||
}
|
||||
|
||||
@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));
|
||||
|
||||
if(toChange.listName() != null) list.setListName(toChange.listName());
|
||||
|
||||
shoppingListRepository.save(list);
|
||||
|
||||
public ResponseEntity<Void> editList(@PathVariable UUID listID, @Valid @RequestBody ShoppingListPatchDTO toChange){
|
||||
shoppingListService.editList(listID, toChange);
|
||||
return ResponseEntity.noContent().build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Get;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryGetDTO(String categoryName, List<ShoppingItemGetDTO> items, UUID categoryID) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Get;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemGetDTO(boolean status, String itemName, String itemAmount, UUID itemID, UUID categoryID, UUID listID) {
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Get;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record ShoppingListGetDTO(List<ShoppingCategoryGetDTO> categories, List<ShoppingItemGetDTO> itemsNoCategory) {
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Get;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingListsGetDTO(String listName, UUID listID){
|
||||
|
||||
}
|
||||
@@ -1,6 +1,9 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record ShoppingCategoryPatchDTO(@NotBlank(message = "categoryName can't be blank") String categoryName) {
|
||||
public record ShoppingCategoryPatchDTO(@NotBlank(message = "Kategoriename darf nicht leer sein!")
|
||||
@Size(max = 50, message = "Kategoriename darf nicht länger als 50 Zeichen sein!")
|
||||
String categoryName) {
|
||||
}
|
||||
@@ -1,12 +1,15 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPatchDTO(String itemName, String itemAmount, Boolean isDone, UUID categoryID) {
|
||||
public record ShoppingItemPatchDTO(@Size(max = 50, message = "Name darf nicht länger als 50 Zeichen sein!") String itemName,
|
||||
@Size(max = 50, message = "Menge darf nicht länger als 50 Zeichen sein!") String itemAmount,
|
||||
Boolean isDone, UUID categoryID) {
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount both cant be blank!")
|
||||
@AssertTrue(message = "Wenigstens eines der Felder muss ausgefüllt sein!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Patch;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record ShoppingListPatchDTO(@NotBlank(message = "listName must not be blank!") String listName) {
|
||||
public record ShoppingListPatchDTO(@NotBlank(message = "Listenname darf nicht leer sein!")
|
||||
@Size(max = 50, message = "Listenname darf nicht länger als 50 Zeichen sein!")
|
||||
String listName) {
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryPostResponseDTO(String categoryName, UUID categoryID){
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPostResponseDTO(String itemName, String itemAmount, UUID itemID, UUID categoryID) {
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingListPostResponseDTO(String listName, UUID listID){
|
||||
}
|
||||
@@ -1,8 +1,11 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryPostDTO(@NotBlank String categoryName, UUID listID) {
|
||||
public record ShoppingCategoryPostDTO(@NotBlank(message = "Kategoriename darf nicht leer sein!")
|
||||
@Size(max = 50, message = "Kategoriename darf nicht länger als 50 Zeichen sein!")
|
||||
String categoryName, UUID listID) {
|
||||
}
|
||||
@@ -2,16 +2,19 @@ package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.AssertTrue;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemPostDTO(String itemName,
|
||||
String itemAmount,
|
||||
UUID categoryID,
|
||||
@NotNull(message = "listID must not be empty!")
|
||||
UUID listID){
|
||||
public record ShoppingItemPostDTO( @Size(max = 50, message = "Kategoriename darf nicht länger als 50 Zeichen sein!")
|
||||
String itemName,
|
||||
@Size(max = 50, message = "Kategoriename darf nicht länger als 50 Zeichen sein!")
|
||||
String itemAmount,
|
||||
UUID categoryID,
|
||||
@NotNull(message = "listID must not be empty!")
|
||||
UUID listID){
|
||||
|
||||
@AssertTrue(message = "itemName and itemAmount cant both be blank!")
|
||||
@AssertTrue(message = "Wenigstens eines der Felder muss ausgefüllt sein!")
|
||||
private boolean isAtleastOneNotBlank(){
|
||||
boolean n = itemName != null && !itemName.isBlank();
|
||||
boolean a = itemAmount != null && !itemAmount.isBlank();
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Post;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.Size;
|
||||
|
||||
public record ShoppingListPostDTO(@NotBlank(message = "listName must not be blank!") String listName) {
|
||||
public record ShoppingListPostDTO(@NotBlank(message = "Listenname darf nicht leer sein!")
|
||||
@Size(max = 50, message = "Listenname darf nicht länger als 50 Zeichen sein!")
|
||||
String listName) {
|
||||
}
|
||||
-6
@@ -1,6 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingCategoryResponseDTO (String categoryName, UUID categoryID){
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingItemResponseDTO(String itemName, String itemAmount, UUID itemID, UUID categoryID) {
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
package de.timaldinger.einkaufsliste.Dto.Response;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
public record ShoppingListResponseDTO (String listName, UUID listID){
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package de.timaldinger.einkaufsliste.Mapper;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingCategoryGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingCategory;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class ShoppingCategoryMapper {
|
||||
|
||||
@Autowired
|
||||
ShoppingItemMapper shoppingItemMapper;
|
||||
|
||||
public ShoppingCategoryGetDTO toGetDTO(ShoppingCategory category){
|
||||
return new ShoppingCategoryGetDTO(
|
||||
category.getCategoryName(),
|
||||
shoppingItemMapper.toGetDTOs(category.getItemsInCategory()),
|
||||
category.getId()
|
||||
);
|
||||
}
|
||||
|
||||
public List<ShoppingCategoryGetDTO> toGetDTOs(List<ShoppingCategory> categories){
|
||||
return categories.stream().map(this::toGetDTO).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package de.timaldinger.einkaufsliste.Mapper;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingItemGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingItem;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class ShoppingItemMapper {
|
||||
public ShoppingItemGetDTO toGetDTO(ShoppingItem item){
|
||||
return new ShoppingItemGetDTO(
|
||||
item.isDone(),
|
||||
item.getItemName(),
|
||||
item.getItemAmount(),
|
||||
item.getId(),
|
||||
item.getCategory() != null ? item.getCategory().getId() : null,
|
||||
item.getList().getId()
|
||||
);
|
||||
}
|
||||
|
||||
public List<ShoppingItemGetDTO> toGetDTOs(List<ShoppingItem> items){
|
||||
return items.stream().map(this::toGetDTO).toList();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package de.timaldinger.einkaufsliste.Mapper;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingListsGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Component
|
||||
public class ShoppingListMapper {
|
||||
|
||||
public List<ShoppingListsGetDTO> toListsGetDTOs(List<ShoppingList> list){
|
||||
return list.stream().map(this::toListsGetDTO).toList();
|
||||
}
|
||||
|
||||
public ShoppingListsGetDTO toListsGetDTO(ShoppingList list){
|
||||
return new ShoppingListsGetDTO(
|
||||
list.getListName(),
|
||||
list.getId()
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -16,8 +16,4 @@ import java.sql.Date;
|
||||
@NoArgsConstructor
|
||||
public class ShoppingList extends ShoppingElement {
|
||||
private String listName;
|
||||
private Date dateCreated;
|
||||
private Date lastChanged;
|
||||
private int numberItems;
|
||||
private int numberCategory;
|
||||
}
|
||||
@@ -12,7 +12,10 @@ import java.util.UUID;
|
||||
|
||||
public interface ShoppingCategoryRepository extends JpaRepository<ShoppingCategory, UUID>{
|
||||
List<ShoppingCategory> findByList(ShoppingList list);
|
||||
List<ShoppingCategory> findByList_Id(UUID listID);
|
||||
@Modifying
|
||||
@Query("DELETE FROM ShoppingCategory c WHERE c.list.id = :listID")
|
||||
void deleteByListId(@Param("listID") UUID listID);
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package de.timaldinger.einkaufsliste.Service;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingCategoryGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingCategoryPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingCategoryPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.Response.ShoppingCategoryPostResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Mapper.ShoppingCategoryMapper;
|
||||
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.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class ShoppingCategoryService {
|
||||
|
||||
@Autowired
|
||||
private ShoppingCategoryMapper shoppingCategoryMapper;
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
@Autowired
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
|
||||
public ShoppingCategoryGetDTO getCategory(UUID categoryID){
|
||||
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID", categoryID));
|
||||
return shoppingCategoryMapper.toGetDTO(category);
|
||||
}
|
||||
|
||||
public ShoppingCategoryPostResponseDTO addCategory(ShoppingCategoryPostDTO newCategory){
|
||||
ShoppingList list = shoppingListRepository.findById(newCategory.listID()).orElseThrow(() -> new ResourceNotFoundException("listID", newCategory.listID()));
|
||||
|
||||
ShoppingCategory category = new ShoppingCategory(newCategory.categoryName(), List.of(), list);
|
||||
shoppingCategoryRepository.save(category);
|
||||
|
||||
return new ShoppingCategoryPostResponseDTO(category.getCategoryName(), category.getId());
|
||||
}
|
||||
|
||||
public void editCategory(UUID categoryID, ShoppingCategoryPatchDTO toChange){
|
||||
ShoppingCategory category = shoppingCategoryRepository.findById(categoryID).orElseThrow(() -> new ResourceNotFoundException("categoryID", categoryID));
|
||||
|
||||
if(toChange.categoryName() != null) category.setCategoryName(toChange.categoryName());
|
||||
|
||||
shoppingCategoryRepository.save(category);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteCategory(UUID categoryID, Boolean deleteAllItems){
|
||||
if(deleteAllItems == null){
|
||||
throw new BadRequestException("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()));
|
||||
}else{
|
||||
itemList.forEach((item) -> item.setCategory(null));
|
||||
shoppingItemRepository.saveAll(itemList);
|
||||
}
|
||||
|
||||
shoppingCategoryRepository.deleteById(categoryID);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package de.timaldinger.einkaufsliste.Service;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.ShoppingItemGetDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingItemPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingItemPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.Response.ShoppingItemPostResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.BadRequestException;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Mapper.ShoppingItemMapper;
|
||||
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 org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
public class ShoppingItemService {
|
||||
|
||||
@Autowired
|
||||
private ShoppingItemMapper shoppingItemMapper;
|
||||
@Autowired
|
||||
private ShoppingItemRepository shoppingItemRepository;
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
|
||||
public ShoppingItemGetDTO getItem(UUID itemID){
|
||||
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID", itemID));
|
||||
return shoppingItemMapper.toGetDTO(item);
|
||||
}
|
||||
|
||||
public ShoppingItemPostResponseDTO addItem(ShoppingItemPostDTO newItem){
|
||||
ShoppingCategory category = null;
|
||||
if(newItem.categoryID() != null){
|
||||
category = shoppingCategoryRepository.findById(newItem.categoryID()).orElseThrow(() -> new ResourceNotFoundException("categoryID", newItem.categoryID()));
|
||||
}
|
||||
ShoppingList list = shoppingListRepository.findById(newItem.listID()).orElseThrow(() -> new ResourceNotFoundException("listID", newItem.listID()));
|
||||
|
||||
ShoppingItem item = new ShoppingItem(newItem.itemName(), newItem.itemAmount(), false, category, list);
|
||||
shoppingItemRepository.save(item);
|
||||
|
||||
return new ShoppingItemPostResponseDTO(item.getItemName(), item.getItemAmount(), item.getId(), category != null ? category.getId() : null);
|
||||
}
|
||||
|
||||
public void editItem(UUID itemID, ShoppingItemPatchDTO toChange){
|
||||
ShoppingItem item = shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID", itemID));
|
||||
|
||||
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())));
|
||||
|
||||
shoppingItemRepository.save(item);
|
||||
}
|
||||
|
||||
public void deleteItem(UUID itemID){
|
||||
shoppingItemRepository.findById(itemID).orElseThrow(() -> new ResourceNotFoundException("itemID", itemID));
|
||||
shoppingItemRepository.deleteById(itemID);
|
||||
}
|
||||
|
||||
public void deleteAllDoneItems(UUID listID, boolean done){
|
||||
if(!done) throw new BadRequestException("Parameter \"done\" must be true!");
|
||||
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
|
||||
List<ShoppingItem> items = shoppingItemRepository.findByList_IdAndIsDoneIsTrue(listID);
|
||||
shoppingItemRepository.deleteAll(items);
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,14 @@
|
||||
package de.timaldinger.einkaufsliste.Service;
|
||||
|
||||
import de.timaldinger.einkaufsliste.Dto.Get.*;
|
||||
import de.timaldinger.einkaufsliste.Dto.Patch.ShoppingListPatchDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.ShoppingListPostDTO;
|
||||
import de.timaldinger.einkaufsliste.Dto.Post.Response.ShoppingListPostResponseDTO;
|
||||
import de.timaldinger.einkaufsliste.Exceptions.ResourceNotFoundException;
|
||||
import de.timaldinger.einkaufsliste.Mapper.ShoppingCategoryMapper;
|
||||
import de.timaldinger.einkaufsliste.Mapper.ShoppingItemMapper;
|
||||
import de.timaldinger.einkaufsliste.Mapper.ShoppingListMapper;
|
||||
import de.timaldinger.einkaufsliste.Models.ShoppingList;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingCategoryRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingItemRepository;
|
||||
import de.timaldinger.einkaufsliste.Repository.ShoppingListRepository;
|
||||
@@ -7,6 +16,7 @@ import jakarta.transaction.Transactional;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.UUID;
|
||||
|
||||
@Service
|
||||
@@ -17,9 +27,44 @@ public class ShoppingListService {
|
||||
private ShoppingListRepository shoppingListRepository;
|
||||
@Autowired
|
||||
private ShoppingCategoryRepository shoppingCategoryRepository;
|
||||
@Autowired
|
||||
private ShoppingCategoryMapper shoppingCategoryMapper;
|
||||
@Autowired
|
||||
private ShoppingItemMapper shoppingItemMapper;
|
||||
@Autowired
|
||||
private ShoppingListMapper shoppingListMapper;
|
||||
|
||||
public List<ShoppingListsGetDTO> getLists(){
|
||||
return shoppingListMapper.toListsGetDTOs(shoppingListRepository.findAll());
|
||||
}
|
||||
|
||||
public ShoppingListGetDTO getList(UUID listID){
|
||||
ShoppingList l = shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
|
||||
List<ShoppingCategoryGetDTO> categories = shoppingCategoryMapper.toGetDTOs(shoppingCategoryRepository.findByList(l));
|
||||
List<ShoppingItemGetDTO> items = shoppingItemMapper.toGetDTOs(shoppingItemRepository.findByList_IdAndCategoryIsNull(listID));
|
||||
|
||||
return new ShoppingListGetDTO(categories, items);
|
||||
}
|
||||
|
||||
public ShoppingListPostResponseDTO addList(ShoppingListPostDTO newList){
|
||||
ShoppingList list = new ShoppingList(newList.listName());
|
||||
shoppingListRepository.save(list);
|
||||
return new ShoppingListPostResponseDTO(list.getListName(), list.getId());
|
||||
}
|
||||
|
||||
public void editList(UUID listID, ShoppingListPatchDTO toChange){
|
||||
ShoppingList list = shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
|
||||
if(toChange.listName() != null) list.setListName(toChange.listName());
|
||||
|
||||
shoppingListRepository.save(list);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void deleteList(UUID listID){
|
||||
shoppingListRepository.findById(listID).orElseThrow(() -> new ResourceNotFoundException("listID", listID));
|
||||
|
||||
shoppingItemRepository.deleteByListId(listID);
|
||||
shoppingCategoryRepository.deleteByListId(listID);
|
||||
shoppingListRepository.deleteById(listID);
|
||||
|
||||
@@ -1,28 +1,144 @@
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
.nav__dropdown {
|
||||
position: relative;
|
||||
:root {
|
||||
/* Akzent (teal) */
|
||||
--c-accent: #0f766e;
|
||||
--c-accent-hover: #134e4a;
|
||||
--c-accent-soft: #f0fdfa;
|
||||
|
||||
/* Spacing-Skala */
|
||||
--space-1: .25rem; /* 4px */
|
||||
--space-2: .5rem; /* 8px */
|
||||
--space-3: 1rem; /* 16px */
|
||||
--space-4: 1.5rem; /* 24px */
|
||||
--space-5: 2rem; /* 32px */
|
||||
--space-6: 3rem; /* 48px */
|
||||
|
||||
/* Neutrale (zinc) */
|
||||
--c-bg: #ffffff;
|
||||
--c-surface: #fafafa;
|
||||
--c-border: #e4e4e7;
|
||||
--c-muted: #71717a;
|
||||
--c-text: #18181b;
|
||||
|
||||
--c-danger: #dc2626;
|
||||
|
||||
--radius: 6px;
|
||||
--maxw: 640px;
|
||||
--shadow: 0 4px 12px rgb(0 0 0 / .12);
|
||||
}
|
||||
|
||||
.nav__dropdownMenu {
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
body {
|
||||
font-family: system-ui, sans-serif;
|
||||
color: var(--c-text);
|
||||
background-color: var(--c-bg);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.nav__dropdown:hover .nav__dropdownMenu,
|
||||
.nav__dropdown.is-open .nav__dropdownMenu{
|
||||
display: block;
|
||||
|
||||
.index, .title, .nav, body > .list {
|
||||
max-width: var(--maxw);
|
||||
margin-inline: auto;
|
||||
padding: var(--space-3);
|
||||
}
|
||||
|
||||
.nav > ul {
|
||||
/* ---- Links ---- */
|
||||
a, a:link, a:visited { color: var(--c-text); }
|
||||
|
||||
/* ---- Formular-Elemente ---- */
|
||||
|
||||
input:not([type="checkbox"]):not([type="radio"]), select {
|
||||
font: inherit;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid var(--c-border);
|
||||
border-radius: var(--radius);
|
||||
background: var(--c-bg);
|
||||
color: var(--c-text);
|
||||
}
|
||||
input::placeholder { color: var(--c-muted); }
|
||||
|
||||
input.is-invalid:not([type="checkbox"]):not([type="radio"]),
|
||||
input:user-invalid:not([type="checkbox"]):not([type="radio"]),
|
||||
select.is-invalid {
|
||||
border-color: var(--c-danger);
|
||||
}
|
||||
|
||||
.is-invalid:focus-visible {
|
||||
outline-color: var(--c-danger);
|
||||
}
|
||||
|
||||
button {
|
||||
font: inherit;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius);
|
||||
background: var(--c-accent);
|
||||
color: #fff;
|
||||
cursor: pointer;
|
||||
}
|
||||
button:hover { background: var(--c-accent-hover); }
|
||||
|
||||
:focus-visible {
|
||||
outline: 2px solid var(--c-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
|
||||
/* ---- Bearbeitung ---- */
|
||||
.error-message{
|
||||
flex-basis: 100%;
|
||||
font-size: .75rem;
|
||||
color: var(--c-danger);
|
||||
}
|
||||
|
||||
.editForm {
|
||||
display: flex;
|
||||
gap: 1rem;
|
||||
list-style: none;
|
||||
margin: 1;
|
||||
padding: 1;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
align-items: center;
|
||||
margin: var(--space-1);
|
||||
}
|
||||
|
||||
|
||||
/* ---- Navigation ---- */
|
||||
.nav { border-bottom: 1px solid var(--c-border); }
|
||||
.nav__links {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
}
|
||||
.nav a { text-decoration: none; }
|
||||
.nav a:hover { color: var(--c-accent); }
|
||||
|
||||
.nav__dropdown { position: relative; cursor: default; }
|
||||
|
||||
.nav__dropdownMenu {
|
||||
background-color: grey;
|
||||
display: none;
|
||||
position: absolute;
|
||||
top: 100%;
|
||||
left: 0;
|
||||
min-width: 12rem;
|
||||
margin-top: 0;
|
||||
list-style: none;
|
||||
background: var(--c-bg);
|
||||
border: 1px solid var(--c-border);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
padding: var(--space-2);
|
||||
}
|
||||
.nav__dropdown:hover .nav__dropdownMenu,
|
||||
.nav__dropdown.is-open .nav__dropdownMenu { display: block; }
|
||||
|
||||
.nav__list a { display: block; padding: var(--space-1) var(--space-2); }
|
||||
.nav__list a:hover { background: var(--c-surface); border-radius: var(--radius); }
|
||||
|
||||
|
||||
|
||||
@media (max-width: 640px) {
|
||||
button {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
font-size: .875rem;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
.addListForm {
|
||||
display: flex;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: var(--space-4);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.addListForm input { flex: 1; }
|
||||
|
||||
.displayedList {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.index .list {
|
||||
padding: var(--space-2) var(--space-3);
|
||||
background: var(--c-surface);
|
||||
border: 1px solid var(--c-border);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
|
||||
shopping-list {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
width: 100%;
|
||||
}
|
||||
.list__name {
|
||||
flex: 1;
|
||||
text-decoration: none;
|
||||
font-weight: 500;
|
||||
}
|
||||
.list__name:hover { color: var(--c-accent); }
|
||||
|
||||
.list__editButton,
|
||||
.list__deleteButton {
|
||||
background: var(--c-bg);
|
||||
color: var(--c-text);
|
||||
border: 1px solid var(--c-border);
|
||||
}
|
||||
.list__editButton:hover,
|
||||
.list__deleteButton:hover { background: var(--c-surface); }
|
||||
.list__deleteButton { color: var(--c-danger); }
|
||||
|
||||
@@ -1,22 +1,109 @@
|
||||
.category__name--bold {
|
||||
font-weight: bold;
|
||||
.title h1 { font-size: 2rem; }
|
||||
|
||||
.addCategoryForm,
|
||||
.addItemForm {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
.addItemForm__nameInput,
|
||||
.addItemForm__amountInput { flex: 1; min-width: 8rem; }
|
||||
|
||||
.deleteAllDoneItemsButton {
|
||||
margin-bottom: var(--space-4);
|
||||
background: var(--c-bg);
|
||||
color: var(--c-danger);
|
||||
border: 1px solid var(--c-border);
|
||||
}
|
||||
.deleteAllDoneItemsButton:hover { background: var(--c-surface); }
|
||||
|
||||
.displayedList {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.category__name--big {
|
||||
font-size : 1.5rem;
|
||||
shopping-category {
|
||||
display: block;
|
||||
border-left: 3px solid var(--c-border);
|
||||
border-radius: var(--radius)
|
||||
}
|
||||
|
||||
shopping-item[is-checked="true"] .item__text{
|
||||
text-decoration: line-through;
|
||||
.category__header{
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.item {
|
||||
.category__innerHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: .5em;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2);
|
||||
}
|
||||
.category__name{
|
||||
font-size: 1.5rem;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.category__deleteButton {
|
||||
background: var(--c-bg);
|
||||
color: var(--c-danger);
|
||||
border: 1px solid var(--c-border);
|
||||
}
|
||||
.category__deleteButton:hover { background: var(--c-surface); }
|
||||
|
||||
.category__deleteAllLabel {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
font-size: .875rem;
|
||||
color: var(--c-muted);
|
||||
margin-left: auto;
|
||||
}
|
||||
shopping-category > ul {
|
||||
list-style: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-1);
|
||||
padding-left: var(--space-3);
|
||||
margin-top: var(--space-2);
|
||||
}
|
||||
|
||||
.item__text{
|
||||
display: inline-flex;
|
||||
gap: .25em;
|
||||
.item { padding: var(--space-1) 0; }
|
||||
|
||||
shopping-item:hover , shopping-category:hover {
|
||||
background-color: var(--c-surface);
|
||||
}
|
||||
|
||||
.category__name:hover, .item__name:hover, .item__amount:hover {
|
||||
text-decoration: underline ;
|
||||
}
|
||||
|
||||
shopping-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-1);
|
||||
width: 100%;
|
||||
}
|
||||
.item__text {
|
||||
display: inline-flex;
|
||||
gap: var(--space-1);
|
||||
flex: 1;
|
||||
}
|
||||
.item__amount { color: var(--c-muted); }
|
||||
|
||||
shopping-item:has(.item__doneCheckbox:checked) .item__text {
|
||||
text-decoration: line-through;
|
||||
color: var(--c-muted);
|
||||
}
|
||||
|
||||
.item__deleteButton {
|
||||
padding: var(--space-1) var(--space-2);
|
||||
font-size: .875rem;
|
||||
background: var(--c-bg);
|
||||
color: var(--c-danger);
|
||||
border: 1px solid var(--c-border);
|
||||
}
|
||||
.item__deleteButton:hover { background: var(--c-surface); }
|
||||
@@ -9,7 +9,9 @@ export class ShoppingCategory extends HTMLElement {
|
||||
|
||||
connectedCallback() {
|
||||
if (this._rendered) return;
|
||||
|
||||
const categoryHeaderDiv = document.createElement("div");
|
||||
const categoryHeaderInnerDiv = document.createElement("div");
|
||||
const span = document.createElement("span");
|
||||
const deleteCategoryButton = document.createElement("button");
|
||||
const deleteAllItemsLabel = document.createElement("label");
|
||||
@@ -19,9 +21,10 @@ export class ShoppingCategory extends HTMLElement {
|
||||
|
||||
|
||||
categoryHeaderDiv.classList.add("category__header");
|
||||
categoryHeaderInnerDiv.classList.add("category__innerHeader");
|
||||
|
||||
span.textContent = this.getAttribute("category-name");
|
||||
span.classList.add("category__name", "category__name--bold", "category__name--big");
|
||||
span.classList.add("category__name");
|
||||
|
||||
deleteAllItemsLabel.classList.add("category__deleteAllLabel");
|
||||
deleteAllItemsLabel.textContent = "Gegenstände mit Kategorie löschen?";
|
||||
@@ -33,7 +36,9 @@ export class ShoppingCategory extends HTMLElement {
|
||||
|
||||
deleteAllItemsLabel.append(deleteAllItemsCheckbox);
|
||||
|
||||
categoryHeaderDiv.append(span, deleteCategoryButton, deleteAllItemsLabel);
|
||||
categoryHeaderInnerDiv.append(span, deleteCategoryButton, deleteAllItemsLabel);
|
||||
|
||||
categoryHeaderDiv.append(categoryHeaderInnerDiv);
|
||||
|
||||
this.prepend(categoryHeaderDiv);
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ShoppingList } from "../../models/ShoppingList.js";
|
||||
import { editElement } from "../../shared/editing.js";
|
||||
import { initErrors } from "../../shared/error.js";
|
||||
import { showError } from "../../shared/error.js";
|
||||
import { handleResponse } from "../../shared/helper.js";
|
||||
import { setElementAttributes } from "../../shared/sharedUI.js";
|
||||
import * as api from "./api/indexAPI.js";
|
||||
@@ -9,24 +9,29 @@ 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 response = await handleResponse(api.addList(listName), `error creating list`);
|
||||
if (response.ok) {
|
||||
ui.addList(response.json);
|
||||
} else {
|
||||
const name = document.querySelector(".addListForm__inputName");
|
||||
showError({ highlightFields: [name], elementForMessage: addListForm, message: response.json.msg });
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
async function deleteList(listElement) {
|
||||
const json = await handleResponse(api.deleteList(listElement.dataset.id), `error deleting list`);
|
||||
if (json) ui.deleteList(listElement);
|
||||
const response = await handleResponse(api.deleteList(listElement.dataset.id), `error deleting list`);
|
||||
if (response.ok) ui.deleteList(listElement);
|
||||
}
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
customElements.define("shopping-list", ShoppingList);
|
||||
|
||||
addListForm.addEventListener("submit", (e) => {
|
||||
e.preventDefault();
|
||||
const formData = Object.fromEntries(new FormData(addListForm));
|
||||
addList(formData.listName);
|
||||
addList(formData.listName?.trim());
|
||||
});
|
||||
|
||||
document.querySelector(".index").addEventListener("click", (event) => {
|
||||
@@ -44,14 +49,36 @@ function init() {
|
||||
setElementAttributes(shoppingListElement, { "list-name": f.listName });
|
||||
//nav wird hier ^ aktualisiert
|
||||
}
|
||||
, onFailure: (response) => {
|
||||
|
||||
const editForm = document.querySelector(".editForm");
|
||||
const name = document.querySelector("input.editForm__name");
|
||||
|
||||
showError({ highlightFields: [name], elementForMessage: editForm, message: response.json.msg });
|
||||
}
|
||||
|
||||
, errmsg: `liste konnte nicht aktualsiiert werden`
|
||||
|
||||
})
|
||||
|
||||
} else if (event.target.matches(".list__deleteButton")) {
|
||||
deleteList(event.target.closest("li"));
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector(".nav").addEventListener("click", (event) => {
|
||||
|
||||
if (event.target.matches(".nav__dropdown")) {
|
||||
event.target.closest("li").classList.add("is-open");
|
||||
event.stopPropagation();
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
document.querySelector("body").addEventListener("click", (event) => {
|
||||
if (!event.target.matches(".nav__dropdown")) {
|
||||
document.querySelector(".is-open")?.classList.remove("is-open");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('DOMContentLoaded', init);
|
||||
@@ -1,11 +1,11 @@
|
||||
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";
|
||||
import { showError } from "../../shared/error.js";
|
||||
|
||||
const addCategoryForm = document.querySelector(".addCategoryForm");
|
||||
const addItemForm = document.querySelector(".addItemForm");
|
||||
@@ -15,41 +15,53 @@ const deleteAllDoneItemsButton = document.querySelector(".deleteAllDoneItemsButt
|
||||
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);
|
||||
const response = await handleResponse(api.addItem(currentList.dataset.id, itemName, itemAmount, categoryID), `item couldnt be created!`);
|
||||
if (response.ok) {
|
||||
ui.addItem(response.json);
|
||||
} else {
|
||||
const form = document.querySelector(".addItemForm");
|
||||
const name = document.querySelector(".addItemForm__nameInput");
|
||||
const amount = document.querySelector(".addItemForm__amountInput");
|
||||
showError({ highlightFields: [name, amount], elementForMessage: form, message: response.json.msg });
|
||||
}
|
||||
}
|
||||
|
||||
async function addCategory(categoryName) {
|
||||
console.log(`adding category ${categoryName}`)
|
||||
|
||||
const json = await handleResponse(api.addCategory(currentList.dataset.id, categoryName), `category couldnt be added!`);
|
||||
if (json) ui.addCategory(json);
|
||||
const response = await handleResponse(api.addCategory(currentList.dataset.id, categoryName), `category couldnt be added!`);
|
||||
if (response.ok) {
|
||||
ui.addCategory(response.json);
|
||||
} else {
|
||||
const form = document.querySelector(".addCategoryForm");
|
||||
const name = document.querySelector(".addCategoryForm__nameInput");
|
||||
showError({ highlightFields: [name], elementForMessage: form, message: response.json.msg });
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
async function deleteItem(li) {
|
||||
console.log(`deleting item ${li.dataset.id}`)
|
||||
|
||||
const json = await handleResponse(api.deleteItem(li.dataset.id), `error deleting item`);
|
||||
if (json) ui.deleteItem(li);
|
||||
const response = await handleResponse(api.deleteItem(li.dataset.id), `error deleting item`);
|
||||
if (response.ok) ui.deleteItem(li);
|
||||
}
|
||||
|
||||
async function deleteCategory(deleteAllItems, categoryID) {
|
||||
console.log(`deleting category with allItems: ${deleteAllItems} id: ${categoryID}`);
|
||||
const json = await handleResponse(api.deleteCategory(deleteAllItems, categoryID), `error deleting category`);
|
||||
const response = await handleResponse(api.deleteCategory(deleteAllItems, categoryID), `error deleting category`);
|
||||
|
||||
if (json) ui.deleteCategory(deleteAllItems, categoryID);
|
||||
if (response.ok) ui.deleteCategory(deleteAllItems, categoryID);
|
||||
}
|
||||
|
||||
async 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();
|
||||
const response = await handleResponse(api.deleteAllDoneItems(currentList.dataset.id), `error deleting all done items`);
|
||||
if (response.ok) ui.deleteAllDoneItems();
|
||||
}
|
||||
|
||||
function init() {
|
||||
|
||||
initErrors(document.querySelector(".nav"));
|
||||
|
||||
customElements.define("shopping-item", ShoppingItem);
|
||||
customElements.define("shopping-category", ShoppingCategory);
|
||||
@@ -57,13 +69,13 @@ function init() {
|
||||
addCategoryForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
let formData = Object.fromEntries(new FormData(addCategoryForm));
|
||||
addCategory(formData.categoryName);
|
||||
addCategory(formData.categoryName?.trim());
|
||||
});
|
||||
|
||||
addItemForm.addEventListener("submit", event => {
|
||||
event.preventDefault();
|
||||
let formData = Object.fromEntries(new FormData(addItemForm));
|
||||
addItem(formData.itemName, formData.itemAmount, formData.itemCategoryID);
|
||||
addItem(formData.itemName?.trim(), formData.itemAmount?.trim(), formData.itemCategoryID);
|
||||
});
|
||||
|
||||
deleteAllDoneItemsButton.addEventListener("click", event => {
|
||||
@@ -99,19 +111,27 @@ function init() {
|
||||
{ name: "itemAmount", value: itemAmount, class: "editForm__amount", attr: "item-amount" }
|
||||
]
|
||||
, onSuccess: (f) => { sharedUI.setElementAttributes(shoppingItemElement, { "item-name": f.itemName, "item-amount": f.itemAmount }) }
|
||||
, onFailure: (response) => {
|
||||
|
||||
const editForm = document.querySelector(".editForm");
|
||||
const name = document.querySelector("input.editForm__name");
|
||||
const amount = document.querySelector("input.editForm__amount")
|
||||
|
||||
showError({ highlightFields: [name, amount], elementForMessage: editForm, message: response.json.msg });
|
||||
}
|
||||
, errmsg: `konnte Item nicht bearbeiten`
|
||||
});
|
||||
|
||||
} else if (event.target.closest(".category__name")) {
|
||||
|
||||
const categoryElement = event.target.closest("shopping-category");
|
||||
const categoryHeader = event.target.closest(".category__header");
|
||||
const categoryInnerHeader = event.target.closest(".category__innerHeader");
|
||||
const id = event.target.closest("li").dataset.id;
|
||||
|
||||
let categoryName = categoryElement.querySelector(".category__name").textContent;
|
||||
|
||||
editElement({
|
||||
element: categoryHeader, apiCall: api.editCategory, id: id,
|
||||
element: categoryInnerHeader, apiCall: api.editCategory, id: id,
|
||||
fields: [
|
||||
{ name: "categoryName", value: categoryName, class: "editForm__name", attr: "category-name" },
|
||||
]
|
||||
@@ -119,10 +139,28 @@ function init() {
|
||||
sharedUI.setElementAttributes(categoryElement, { "category-name": f.categoryName })
|
||||
document.querySelector(`option[value='${id}']`).textContent = f.categoryName;
|
||||
}
|
||||
, onFailure: (response) => {
|
||||
|
||||
const editForm = document.querySelector(".editForm");
|
||||
const name = document.querySelector(".editForm__name");
|
||||
|
||||
showError({ highlightFields: [name], elementForMessage: editForm, message: response.json.msg });
|
||||
|
||||
}
|
||||
, errmsg: `konnte Kategorie nicht bearbeiten`
|
||||
});
|
||||
|
||||
}
|
||||
|
||||
|
||||
});
|
||||
|
||||
document.querySelector(".nav").addEventListener("click", (event) => {
|
||||
|
||||
if (event.target.matches(".nav__dropdown")) {
|
||||
event.target.closest("li").classList.add("is-open");
|
||||
event.stopPropagation();
|
||||
}
|
||||
});
|
||||
|
||||
document.querySelector(".displayedList").addEventListener("change", (e) => {
|
||||
@@ -133,6 +171,14 @@ function init() {
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
|
||||
document.querySelector("body").addEventListener("click", (event) => {
|
||||
if (!event.target.matches(".nav__dropdown")) {
|
||||
document.querySelector(".is-open")?.classList.remove("is-open");
|
||||
}
|
||||
});
|
||||
|
||||
console.log("javascript initialized!");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { abortEditing, createEditForm } from "./sharedUI.js";
|
||||
import { handleResponse } from "./helper.js";
|
||||
|
||||
export async function editElement({ element, fields, apiCall, id, onSuccess, errmsg }) {
|
||||
export async function editElement({ element, fields, apiCall, id, onSuccess, onFailure, errmsg }) {
|
||||
const formElement = createEditForm(fields);
|
||||
|
||||
element.replaceWith(formElement);
|
||||
@@ -12,11 +12,21 @@ export async function editElement({ element, fields, apiCall, id, onSuccess, err
|
||||
event.preventDefault();
|
||||
|
||||
let formData = Object.fromEntries(new FormData(formElement));
|
||||
|
||||
for (const key in formData) {
|
||||
if (typeof formData[key] === "string") formData[key] = formData[key].trim();
|
||||
}
|
||||
|
||||
let result = await handleResponse(apiCall(id, formData), errmsg);
|
||||
|
||||
abortEditing(formElement, element);
|
||||
|
||||
if (result) onSuccess(formData);
|
||||
if (result.ok) {
|
||||
abortEditing(formElement, element);
|
||||
onSuccess(formData);
|
||||
} else {
|
||||
onFailure(result);
|
||||
|
||||
}
|
||||
});
|
||||
|
||||
formElement.addEventListener("click", (e) => {
|
||||
|
||||
@@ -1,22 +1,30 @@
|
||||
const errorDiv = document.createElement("div");
|
||||
const errorSpan = document.createElement("span");
|
||||
let errorTimer;
|
||||
export function createErrorSpan(msg) {
|
||||
const span = document.createElement("span");
|
||||
span.textContent = msg;
|
||||
span.classList.add("error-message");
|
||||
return span;
|
||||
}
|
||||
|
||||
export function showError(msg) {
|
||||
errorSpan.textContent = msg;
|
||||
errorDiv.hidden = false
|
||||
|
||||
export function showError({ highlightFields, elementForMessage, message }) {
|
||||
|
||||
highlightFields.forEach(field => {
|
||||
field.classList.add("is-invalid");
|
||||
});
|
||||
|
||||
const errSpan = createErrorSpan(message);
|
||||
|
||||
elementForMessage.append(errSpan);
|
||||
|
||||
let errorTimer;
|
||||
clearTimeout(errorTimer);
|
||||
errorTimer = (setTimeout(() => {
|
||||
errorDiv.hidden = true;
|
||||
errorSpan.textContent = "";
|
||||
}, 3000));
|
||||
}
|
||||
|
||||
highlightFields.forEach(field => {
|
||||
field.classList.remove("is-invalid");
|
||||
})
|
||||
|
||||
export function initErrors(element) {
|
||||
errorDiv.hidden = true;
|
||||
errorDiv.append(errorSpan);
|
||||
elementForMessage.removeChild(errSpan);
|
||||
}, 5000));
|
||||
|
||||
element.append(errorDiv);
|
||||
}
|
||||
@@ -1,21 +1,19 @@
|
||||
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;
|
||||
return { ok: true, json: null };
|
||||
}
|
||||
|
||||
const json = await response.json();
|
||||
|
||||
if (!response.ok) {
|
||||
showError(json.msg);
|
||||
console.error(errorMsg);
|
||||
return false;
|
||||
return { ok: false, json: json };
|
||||
}
|
||||
|
||||
return json;
|
||||
return { ok: true, json: json };
|
||||
|
||||
}
|
||||
@@ -25,6 +25,7 @@ export function createEditForm(fields) {
|
||||
|
||||
|
||||
editForm.append(...inputs, saveButton, abortButton);
|
||||
editForm.classList.add("editForm");
|
||||
|
||||
return editForm;
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ xmlns:th="http://www.thymeleaf.org">
|
||||
<meta name="author" content="" />
|
||||
<link href="/css/base.css" rel="stylesheet">
|
||||
<link href="/css/index.css" rel="stylesheet" >
|
||||
<title>Einkaufsliste</title>
|
||||
<script src="/js/pages/index/index.js" type="module"></script>
|
||||
|
||||
<body>
|
||||
@@ -15,7 +16,7 @@ xmlns:th="http://www.thymeleaf.org">
|
||||
<nav class="nav">
|
||||
<ul class="nav__links">
|
||||
<li class="nav__link"><a href="/">Alle Einkaufslisten</a></li>
|
||||
<li class="nav__dropdown">Listen >
|
||||
<li class="nav__dropdown">Listen
|
||||
<ul class="nav__dropdownMenu">
|
||||
<li th:each="list : ${lists}" th:data-id="${list.id}" class="nav__list">
|
||||
<a th:text="${list.listName}" th:href="@{/list/{id}(id=${list.id})}"></a>
|
||||
@@ -27,7 +28,7 @@ xmlns:th="http://www.thymeleaf.org">
|
||||
|
||||
<div class="index">
|
||||
<form class="addListForm">
|
||||
<input type="text" name="listName" required />
|
||||
<input class="addListForm__inputName" type="text" name="listName"/>
|
||||
<button type="submit">Neue Liste erstellen</button>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
<nav class="nav">
|
||||
<ul class="nav__links">
|
||||
<li class="nav__link"><a href="/">Alle Einkaufslisten</a></li>
|
||||
<li class="nav__dropdown">Listen >
|
||||
<li class="nav__dropdown">Listen
|
||||
<ul class="nav__dropdownMenu">
|
||||
<li th:each="list : ${lists}" th:data-id="${list.id}" class="nav__list">
|
||||
<a th:text="${list.listName}" th:href="@{/list/{id}(id=${list.id})}"></a>
|
||||
|
||||
Reference in new issue
Block a user