From ca3a501be43d721be20e4b01ef8ae144b4a31c3a Mon Sep 17 00:00:00 2001 From: albrecht <flo@DESKTOP-ERC0T8S> Date: Mon, 10 Jul 2023 09:34:27 +0200 Subject: [PATCH] =?UTF-8?q?Log=20funktionen=20bei=20allen=20Handlern=20ein?= =?UTF-8?q?gef=C3=BCgt?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/gomazon/db/db.go | 11 +++-- src/gomazon/handler/auth.go | 7 ++- src/gomazon/handler/bank.go | 14 ++++-- src/gomazon/handler/bewertung.go | 71 ++++++++++++++------------ src/gomazon/handler/produkt.go | 85 ++++++++++++++++++-------------- src/gomazon/handler/warenkorb.go | 50 ++++++++++--------- src/gomazon/main.go | 40 +++++++-------- src/gomazon/model/bewertung.go | 8 +-- src/gomazon/model/position.go | 2 +- src/gomazon/model/produkt.go | 12 ++--- src/gomazon/model/warenkorb.go | 2 +- src/gomazon/service/bewertung.go | 66 ++++++++++++------------- src/gomazon/service/produkt.go | 46 ++++++++--------- src/gomazon/service/warenkorb.go | 68 ++++++++++++------------- 14 files changed, 262 insertions(+), 220 deletions(-) diff --git a/src/gomazon/db/db.go b/src/gomazon/db/db.go index 7e5ffea..f070867 100644 --- a/src/gomazon/db/db.go +++ b/src/gomazon/db/db.go @@ -23,18 +23,23 @@ func init() { } log.Info("Starting automatic migrations") if err := DB.Debug().AutoMigrate(&model.BankAccount{}); err != nil { + log.Errorf("Failed to auto migrate BankAccount") panic(err) } - if err := DB.Debug().AutoMigrate(&model.Produkt{}); err != nil { + if err := DB.Debug().AutoMigrate(&model.Product{}); err != nil { + log.Errorf("Failed to auto migrate Product") panic(err) } - if err := DB.Debug().AutoMigrate(&model.Warenkorb{}); err != nil { + if err := DB.Debug().AutoMigrate(&model.ShoppingCart{}); err != nil { + log.Errorf("Failed to auto migrate ShoppingCart") panic(err) } - if err := DB.Debug().AutoMigrate(&model.Bewertung{}); err != nil { + if err := DB.Debug().AutoMigrate(&model.Rating{}); err != nil { + log.Errorf("Failed to auto migrate Rating") panic(err) } if err := DB.Debug().AutoMigrate(&model.Position{}); err != nil { + log.Errorf("Failed to auto migrate Position") panic(err) } log.Info("Automatic migrations finished") diff --git a/src/gomazon/handler/auth.go b/src/gomazon/handler/auth.go index aae92cf..ea186d3 100644 --- a/src/gomazon/handler/auth.go +++ b/src/gomazon/handler/auth.go @@ -5,6 +5,7 @@ import ( "time" "github.com/gin-gonic/gin" + log "github.com/sirupsen/logrus" "gitlab.reutlingen-university.de/albrecht/gomazon/service" ) @@ -17,18 +18,21 @@ func GenerateAdminTokenHandler(c *gin.Context) { } if err := c.ShouldBindJSON(&requestBody); err != nil { + log.Errorf("Invalid request body for authentication") c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid request body"}) return } // Überprüfen, ob der Benutzername vorhanden ist if requestBody.Username == "" { + log.Errorf("Invalid username for authentication") c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid username"}) return } // Überprüfen, ob isAdmin gesetzt ist if _, ok := interface{}(requestBody.IsAdmin).(bool); !ok { + log.Errorf("Invalid isAdmin flag for authentication") c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid isAdmin value"}) return } @@ -37,9 +41,10 @@ func GenerateAdminTokenHandler(c *gin.Context) { expiration := time.Now().Add(30 * time.Minute) token, err := service.GenerateAdminJWTToken(requestBody.Username, requestBody.IsAdmin, expiration) if err != nil { + log.Errorf("Failed to generate admin token") c.JSON(http.StatusInternalServerError, gin.H{"error": "Failed to generate admin token"}) return } - + log.Infof("Generated admin token") c.JSON(http.StatusOK, gin.H{"token": token}) } diff --git a/src/gomazon/handler/bank.go b/src/gomazon/handler/bank.go index 4bd898a..6dde9c6 100644 --- a/src/gomazon/handler/bank.go +++ b/src/gomazon/handler/bank.go @@ -18,11 +18,13 @@ func (h *BankAccountHandler) CreateBankAccount(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } var bankAccount model.BankAccount if err := c.ShouldBindJSON(&bankAccount); err != nil { + log.Errorf("ShouldBindJSON in CreateBankAccount failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } @@ -30,17 +32,19 @@ func (h *BankAccountHandler) CreateBankAccount(c *gin.Context) { createdAccount, err := h.BankAccountService.CreateBankAccount(bankAccount) if err != nil { + log.Errorf("Creation of the bank account failed") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - + log.Info("Bank account successfully created") c.JSON(http.StatusCreated, createdAccount) } + func (h *BankAccountHandler) UpdateBankAccount(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") } var withdrawalData struct { @@ -48,15 +52,17 @@ func (h *BankAccountHandler) UpdateBankAccount(c *gin.Context) { } if err := c.ShouldBindJSON(&withdrawalData); err != nil { + log.Errorf("ShouldBindJSON in UpdateBankAccount failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } updatedAccount, err := h.BankAccountService.UpdateBankAccount(username, withdrawalData.Amount) if err != nil { + log.Errorf("Account update from User '%v' failed", updatedAccount.Username) c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - + log.Info("Account update successfull") c.JSON(http.StatusOK, updatedAccount) } diff --git a/src/gomazon/handler/bewertung.go b/src/gomazon/handler/bewertung.go index 89e5195..4d6095e 100644 --- a/src/gomazon/handler/bewertung.go +++ b/src/gomazon/handler/bewertung.go @@ -10,87 +10,94 @@ import ( "gitlab.reutlingen-university.de/albrecht/gomazon/service" ) -type BewertungHandler struct { - BewertungService *service.BewertungService - ProduktService *service.ProduktService +type RatingHandler struct { + RatingService *service.RatingService + ProductService *service.ProductService } -func (h *BewertungHandler) CreateBewertung(c *gin.Context) { +func (h *RatingHandler) CreateRating(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") } - // Produkt-ID aus dem URL-Parameter extrahieren - produktID, err := strconv.Atoi(c.Param("id")) + // Product-ID aus dem URL-Parameter extrahieren + ProductID, err := strconv.Atoi(c.Param("id")) if err != nil { + log.Errorf("Invalid ID for a product") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - // Bewertungsdaten aus dem Request-Body lesen - var bewertung *model.Bewertung - if err := c.ShouldBindJSON(&bewertung); err != nil { + // Ratingsdaten aus dem Request-Body lesen + var Rating *model.Rating + if err := c.ShouldBindJSON(&Rating); err != nil { + log.Errorf("ShouldBindJSON in CreateRating failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - bewertung.Username = username + Rating.Username = username - // Bewertung erstellen - err = h.BewertungService.CreateBewertung(uint(produktID), bewertung) + // Rating erstellen + err = h.RatingService.CreateRating(uint(ProductID), Rating) if err != nil { + log.Errorf("Creation of Rating failed") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, bewertung) + log.Info("Ration successfully created") + c.JSON(http.StatusOK, Rating) } -func (h *BewertungHandler) DeleteBewertung(c *gin.Context) { +func (h *RatingHandler) DeleteRating(c *gin.Context) { - // Produkt-ID und Bewertungs-ID aus den URL-Parametern extrahieren - bewertungID, err := strconv.Atoi(c.Param("id")) + // Product-ID und Ratings-ID aus den URL-Parametern extrahieren + RatingID, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Bewertung ID"}) + log.Errorf("Invalid Rating ID") + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Rating ID"}) return } - bewertung, err := h.ProduktService.GetBewertungByID(uint(bewertungID)) + Rating, err := h.ProductService.GetRatingByID(uint(RatingID)) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Bewertung ID"}) + log.Errorf("Invalid Rating ID") + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Rating ID"}) return } tokenString := c.GetHeader("Authorization") username, admin, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") } - if admin || (bewertung.Username == username) { + if admin || (Rating.Username == username) { - // Bewertung löschen - err = h.BewertungService.DeleteBewertung(uint(bewertungID)) + // Rating löschen + err = h.RatingService.DeleteRating(uint(RatingID)) if err != nil { + log.Error("Could not delete Rating") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, gin.H{"message": "Bewertung erfolgreich gelöscht"}) + log.Info("Rating successfully deleted") + c.JSON(http.StatusOK, gin.H{"message": "Rating successfully deleted"}) } else { c.JSON(http.StatusBadRequest, gin.H{"error": "not authorized"}) - log.Errorf("%v is not the owner (%v)", username, bewertung.Username) + log.Errorf("%v (isAdmin = %v) is not an admin or the owner (%v)", username, admin, Rating.Username) return } } -func (h *BewertungHandler) ReadBewertungen(c *gin.Context) { - produkte, err := h.BewertungService.ProduktService.ReadBewertungen() +func (h *RatingHandler) ReadRatings(c *gin.Context) { + Products, err := h.RatingService.ProductService.ReadRatings() if err != nil { + log.Errorf("Failed to load all Ratings") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, produkte) + log.Info("Loaded all ratings") + c.JSON(http.StatusOK, Products) } diff --git a/src/gomazon/handler/produkt.go b/src/gomazon/handler/produkt.go index 2baf38d..dcc3a3c 100644 --- a/src/gomazon/handler/produkt.go +++ b/src/gomazon/handler/produkt.go @@ -10,11 +10,11 @@ import ( "gitlab.reutlingen-university.de/albrecht/gomazon/service" ) -type ProduktHandler struct { - ProduktService *service.ProduktService +type ProductHandler struct { + ProductService *service.ProductService } -func (h *ProduktHandler) CreateProdukt(c *gin.Context) { +func (h *ProductHandler) CreateProduct(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, admin, err := service.ExtractTokenData(tokenString) if !admin { @@ -23,39 +23,43 @@ func (h *ProduktHandler) CreateProdukt(c *gin.Context) { return } if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } - var produkt model.Produkt + var Product model.Product - // Die Produktinformationen aus dem Request-Body binden - if err := c.ShouldBindJSON(&produkt); err != nil { + // Die Productinformationen aus dem Request-Body binden + if err := c.ShouldBindJSON(&Product); err != nil { + log.Errorf("ShouldBindJSON in CreateProduct failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - produkt.Gesamtrating = 0.0 + Product.Gesamtrating = 0.0 - // Das Produkt über den ProduktService erstellen - createdProdukt, err := h.ProduktService.CreateProdukt(produkt) + // Das Product über den ProductService erstellen + createdProduct, err := h.ProductService.CreateProduct(Product) if err != nil { + log.Errorf("Creation of product failed") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, createdProdukt) + log.Info("Product successfully created") + c.JSON(http.StatusOK, createdProduct) } -func (h *ProduktHandler) ReadProdukte(c *gin.Context) { - produkte, err := h.ProduktService.ReadProdukte() +func (h *ProductHandler) ReadProducts(c *gin.Context) { + Products, err := h.ProductService.ReadProducts() if err != nil { + log.Errorf("Failed to load all Products") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, produkte) + log.Info("Loaded all products") + c.JSON(http.StatusOK, Products) } -func (h *ProduktHandler) UpdateProdukt(c *gin.Context) { +func (h *ProductHandler) UpdateProduct(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, admin, err := service.ExtractTokenData(tokenString) if !admin { @@ -64,31 +68,35 @@ func (h *ProduktHandler) UpdateProdukt(c *gin.Context) { return } if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Ungültige ID"}) + log.Error("Invalid ID") + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"}) return } - var produkt model.Produkt - if err := c.ShouldBindJSON(&produkt); err != nil { + var Product model.Product + if err := c.ShouldBindJSON(&Product); err != nil { + log.Error("ShouldBindJSON in UpdateProduct failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - updatedProdukt, err := h.ProduktService.UpdateProdukt(uint(id), produkt) + updatedProduct, err := h.ProductService.UpdateProduct(uint(id), Product) if err != nil { + log.Error("Productupdate failed") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, updatedProdukt) + log.Info("Product updated successfully") + c.JSON(http.StatusOK, updatedProduct) } -func (h *ProduktHandler) DeleteProdukt(c *gin.Context) { +func (h *ProductHandler) DeleteProduct(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, admin, err := service.ExtractTokenData(tokenString) if !admin { @@ -97,36 +105,41 @@ func (h *ProduktHandler) DeleteProdukt(c *gin.Context) { return } if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Ungültige ID"}) + log.Error("Invalid ID") + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"}) return } - err = h.ProduktService.DeleteProdukt(uint(id)) + err = h.ProductService.DeleteProduct(uint(id)) if err != nil { + log.Error("DeleteProduct failed") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, gin.H{"message": "Produkt erfolgreich gelöscht"}) + log.Info("Product successfully removed") + c.JSON(http.StatusOK, gin.H{"message": "Product successfully removed"}) } -func (h *ProduktHandler) GetProduktByID(c *gin.Context) { +func (h *ProductHandler) GetProductByID(c *gin.Context) { id, err := strconv.Atoi(c.Param("id")) if err != nil { - c.JSON(http.StatusBadRequest, gin.H{"error": "Ungültige ID"}) + log.Error("Invalid ID") + c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid ID"}) return } - produkt, err := h.ProduktService.GetProduktByID(uint(id)) + Product, err := h.ProductService.GetProductByID(uint(id)) if err != nil { - c.JSON(http.StatusNotFound, gin.H{"error": "Produkt nicht gefunden"}) + log.Errorf("Could not find Product with the ID: %v", id) + c.JSON(http.StatusNotFound, gin.H{"error": "Could not find Product"}) return } - - c.JSON(http.StatusOK, produkt) + log.Infof("Product with ID %v found", id) + c.JSON(http.StatusOK, Product) } diff --git a/src/gomazon/handler/warenkorb.go b/src/gomazon/handler/warenkorb.go index 80fe487..67a034e 100644 --- a/src/gomazon/handler/warenkorb.go +++ b/src/gomazon/handler/warenkorb.go @@ -10,45 +10,49 @@ import ( "gitlab.reutlingen-university.de/albrecht/gomazon/service" ) -type WarenkorbHandler struct { - WarenkorbService *service.WarenkorbService - BankAccountService *service.BankAccountService +type ShoppingCartHandler struct { + ShoppingCartService *service.ShoppingCartService + BankAccountService *service.BankAccountService } -// Warenkorb erstellen -func (h *WarenkorbHandler) CreateWarenkorb(c *gin.Context) { +// ShoppingCart erstellen +func (h *ShoppingCartHandler) CreateShoppingCart(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } - var warenkorb model.Warenkorb - // if err := c.ShouldBindJSON(&warenkorb); err != nil { + var ShoppingCart model.ShoppingCart + // if err := c.ShouldBindJSON(&ShoppingCart); err != nil { // c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) // return // } - warenkorb.Username = username + ShoppingCart.Username = username - createdWarenkorb, err := h.WarenkorbService.CreateWarenkorb(warenkorb) + createdShoppingCart, err := h.ShoppingCartService.CreateShoppingCart(ShoppingCart) if err != nil { + log.Error("Could not create Shopping Cart") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusCreated, createdWarenkorb) + log.Info("Shopping Cart created/Get existing Shopping Cart") + c.JSON(http.StatusCreated, createdShoppingCart) } -// Einzelnes Produkt zum Warenkorb hinzufügen -func (h *WarenkorbHandler) AddProductToWarenkorb(c *gin.Context) { +// Einzelnes Product zum ShoppingCart hinzufügen +func (h *ShoppingCartHandler) AddProductToShoppingCart(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { - log.Errorf(err.Error()) + log.Errorf("Extraction of JWT-Token failed") + return } - produktID, err := strconv.Atoi(c.Param("id")) + ProductID, err := strconv.Atoi(c.Param("id")) if err != nil { + log.Error("Invalid Product ID") c.JSON(http.StatusBadRequest, gin.H{"error": "Invalid Product ID"}) return } @@ -58,28 +62,30 @@ func (h *WarenkorbHandler) AddProductToWarenkorb(c *gin.Context) { } if err := c.ShouldBindJSON(&addProductData); err != nil { + log.Error("ShouldBindJSON in AddProductToShoppingCart failed") c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - updatedWarenkorb, err := h.WarenkorbService.AddProductToWarenkorb(username, uint(produktID), addProductData.Menge) + updatedShoppingCart, err := h.ShoppingCartService.AddProductToShoppingCart(username, uint(ProductID), addProductData.Menge) if err != nil { + log.Error("Coud not insert product to Shopping Cart") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return } - - c.JSON(http.StatusOK, updatedWarenkorb) + log.Info("Insertet Product to Shopping Cart") + c.JSON(http.StatusOK, updatedShoppingCart) } -// Bezahlfunktion für den Warenkorb -func (h *WarenkorbHandler) Bezahlen(c *gin.Context) { +// Bezahlfunktion für den ShoppingCart +func (h *ShoppingCartHandler) Bezahlen(c *gin.Context) { tokenString := c.GetHeader("Authorization") username, _, err := service.ExtractTokenData(tokenString) if err != nil { log.Errorf(err.Error()) } - err = h.WarenkorbService.Bezahlen(username) + err = h.ShoppingCartService.Bezahlen(username) if err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) return diff --git a/src/gomazon/main.go b/src/gomazon/main.go index 35f97b9..698192c 100644 --- a/src/gomazon/main.go +++ b/src/gomazon/main.go @@ -10,16 +10,16 @@ func main() { router := gin.Default() // Service erstellen - produktService := &service.ProduktService{} - bewertungService := &service.BewertungService{} + ProductService := &service.ProductService{} + RatingService := &service.RatingService{} bankAccountService := &service.BankAccountService{} - warenkorbService := &service.WarenkorbService{} + ShoppingCartService := &service.ShoppingCartService{} // Handler erstellen und den Service zuweisen - produktHandler := &handler.ProduktHandler{ProduktService: produktService} - bewertungHandler := &handler.BewertungHandler{BewertungService: bewertungService} + ProductHandler := &handler.ProductHandler{ProductService: ProductService} + RatingHandler := &handler.RatingHandler{RatingService: RatingService} bankAccountHandler := &handler.BankAccountHandler{BankAccountService: bankAccountService} - warenkorbHandler := &handler.WarenkorbHandler{WarenkorbService: warenkorbService} + ShoppingCartHandler := &handler.ShoppingCartHandler{ShoppingCartService: ShoppingCartService} // Initialer Test, wie Gin funktioniert router.GET("/health", func(c *gin.Context) { @@ -29,26 +29,26 @@ func main() { ////Non-Admin-Funktionen router.GET("/createJWT", handler.GenerateAdminTokenHandler) //generate jwt-token - //Produkte - router.POST("/products", produktHandler.CreateProdukt) //neues Produkt (Admin only) - router.PUT("/products/:id", produktHandler.UpdateProdukt) //update Produkt (Admin only) - router.DELETE("/products/:id", produktHandler.DeleteProdukt) //Delete Produkt (Admin only) - router.GET("/products", produktHandler.ReadProdukte) //alle Produkte - router.GET("/products/:id", produktHandler.GetProduktByID) //einzelnes Produkt + //Products + router.POST("/products", ProductHandler.CreateProduct) //neues Product (Admin only) + router.PUT("/products/:id", ProductHandler.UpdateProduct) //update Product (Admin only) + router.DELETE("/products/:id", ProductHandler.DeleteProduct) //Delete Product (Admin only) + router.GET("/products", ProductHandler.ReadProducts) //alle Products + router.GET("/products/:id", ProductHandler.GetProductByID) //einzelnes Product - //Bewertung - router.POST("/products/:id/rating", bewertungHandler.CreateBewertung) //neue Bewertung - router.DELETE("/ratings/:id", bewertungHandler.DeleteBewertung) //Delete Bewertung (Admin only (oder eigene)) - router.GET("/ratings", bewertungHandler.ReadBewertungen) //alle Bewertungen + //Rating + router.POST("/products/:id/rating", RatingHandler.CreateRating) //neue Rating + router.DELETE("/ratings/:id", RatingHandler.DeleteRating) //Delete Rating (Admin only (oder eigene)) + router.GET("/ratings", RatingHandler.ReadRatings) //alle Ratings //Bankkonto router.POST("/bankaccounts", bankAccountHandler.CreateBankAccount) // neues Konto router.PUT("/bankaccounts", bankAccountHandler.UpdateBankAccount) // Überweisung - //Warenkorb - router.POST("/warenkorb", warenkorbHandler.CreateWarenkorb) //neuer Warenkorb - router.POST("/warenkorb/produkt/:id", warenkorbHandler.AddProductToWarenkorb) //produkt hinzufügen - router.POST("/warenkorb/bezahlen", warenkorbHandler.Bezahlen) //bezahlen + //ShoppingCart + router.POST("/ShoppingCart", ShoppingCartHandler.CreateShoppingCart) //neuer ShoppingCart + router.POST("/ShoppingCart/Product/:id", ShoppingCartHandler.AddProductToShoppingCart) //Product hinzufügen + router.POST("/ShoppingCart/bezahlen", ShoppingCartHandler.Bezahlen) //bezahlen router.Run(":8080") } diff --git a/src/gomazon/model/bewertung.go b/src/gomazon/model/bewertung.go index 86c04b4..da96caf 100644 --- a/src/gomazon/model/bewertung.go +++ b/src/gomazon/model/bewertung.go @@ -2,10 +2,10 @@ package model import "gorm.io/gorm" -type Bewertung struct { - gorm.Model //benötigt, weil Bewertungen auch gelöscht werden sollen +type Rating struct { + gorm.Model //benötigt, weil Ratings auch gelöscht werden sollen Username string `gorm:"notNull"` Inhalt string `gorm:"notNull"` - Bewertung int `gorm:"notNull"` - ProduktId uint + Rating int `gorm:"notNull"` + ProductId uint } diff --git a/src/gomazon/model/position.go b/src/gomazon/model/position.go index c078383..9cc75cc 100644 --- a/src/gomazon/model/position.go +++ b/src/gomazon/model/position.go @@ -5,7 +5,7 @@ import "gorm.io/gorm" type Position struct { gorm.Model Menge int `gorm:"notNull"` - ProduktId uint `gorm:"notNull"` + ProductId uint `gorm:"notNull"` Preis float64 `gorm:"notNull"` Gesamtpreis float64 `gorm:"notNull"` } diff --git a/src/gomazon/model/produkt.go b/src/gomazon/model/produkt.go index 7afafc5..7c872fa 100644 --- a/src/gomazon/model/produkt.go +++ b/src/gomazon/model/produkt.go @@ -2,11 +2,11 @@ package model import "gorm.io/gorm" -type Produkt struct { +type Product struct { gorm.Model - Name string `gorm:"notNull"` - Description string `gorm:"notNull;size:80"` - Gesamtrating float64 `gorm:"notNull;default:0.0"` - Preis float64 `gorm:"notNull"` - Bewertungen []Bewertung `gorm:"foreignKey:ProduktId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + Name string `gorm:"notNull"` + Description string `gorm:"notNull;size:80"` + Gesamtrating float64 `gorm:"notNull;default:0.0"` + Preis float64 `gorm:"notNull"` + Ratings []Rating `gorm:"foreignKey:ProductId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` } diff --git a/src/gomazon/model/warenkorb.go b/src/gomazon/model/warenkorb.go index 86bba4c..b18b6dc 100644 --- a/src/gomazon/model/warenkorb.go +++ b/src/gomazon/model/warenkorb.go @@ -2,7 +2,7 @@ package model import "gorm.io/gorm" -type Warenkorb struct { +type ShoppingCart struct { gorm.Model Positionen []Position `gorm:"foreignKey:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` Gesamtpreis float64 `gorm:"notNull;default:0.0"` diff --git a/src/gomazon/service/bewertung.go b/src/gomazon/service/bewertung.go index 79064e3..5cb3311 100644 --- a/src/gomazon/service/bewertung.go +++ b/src/gomazon/service/bewertung.go @@ -6,43 +6,43 @@ import ( "gitlab.reutlingen-university.de/albrecht/gomazon/model" ) -type BewertungService struct { - ProduktService *ProduktService +type RatingService struct { + ProductService *ProductService } -func (s *BewertungService) CreateBewertung(produktID uint, bewertung *model.Bewertung) error { - bewertung.ProduktId = produktID +func (s *RatingService) CreateRating(ProductID uint, Rating *model.Rating) error { + Rating.ProductId = ProductID - result := db.DB.Create(bewertung) + result := db.DB.Create(Rating) if result.Error != nil { return result.Error } - produkt, err := s.ProduktService.GetProduktByID(produktID) + Product, err := s.ProductService.GetProductByID(ProductID) if err != nil { - log.Errorf("Error in CreateBewertung: GetProduktByID failed") + log.Errorf("Error in CreateRating: GetProductByID failed") return nil } - err = RecalculateGesamtratingForProdukt(produkt) + err = RecalculateGesamtratingForProduct(Product) if err != nil { log.Errorf("Recalculation failed") return nil } - entry := log.WithField("ID", produktID) + entry := log.WithField("ID", ProductID) entry.Info("Successfully added new rating to a product.") - entry.Tracef("Stored: %v", produktID) + entry.Tracef("Stored: %v", ProductID) return nil } -func (s *BewertungService) DeleteBewertung(bewertungID uint) error { - bewertung, err := s.ProduktService.GetBewertungByID(bewertungID) +func (s *RatingService) DeleteRating(RatingID uint) error { + Rating, err := s.ProductService.GetRatingByID(RatingID) if err != nil { - log.Errorf("failed to get Produkt: %v", err) + log.Errorf("failed to get Product: %v", err) return nil } - result := db.DB.Delete(&bewertung) + result := db.DB.Delete(&Rating) if result.Error != nil { return result.Error } @@ -50,50 +50,50 @@ func (s *BewertungService) DeleteBewertung(bewertungID uint) error { return nil } -func (s *ProduktService) GetBewertungByID(id uint) (*model.Bewertung, error) { - var bewertung model.Bewertung +func (s *ProductService) GetRatingByID(id uint) (*model.Rating, error) { + var Rating model.Rating - result := db.DB.First(&bewertung, id) + result := db.DB.First(&Rating, id) if result.Error != nil { return nil, result.Error } - return &bewertung, nil + return &Rating, nil } -func (s *ProduktService) ReadBewertungen() ([]model.Bewertung, error) { - var bewertungen []model.Bewertung +func (s *ProductService) ReadRatings() ([]model.Rating, error) { + var Ratings []model.Rating - result := db.DB.Find(&bewertungen) + result := db.DB.Find(&Ratings) if result.Error != nil { return nil, result.Error } - return bewertungen, nil + return Ratings, nil } -func RecalculateGesamtratingForProdukt(produkt *model.Produkt) error { +func RecalculateGesamtratingForProduct(Product *model.Product) error { // Gesamtrating zurücksetzen - produkt.Gesamtrating = 0.0 + Product.Gesamtrating = 0.0 - // Bewertungen für das Produkt aus der Datenbank abrufen - var bewertungen []model.Bewertung - err := db.DB.Where("produkt_id = ?", produkt.ID).Find(&bewertungen).Error + // Ratings für das Product aus der Datenbank abrufen + var Ratings []model.Rating + err := db.DB.Where("Product_id = ?", Product.ID).Find(&Ratings).Error if err != nil { return err } - numRatings := len(bewertungen) + numRatings := len(Ratings) if numRatings > 0 { totalRating := 0 - for _, bewertung := range bewertungen { - totalRating += bewertung.Bewertung + for _, Rating := range Ratings { + totalRating += Rating.Rating } - produkt.Gesamtrating = float64(totalRating) / float64(numRatings) + Product.Gesamtrating = float64(totalRating) / float64(numRatings) } - // Produkt in der Datenbank aktualisieren - err = db.DB.Save(produkt).Error + // Product in der Datenbank aktualisieren + err = db.DB.Save(Product).Error if err != nil { return err } diff --git a/src/gomazon/service/produkt.go b/src/gomazon/service/produkt.go index dc8982e..2114fba 100644 --- a/src/gomazon/service/produkt.go +++ b/src/gomazon/service/produkt.go @@ -5,54 +5,54 @@ import ( "gitlab.reutlingen-university.de/albrecht/gomazon/model" ) -type ProduktService struct{} +type ProductService struct{} -func (s *ProduktService) CreateProdukt(produkt model.Produkt) (*model.Produkt, error) { - result := db.DB.Create(&produkt) +func (s *ProductService) CreateProduct(Product model.Product) (*model.Product, error) { + result := db.DB.Create(&Product) if result.Error != nil { return nil, result.Error } - return &produkt, nil + return &Product, nil } -func (s *ProduktService) ReadProdukte() ([]model.Produkt, error) { - var produkte []model.Produkt +func (s *ProductService) ReadProducts() ([]model.Product, error) { + var Products []model.Product - result := db.DB.Find(&produkte) + result := db.DB.Find(&Products) if result.Error != nil { return nil, result.Error } - return produkte, nil + return Products, nil } -func (s *ProduktService) UpdateProdukt(id uint, produktChanges model.Produkt) (*model.Produkt, error) { - produkt, err := s.GetProduktByID(id) +func (s *ProductService) UpdateProduct(id uint, ProductChanges model.Product) (*model.Product, error) { + Product, err := s.GetProductByID(id) if err != nil { return nil, err } - produkt.Name = produktChanges.Name - produkt.Description = produktChanges.Description - produkt.Preis = produktChanges.Preis - produkt.Bewertungen = produktChanges.Bewertungen + Product.Name = ProductChanges.Name + Product.Description = ProductChanges.Description + Product.Preis = ProductChanges.Preis + Product.Ratings = ProductChanges.Ratings - result := db.DB.Save(&produkt) + result := db.DB.Save(&Product) if result.Error != nil { return nil, result.Error } - return produkt, nil + return Product, nil } -func (s *ProduktService) DeleteProdukt(id uint) error { - produkt, err := s.GetProduktByID(id) +func (s *ProductService) DeleteProduct(id uint) error { + Product, err := s.GetProductByID(id) if err != nil { return err } - result := db.DB.Delete(&produkt) + result := db.DB.Delete(&Product) if result.Error != nil { return result.Error } @@ -60,13 +60,13 @@ func (s *ProduktService) DeleteProdukt(id uint) error { return nil } -func (s *ProduktService) GetProduktByID(id uint) (*model.Produkt, error) { - var produkt model.Produkt +func (s *ProductService) GetProductByID(id uint) (*model.Product, error) { + var Product model.Product - result := db.DB.First(&produkt, id) + result := db.DB.First(&Product, id) if result.Error != nil { return nil, result.Error } - return &produkt, nil + return &Product, nil } diff --git a/src/gomazon/service/warenkorb.go b/src/gomazon/service/warenkorb.go index bd341e5..77b6810 100644 --- a/src/gomazon/service/warenkorb.go +++ b/src/gomazon/service/warenkorb.go @@ -8,68 +8,68 @@ import ( "gorm.io/gorm" ) -type WarenkorbService struct { +type ShoppingCartService struct { BankAccountService *BankAccountService } -// Warenkorb erstellen -func (s *WarenkorbService) CreateWarenkorb(warenkorb model.Warenkorb) (*model.Warenkorb, error) { - // Überprüfen, ob der Warenkorb für den Benutzernamen bereits vorhanden ist - existingWarenkorb := &model.Warenkorb{} - result := db.DB.Where("username = ?", warenkorb.Username).First(existingWarenkorb) +// ShoppingCart erstellen +func (s *ShoppingCartService) CreateShoppingCart(ShoppingCart model.ShoppingCart) (*model.ShoppingCart, error) { + // Überprüfen, ob der ShoppingCart für den Benutzernamen bereits vorhanden ist + existingShoppingCart := &model.ShoppingCart{} + result := db.DB.Where("username = ?", ShoppingCart.Username).First(existingShoppingCart) if result.Error == nil { - return existingWarenkorb, nil + return existingShoppingCart, nil } else if !errors.Is(result.Error, gorm.ErrRecordNotFound) { return nil, result.Error } - // Hier den Code für die Datenbankoperation zum Erstellen des Warenkorbs einfügen - result = db.DB.Create(&warenkorb) + // Hier den Code für die Datenbankoperation zum Erstellen des ShoppingCarts einfügen + result = db.DB.Create(&ShoppingCart) if result.Error != nil { return nil, result.Error } - return &warenkorb, nil + return &ShoppingCart, nil } -// Einzelnes Produkt zum Warenkorb hinzufügen -func (s *WarenkorbService) AddProductToWarenkorb(username string, produktID uint, menge int) (*model.Warenkorb, error) { - warenkorb := &model.Warenkorb{} - result := db.DB.Preload("Positionen").Where("username = ?", username).First(warenkorb) +// Einzelnes Product zum ShoppingCart hinzufügen +func (s *ShoppingCartService) AddProductToShoppingCart(username string, ProductID uint, menge int) (*model.ShoppingCart, error) { + ShoppingCart := &model.ShoppingCart{} + result := db.DB.Preload("Positionen").Where("username = ?", username).First(ShoppingCart) if result.Error != nil { return nil, result.Error } - produkt := &model.Produkt{} - result = db.DB.First(produkt, produktID) + Product := &model.Product{} + result = db.DB.First(Product, ProductID) if result.Error != nil { return nil, result.Error } - gesPreis := produkt.Preis * float64(menge) + gesPreis := Product.Preis * float64(menge) position := model.Position{ Menge: menge, - ProduktId: produkt.ID, - Preis: produkt.Preis, + ProductId: Product.ID, + Preis: Product.Preis, Gesamtpreis: gesPreis, } - warenkorb.Positionen = append(warenkorb.Positionen, position) - warenkorb.Gesamtpreis += position.Gesamtpreis + ShoppingCart.Positionen = append(ShoppingCart.Positionen, position) + ShoppingCart.Gesamtpreis += position.Gesamtpreis - result = db.DB.Save(warenkorb) + result = db.DB.Save(ShoppingCart) if result.Error != nil { return nil, result.Error } - return warenkorb, nil + return ShoppingCart, nil } -// Bezahlfunktion für den Warenkorb -func (s *WarenkorbService) Bezahlen(username string) error { - warenkorb := &model.Warenkorb{} - result := db.DB.Preload("Positionen").Where("username = ?", username).First(warenkorb) +// Bezahlfunktion für den ShoppingCart +func (s *ShoppingCartService) Bezahlen(username string) error { + ShoppingCart := &model.ShoppingCart{} + result := db.DB.Preload("Positionen").Where("username = ?", username).First(ShoppingCart) if result.Error != nil { return result.Error } @@ -80,24 +80,24 @@ func (s *WarenkorbService) Bezahlen(username string) error { } // Überprüfen, ob das Bankkonto ausreichend Guthaben hat - if bankAccount.Balance < warenkorb.Gesamtpreis { + if bankAccount.Balance < ShoppingCart.Gesamtpreis { return errors.New("nicht genügend Guthaben auf dem Bankkonto") } // Banküberweisung durchführen - _, err = s.BankAccountService.UpdateBankAccount(username, -warenkorb.Gesamtpreis) + _, err = s.BankAccountService.UpdateBankAccount(username, -ShoppingCart.Gesamtpreis) if err != nil { return err } - // Einträge im Warenkorb zurücksetzen - for i := range warenkorb.Positionen { - warenkorb.Positionen[i].Menge = 0 + // Einträge im ShoppingCart zurücksetzen + for i := range ShoppingCart.Positionen { + ShoppingCart.Positionen[i].Menge = 0 } - warenkorb.Gesamtpreis = 0.0 + ShoppingCart.Gesamtpreis = 0.0 - result = db.DB.Save(warenkorb) + result = db.DB.Save(ShoppingCart) if result.Error != nil { return result.Error } -- GitLab