diff --git a/README.md b/README.md index 3f0f4353b9bd4c83381a3a5a6c23da62a3eab04e..f2db6cd23c212de68c18ef30e5bce8eedc4bb280 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # gomazon ADD Product -curl -H "Content-Type: application/json" -d '{"description":"test","gesamtrating":4.0,"preis":2.38}' localhost:8080/product/new +curl -H "Content-Type: application/json" -d '{"description":"test","totalrating":4.0,"price":2.38}' localhost:8080/product/new Read Product curl localhost:8080/products \ No newline at end of file diff --git a/src/gomazon/handler/produkt.go b/src/gomazon/handler/produkt.go index dcc3a3cf2fdf59491c4dc274154f48e70aeb28f3..8a75d1ac2f8befb7a674101fb21f8ebfea926c24 100644 --- a/src/gomazon/handler/produkt.go +++ b/src/gomazon/handler/produkt.go @@ -35,7 +35,7 @@ func (h *ProductHandler) CreateProduct(c *gin.Context) { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) return } - Product.Gesamtrating = 0.0 + Product.Totalrating = 0.0 // Das Product über den ProductService erstellen createdProduct, err := h.ProductService.CreateProduct(Product) diff --git a/src/gomazon/handler/warenkorb.go b/src/gomazon/handler/warenkorb.go index 67a034e4173147894868d2983ab39ba5e58a5b07..066a826bd494450892f9a56c946d3002b3982278 100644 --- a/src/gomazon/handler/warenkorb.go +++ b/src/gomazon/handler/warenkorb.go @@ -58,7 +58,7 @@ func (h *ShoppingCartHandler) AddProductToShoppingCart(c *gin.Context) { } var addProductData struct { - Menge int `json:"menge" binding:"required"` + Amount int `json:"amount" binding:"required"` } if err := c.ShouldBindJSON(&addProductData); err != nil { @@ -67,7 +67,7 @@ func (h *ShoppingCartHandler) AddProductToShoppingCart(c *gin.Context) { return } - updatedShoppingCart, err := h.ShoppingCartService.AddProductToShoppingCart(username, uint(ProductID), addProductData.Menge) + updatedShoppingCart, err := h.ShoppingCartService.AddProductToShoppingCart(username, uint(ProductID), addProductData.Amount) if err != nil { log.Error("Coud not insert product to Shopping Cart") c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) diff --git a/src/gomazon/model/bewertung.go b/src/gomazon/model/bewertung.go index da96cafdcc726cdc8b626d6e0fcc280c9632c6ec..81d7386c15fe82d06f6173694f075bad66d1d65a 100644 --- a/src/gomazon/model/bewertung.go +++ b/src/gomazon/model/bewertung.go @@ -5,7 +5,7 @@ import "gorm.io/gorm" type Rating struct { gorm.Model //benötigt, weil Ratings auch gelöscht werden sollen Username string `gorm:"notNull"` - Inhalt string `gorm:"notNull"` + Content string `gorm:"notNull"` Rating int `gorm:"notNull"` ProductId uint } diff --git a/src/gomazon/model/position.go b/src/gomazon/model/position.go index 9cc75cc8683af4171db973328565c574484213af..aa2bdd46ff191ed4231ca4d9cdeea4d368140f6f 100644 --- a/src/gomazon/model/position.go +++ b/src/gomazon/model/position.go @@ -4,8 +4,8 @@ import "gorm.io/gorm" type Position struct { gorm.Model - Menge int `gorm:"notNull"` - ProductId uint `gorm:"notNull"` - Preis float64 `gorm:"notNull"` - Gesamtpreis float64 `gorm:"notNull"` + Amount int `gorm:"notNull"` + ProductId uint `gorm:"notNull"` + Price float64 `gorm:"notNull"` + Totalprice float64 `gorm:"notNull"` } diff --git a/src/gomazon/model/produkt.go b/src/gomazon/model/produkt.go index 7c872fad7ffe768df22101b74abc3d68867f1655..57502f899a41caf09438f63757d98d284909c84d 100644 --- a/src/gomazon/model/produkt.go +++ b/src/gomazon/model/produkt.go @@ -4,9 +4,9 @@ import "gorm.io/gorm" 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"` - Ratings []Rating `gorm:"foreignKey:ProductId;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + Name string `gorm:"notNull"` + Description string `gorm:"notNull;size:80"` + Totalrating float64 `gorm:"notNull;default:0.0"` + Price 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 b18b6dc0596918189fd2b32ee059cedcf7dec681..164ea4e246122451723d954e2b9980f948774a60 100644 --- a/src/gomazon/model/warenkorb.go +++ b/src/gomazon/model/warenkorb.go @@ -4,7 +4,7 @@ import "gorm.io/gorm" type ShoppingCart struct { gorm.Model - Positionen []Position `gorm:"foreignKey:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` - Gesamtpreis float64 `gorm:"notNull;default:0.0"` - Username string `gorm:"unique"` + Positionen []Position `gorm:"foreignKey:ID;constraint:OnUpdate:CASCADE,OnDelete:CASCADE"` + Totalprice float64 `gorm:"notNull;default:0.0"` + Username string `gorm:"unique"` } diff --git a/src/gomazon/service/auth.go b/src/gomazon/service/auth.go index 3087e6e3eff3cb0ea4d70a5c2516236690779bde..5df43f9253f5c9832cf3cce7330953ee61d4c0a4 100644 --- a/src/gomazon/service/auth.go +++ b/src/gomazon/service/auth.go @@ -6,6 +6,7 @@ import ( "time" "github.com/dgrijalva/jwt-go" + log "github.com/sirupsen/logrus" ) func GenerateAdminJWTToken(username string, isAdmin bool, expiration time.Time) (string, error) { @@ -20,9 +21,10 @@ func GenerateAdminJWTToken(username string, isAdmin bool, expiration time.Time) // Generiere den Token mit einem geheimen Schlüssel tokenString, err := token.SignedString([]byte("key-replacement")) if err != nil { + log.Error("Stringsigning failed") return "", err } - + log.Info("JWT-Token generated") return tokenString, nil } @@ -31,41 +33,47 @@ func ExtractTokenData(tokenString string) (string, bool, error) { tokenString = strings.TrimPrefix(tokenString, "Bearer ") // Token parsen token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { - // Geheimer Schlüssel für die Token-Validierung return []byte("key-replacement"), nil }) if err != nil { + log.Error("Tokenparsing failed") return "", false, err } // Überprüfen, ob das Token gültig ist if !token.Valid { + log.Error("invalid token") return "", false, fmt.Errorf("invalid token") } if claims, ok := token.Claims.(jwt.MapClaims); ok { expirationTime := time.Unix(int64(claims["exp"].(float64)), 0) if time.Now().After(expirationTime) { - return "", false, fmt.Errorf("token has expired") + log.Errorf("Token has expired - Expiredate: %v - Time now: %v", expirationTime, time.Now()) + return "", false, fmt.Errorf("token has expired - Expiredate: %v - Time now: %v", expirationTime, time.Now()) } } else { + log.Error("Invalid token claims") return "", false, fmt.Errorf("invalid token claims") } // Claims aus dem Token extrahieren claims, ok := token.Claims.(jwt.MapClaims) if !ok { + log.Error("Invalid token claims") return "", false, fmt.Errorf("invalid token claims") } // Benutzername und isAdmin aus den Claims erhalten username, ok := claims["username"].(string) if !ok { + log.Error("Invalid Username claim") return "", false, fmt.Errorf("invalid username claim") } isAdmin, ok := claims["isAdmin"].(bool) if !ok { + log.Error("Invalid isAdmin claim") return "", false, fmt.Errorf("invalid isAdmin claim") } diff --git a/src/gomazon/service/bank.go b/src/gomazon/service/bank.go index ed028837b36292941d6ebeb4d6b7e6c70b20061e..50a330ea2098b9ea76b9b32876dafff3a194deae 100644 --- a/src/gomazon/service/bank.go +++ b/src/gomazon/service/bank.go @@ -26,9 +26,10 @@ func (s *BankAccountService) CreateBankAccount(bankAccount model.BankAccount) (* // Hier den Code für die Datenbankoperation zum Erstellen des Bankkontos einfügen result = db.DB.Create(&bankAccount) if result.Error != nil { + log.Error("Could not create Bankaccount") return nil, result.Error } - + log.Info("Created Bankaccount") return &bankAccount, nil } @@ -38,15 +39,15 @@ func (s *BankAccountService) UpdateBankAccount(username string, amount float64) result := db.DB.Where("username = ?", username).First(bankAccount) if result.Error != nil { if errors.Is(result.Error, gorm.ErrRecordNotFound) { - log.Errorf("Bankkonto mit Benutzernamen %s nicht gefunden", username) + log.Errorf("Bankaccount of User %s not found", username) } return nil, result.Error } // Überprüfen, ob der Betrag zu einem negativen Kontostand führen würde if amount < 0 && bankAccount.Balance+amount < 0 { - log.Error("Abhebungsbetrag übersteigt das Guthaben auf dem Bankkonto") - return nil, fmt.Errorf("der Abhebungsbetrag übersteigt das Guthaben auf dem Bankkonto") + log.Error("Withdrawal amount exceeds the balance on the bank account") + return nil, fmt.Errorf("withdrawal amount exceeds the balance on the bank account") } // Einzahlung oder Abhebung vom Bankkonto durchführen @@ -55,6 +56,7 @@ func (s *BankAccountService) UpdateBankAccount(username string, amount float64) // Bankkonto in einer einzelnen Datenbankoperation speichern result = db.DB.Save(bankAccount) if result.Error != nil { + log.Error("Could not save changes of Bankaccount") return nil, result.Error } @@ -65,8 +67,9 @@ func (s *BankAccountService) GetBankAccountByUsername(username string) (*model.B bankAccount := &model.BankAccount{} result := db.DB.Where("username = ?", username).First(bankAccount) if result.Error != nil { + log.Errorf("Could not find Bankaccount from User %v", username) return nil, result.Error } - + log.Infof("Bankaccount from User %v found", username) return bankAccount, nil } diff --git a/src/gomazon/service/bewertung.go b/src/gomazon/service/bewertung.go index 5cb33112df720f5a77d1b300727a7fb6df25c0f4..8a78251c4910542df87fda82d37a3f398313360a 100644 --- a/src/gomazon/service/bewertung.go +++ b/src/gomazon/service/bewertung.go @@ -15,6 +15,7 @@ func (s *RatingService) CreateRating(ProductID uint, Rating *model.Rating) error result := db.DB.Create(Rating) if result.Error != nil { + log.Error("Could not create Rating") return result.Error } @@ -23,7 +24,7 @@ func (s *RatingService) CreateRating(ProductID uint, Rating *model.Rating) error log.Errorf("Error in CreateRating: GetProductByID failed") return nil } - err = RecalculateGesamtratingForProduct(Product) + err = RecalculateTotalratingForProduct(Product) if err != nil { log.Errorf("Recalculation failed") return nil @@ -44,9 +45,11 @@ func (s *RatingService) DeleteRating(RatingID uint) error { result := db.DB.Delete(&Rating) if result.Error != nil { + log.Error("Could not delete Rating") return result.Error } + log.Info("Successfully deleted Rating") return nil } @@ -55,9 +58,11 @@ func (s *ProductService) GetRatingByID(id uint) (*model.Rating, error) { result := db.DB.First(&Rating, id) if result.Error != nil { + log.Error("Could not find Rating") return nil, result.Error } + log.Info("Found Rating") return &Rating, nil } @@ -66,20 +71,23 @@ func (s *ProductService) ReadRatings() ([]model.Rating, error) { result := db.DB.Find(&Ratings) if result.Error != nil { + log.Error("Failed to load all Ratings") return nil, result.Error } + log.Info("Loaded all Ratings") return Ratings, nil } -func RecalculateGesamtratingForProduct(Product *model.Product) error { - // Gesamtrating zurücksetzen - Product.Gesamtrating = 0.0 +func RecalculateTotalratingForProduct(Product *model.Product) error { + // Totalrating zurücksetzen + Product.Totalrating = 0.0 // 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 { + log.Error("Could not find Product") return err } @@ -89,14 +97,16 @@ func RecalculateGesamtratingForProduct(Product *model.Product) error { for _, Rating := range Ratings { totalRating += Rating.Rating } - Product.Gesamtrating = float64(totalRating) / float64(numRatings) + Product.Totalrating = float64(totalRating) / float64(numRatings) } // Product in der Datenbank aktualisieren err = db.DB.Save(Product).Error if err != nil { + log.Error("Could not save Product") return err } + log.Infof("Successfully recalculated Product %v", Product.ID) return nil } diff --git a/src/gomazon/service/produkt.go b/src/gomazon/service/produkt.go index 2114fba10449b12558cefa6837cc56b2094ed0d5..c39840450634a152809165bc21f17c4528a3de65 100644 --- a/src/gomazon/service/produkt.go +++ b/src/gomazon/service/produkt.go @@ -1,6 +1,7 @@ package service import ( + log "github.com/sirupsen/logrus" "gitlab.reutlingen-university.de/albrecht/gomazon/db" "gitlab.reutlingen-university.de/albrecht/gomazon/model" ) @@ -10,6 +11,7 @@ type ProductService struct{} func (s *ProductService) CreateProduct(Product model.Product) (*model.Product, error) { result := db.DB.Create(&Product) if result.Error != nil { + log.Error("Could not create Product") return nil, result.Error } @@ -21,6 +23,7 @@ func (s *ProductService) ReadProducts() ([]model.Product, error) { result := db.DB.Find(&Products) if result.Error != nil { + log.Error("Could not find Products") return nil, result.Error } @@ -35,11 +38,12 @@ func (s *ProductService) UpdateProduct(id uint, ProductChanges model.Product) (* Product.Name = ProductChanges.Name Product.Description = ProductChanges.Description - Product.Preis = ProductChanges.Preis + Product.Price = ProductChanges.Price Product.Ratings = ProductChanges.Ratings result := db.DB.Save(&Product) if result.Error != nil { + log.Error("Could not save Product") return nil, result.Error } @@ -54,6 +58,7 @@ func (s *ProductService) DeleteProduct(id uint) error { result := db.DB.Delete(&Product) if result.Error != nil { + log.Error("Could not delete Product") return result.Error } @@ -65,6 +70,7 @@ func (s *ProductService) GetProductByID(id uint) (*model.Product, error) { result := db.DB.First(&Product, id) if result.Error != nil { + log.Error("Could not find Product") return nil, result.Error } diff --git a/src/gomazon/service/warenkorb.go b/src/gomazon/service/warenkorb.go index 77b6810c7757b6f25d6e241c0eacbe8f54d17f2f..5ce348c460ef2be49613b6133b773fba09ec5252 100644 --- a/src/gomazon/service/warenkorb.go +++ b/src/gomazon/service/warenkorb.go @@ -3,6 +3,7 @@ package service import ( "errors" + log "github.com/sirupsen/logrus" "gitlab.reutlingen-university.de/albrecht/gomazon/db" "gitlab.reutlingen-university.de/albrecht/gomazon/model" "gorm.io/gorm" @@ -26,43 +27,49 @@ func (s *ShoppingCartService) CreateShoppingCart(ShoppingCart model.ShoppingCart // Hier den Code für die Datenbankoperation zum Erstellen des ShoppingCarts einfügen result = db.DB.Create(&ShoppingCart) if result.Error != nil { + log.Error("Could not create ShoppingCart") return nil, result.Error } + log.Info("Successfully created Shoppingcart") return &ShoppingCart, nil } // Einzelnes Product zum ShoppingCart hinzufügen -func (s *ShoppingCartService) AddProductToShoppingCart(username string, ProductID uint, menge int) (*model.ShoppingCart, error) { +func (s *ShoppingCartService) AddProductToShoppingCart(username string, ProductID uint, amount int) (*model.ShoppingCart, error) { ShoppingCart := &model.ShoppingCart{} result := db.DB.Preload("Positionen").Where("username = ?", username).First(ShoppingCart) if result.Error != nil { + log.Errorf("Could not find Shoppingcart of User %v", username) return nil, result.Error } Product := &model.Product{} result = db.DB.First(Product, ProductID) if result.Error != nil { + log.Errorf("Could not find Product with ID %v", ProductID) return nil, result.Error } - gesPreis := Product.Preis * float64(menge) + gesPrice := Product.Price * float64(amount) position := model.Position{ - Menge: menge, - ProductId: Product.ID, - Preis: Product.Preis, - Gesamtpreis: gesPreis, + Amount: amount, + ProductId: Product.ID, + Price: Product.Price, + Totalprice: gesPrice, } ShoppingCart.Positionen = append(ShoppingCart.Positionen, position) - ShoppingCart.Gesamtpreis += position.Gesamtpreis + ShoppingCart.Totalprice += position.Totalprice result = db.DB.Save(ShoppingCart) if result.Error != nil { + log.Error("Could not save Shoppingcart") return nil, result.Error } + log.Info("Successfully added Product") return ShoppingCart, nil } @@ -71,6 +78,7 @@ func (s *ShoppingCartService) Bezahlen(username string) error { ShoppingCart := &model.ShoppingCart{} result := db.DB.Preload("Positionen").Where("username = ?", username).First(ShoppingCart) if result.Error != nil { + log.Errorf("Could not find Shoppingcart of User %v", username) return result.Error } @@ -80,27 +88,31 @@ func (s *ShoppingCartService) Bezahlen(username string) error { } // Überprüfen, ob das Bankkonto ausreichend Guthaben hat - if bankAccount.Balance < ShoppingCart.Gesamtpreis { - return errors.New("nicht genügend Guthaben auf dem Bankkonto") + if bankAccount.Balance < ShoppingCart.Totalprice { + log.Error("Not enough balance in the bank account") + return errors.New("not enough balance in the bank account") } // Banküberweisung durchführen - _, err = s.BankAccountService.UpdateBankAccount(username, -ShoppingCart.Gesamtpreis) + _, err = s.BankAccountService.UpdateBankAccount(username, -ShoppingCart.Totalprice) if err != nil { + log.Error("UpdateBankAccount failed") return err } // Einträge im ShoppingCart zurücksetzen for i := range ShoppingCart.Positionen { - ShoppingCart.Positionen[i].Menge = 0 + ShoppingCart.Positionen[i].Amount = 0 } - ShoppingCart.Gesamtpreis = 0.0 + ShoppingCart.Totalprice = 0.0 result = db.DB.Save(ShoppingCart) if result.Error != nil { + log.Error("Could not save Shoppingcart") return result.Error } + log.Info("Successfully paid Shoppingcart") return nil }