You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
91 lines
2.1 KiB
91 lines
2.1 KiB
package logic
|
|
|
|
import (
|
|
"context"
|
|
|
|
"healthapi/internal/model"
|
|
"healthapi/internal/svc"
|
|
"healthapi/internal/types"
|
|
"healthapi/pkg/errorx"
|
|
|
|
"github.com/zeromicro/go-zero/core/logx"
|
|
)
|
|
|
|
type UpdateCartLogic struct {
|
|
logx.Logger
|
|
ctx context.Context
|
|
svcCtx *svc.ServiceContext
|
|
}
|
|
|
|
func NewUpdateCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateCartLogic {
|
|
return &UpdateCartLogic{
|
|
Logger: logx.WithContext(ctx),
|
|
ctx: ctx,
|
|
svcCtx: svcCtx,
|
|
}
|
|
}
|
|
|
|
func (l *UpdateCartLogic) UpdateCart(req *types.UpdateCartReq) (resp *types.CartItem, err error) {
|
|
userID, err := GetUserIDFromCtx(l.ctx)
|
|
if err != nil {
|
|
return nil, errorx.ErrUnauthorized
|
|
}
|
|
|
|
var cartItem model.CartItem
|
|
if err := l.svcCtx.DB.Where("id = ? AND user_id = ?", req.Id, userID).First(&cartItem).Error; err != nil {
|
|
return nil, errorx.NewCodeError(404, "购物车项不存在")
|
|
}
|
|
|
|
// 获取商品信息
|
|
var product model.Product
|
|
if err := l.svcCtx.DB.First(&product, cartItem.ProductID).Error; err != nil {
|
|
return nil, errorx.NewCodeError(404, "商品不存在")
|
|
}
|
|
|
|
price := product.Price
|
|
stock := product.Stock
|
|
skuName := ""
|
|
image := product.MainImage
|
|
|
|
// 如果有 SKU
|
|
if cartItem.SkuID > 0 {
|
|
var sku model.ProductSku
|
|
if err := l.svcCtx.DB.First(&sku, cartItem.SkuID).Error; err == nil {
|
|
price = sku.Price
|
|
stock = sku.Stock
|
|
skuName = sku.Name
|
|
if sku.Image != "" {
|
|
image = sku.Image
|
|
}
|
|
}
|
|
}
|
|
|
|
// 更新数量
|
|
if req.Quantity > 0 {
|
|
if req.Quantity > stock {
|
|
return nil, errorx.NewCodeError(400, "库存不足")
|
|
}
|
|
cartItem.Quantity = req.Quantity
|
|
}
|
|
|
|
// 更新选中状态(使用结构体字段,因为 bool 默认值为 false)
|
|
cartItem.Selected = req.Selected
|
|
|
|
if err := l.svcCtx.DB.Save(&cartItem).Error; err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
resp = &types.CartItem{
|
|
ID: uint(cartItem.ID),
|
|
ProductID: cartItem.ProductID,
|
|
SkuID: cartItem.SkuID,
|
|
ProductName: product.Name,
|
|
SkuName: skuName,
|
|
Image: image,
|
|
Price: price,
|
|
Quantity: cartItem.Quantity,
|
|
Selected: cartItem.Selected,
|
|
Stock: stock,
|
|
}
|
|
return resp, nil
|
|
}
|
|
|