package logic import ( "context" "healthapi/internal/model" "healthapi/internal/svc" "healthapi/internal/types" "healthapi/pkg/errorx" "github.com/zeromicro/go-zero/core/logx" ) type GetCartLogic struct { logx.Logger ctx context.Context svcCtx *svc.ServiceContext } func NewGetCartLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCartLogic { return &GetCartLogic{ Logger: logx.WithContext(ctx), ctx: ctx, svcCtx: svcCtx, } } func (l *GetCartLogic) GetCart() (resp *types.CartResp, err error) { userID, err := GetUserIDFromCtx(l.ctx) if err != nil { return nil, errorx.ErrUnauthorized } var cartItems []model.CartItem l.svcCtx.DB.Where("user_id = ?", userID).Order("created_at DESC").Find(&cartItems) resp = &types.CartResp{ Items: make([]types.CartItem, 0, len(cartItems)), TotalCount: 0, SelectedCount: 0, TotalAmount: 0, } for _, item := range cartItems { // 获取商品信息 var product model.Product if err := l.svcCtx.DB.First(&product, item.ProductID).Error; err != nil { continue // 跳过已下架的商品 } cartItem := types.CartItem{ ID: uint(item.ID), ProductID: item.ProductID, SkuID: item.SkuID, ProductName: product.Name, Image: product.MainImage, Price: product.Price, Quantity: item.Quantity, Selected: item.Selected, Stock: product.Stock, } // 如果有 SKU,获取 SKU 信息 if item.SkuID > 0 { var sku model.ProductSku if err := l.svcCtx.DB.First(&sku, item.SkuID).Error; err == nil { cartItem.SkuName = sku.Name cartItem.Price = sku.Price cartItem.Stock = sku.Stock if sku.Image != "" { cartItem.Image = sku.Image } } } resp.Items = append(resp.Items, cartItem) resp.TotalCount += item.Quantity if item.Selected { resp.SelectedCount += item.Quantity resp.TotalAmount += cartItem.Price * float64(item.Quantity) } } return resp, nil }