diff --git a/backend/handlers/cart_handler.go b/backend/handlers/cart_handler.go index 57f347f..7540f60 100644 --- a/backend/handlers/cart_handler.go +++ b/backend/handlers/cart_handler.go @@ -1,6 +1,8 @@ package handlers import ( + "fmt" + "math" "net/http" "github.com/gin-gonic/gin" @@ -27,6 +29,13 @@ func GetCart(c *gin.Context) { c.JSON(http.StatusOK, cartItems) } +func isValidQuantity(item models.Item, quantity float64) bool { + if item.UnitType == "piece" { + return quantity == math.Trunc(quantity) + } + return true +} + func AddToCart(c *gin.Context) { userID := getUserID(c) @@ -47,6 +56,10 @@ func AddToCart(c *gin.Context) { return } + if !isValidQuantity(item, req.Quantity) { + c.JSON(http.StatusBadRequest, gin.H{"error": fmt.Errorf("товар %s продается поштучно, дробное количество недопустимо", item.Name)}) + } + if req.Quantity > item.Stock { c.JSON(http.StatusBadRequest, gin.H{"error": "Недостаточно товара на складе"}) } diff --git a/backend/handlers/item_handlers.go b/backend/handlers/item_handlers.go index d0aab1f..2dc9317 100644 --- a/backend/handlers/item_handlers.go +++ b/backend/handlers/item_handlers.go @@ -68,29 +68,35 @@ func UpdateItem(c *gin.Context) { } database.DB.Model(&item).Updates(models.Item{ - Name: input.Name, - Unit: input.Unit, - City: input.City, - Price: input.Price, + Name: input.Name, + Unit: input.Unit, + UnitType: input.UnitType, + City: input.City, + Price: input.Price, }) c.JSON(http.StatusOK, item) } func AddItem(c *gin.Context) { - var input models.Item + var item models.Item - if err := c.ShouldBindJSON(&input); err != nil { + if err := c.ShouldBindJSON(&item); err != nil { c.JSON(http.StatusBadRequest, gin.H{"error": "Неверные данные"}) return } - if err := database.DB.Create(&input).Error; err != nil { + if item.UnitType != "weight" && item.UnitType != "piece" { + c.JSON(http.StatusBadRequest, gin.H{"error": "Товар должен быть весовым или штучным"}) + return + } + + if err := database.DB.Create(&item).Error; err != nil { c.JSON(http.StatusInternalServerError, gin.H{"error": "Не удалось создать товар"}) return } - c.JSON(http.StatusCreated, input) + c.JSON(http.StatusCreated, item) } func DeleteItem(c *gin.Context) { diff --git a/backend/models/item.go b/backend/models/item.go index de4cd18..8c5339f 100644 --- a/backend/models/item.go +++ b/backend/models/item.go @@ -7,6 +7,7 @@ type Item struct { Name string `json:"name"` City string `json:"city"` Unit string `json:"unit"` + UnitType string `json:"unit_type" gorm:"default:'weight'"` Price int `json:"price"` Category string `json:"category"` Stock float64 `gorm:"default:0" json:"stock"`