fix: 添加购物车时检查购物资格
- 后端 CartHandler.Add 新增购物资格检查 - 后端新增库存检查和最大购买数量检查 - 前端商品详情页添加资格不足提示和视觉反馈 - 显示用户当前资格和所需资格总数 Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
@@ -34,11 +34,61 @@ func (h *CartHandler) Add(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
var cart models.Cart
|
||||
result := utils.DB.Where("user_id = ? AND product_id = ?", userID, req.ProductID).First(&cart)
|
||||
// 获取商品信息
|
||||
var product models.Product
|
||||
if err := utils.DB.First(&product, req.ProductID).Error; err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Product not found"})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查商品是否上架
|
||||
if !product.IsActive {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Product is not available"})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查购物资格
|
||||
if product.RequireCredit {
|
||||
var user models.User
|
||||
utils.DB.First(&user, userID)
|
||||
totalCreditCost := product.CreditCost * req.Quantity
|
||||
if user.PurchaseCredits < totalCreditCost {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Insufficient purchase credits. Required: " + strconv.Itoa(totalCreditCost) + ", Available: " + strconv.Itoa(user.PurchaseCredits)})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 检查库存
|
||||
var inventory models.Inventory
|
||||
if err := utils.DB.Where("product_id = ?", req.ProductID).First(&inventory).Error; err == nil {
|
||||
if inventory.Quantity < req.Quantity {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Insufficient stock. Available: " + strconv.Itoa(inventory.Quantity)})
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 检查购物车中是否已存在该商品
|
||||
var existingCart models.Cart
|
||||
var totalQuantity int
|
||||
result := utils.DB.Where("user_id = ? AND product_id = ?", userID, req.ProductID).First(&existingCart)
|
||||
if result.Error == nil {
|
||||
cart.Quantity += req.Quantity
|
||||
utils.DB.Save(&cart)
|
||||
totalQuantity = existingCart.Quantity + req.Quantity
|
||||
} else {
|
||||
totalQuantity = req.Quantity
|
||||
}
|
||||
|
||||
// 检查最大购买数量
|
||||
if product.MaxPurchase != nil && *product.MaxPurchase > 0 && totalQuantity > *product.MaxPurchase {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Maximum purchase quantity is " + strconv.Itoa(*product.MaxPurchase)})
|
||||
return
|
||||
}
|
||||
|
||||
// 添加或更新购物车
|
||||
var cart models.Cart
|
||||
if result.Error == nil {
|
||||
existingCart.Quantity = totalQuantity
|
||||
utils.DB.Save(&existingCart)
|
||||
cart = existingCart
|
||||
} else {
|
||||
cart = models.Cart{
|
||||
UserID: userID,
|
||||
|
||||
Reference in New Issue
Block a user