fix: add unit type for piece items
This commit is contained in:
@@ -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": "Недостаточно товара на складе"})
|
||||
}
|
||||
|
||||
@@ -70,6 +70,7 @@ func UpdateItem(c *gin.Context) {
|
||||
database.DB.Model(&item).Updates(models.Item{
|
||||
Name: input.Name,
|
||||
Unit: input.Unit,
|
||||
UnitType: input.UnitType,
|
||||
City: input.City,
|
||||
Price: input.Price,
|
||||
})
|
||||
@@ -78,19 +79,24 @@ func UpdateItem(c *gin.Context) {
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
@@ -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"`
|
||||
|
||||
Reference in New Issue
Block a user