cake_crm/internal/services/cart/cart.go

110 lines
2.3 KiB
Go
Raw Permalink Normal View History

2024-05-29 20:54:12 +00:00
package cart
2024-05-23 18:10:31 +00:00
import (
"context"
"errors"
"strconv"
2024-09-04 20:54:59 +00:00
"cake_crm/internal/modules/storage"
"cake_crm/proto"
2024-05-23 18:10:31 +00:00
)
type ProductAndCount struct {
product *proto.Product
count int64
}
type Service struct {
storage storage.IStorage
}
func NewService(storage storage.IStorage) *Service {
return &Service{
storage: storage,
}
}
2024-05-29 20:54:12 +00:00
func (s *Service) GetCart(ctx context.Context, items []*proto.OrderItem) (*proto.CartRsp, error) {
var cartAmount int64
var cartAmountOld int64
res := make([]*proto.CartItem, 0, len(items))
2024-05-23 18:10:31 +00:00
for _, item := range items {
product, err := s.storage.GetProduct(ctx, item.ProductId)
if err != nil {
return nil, err
}
2024-05-29 20:24:20 +00:00
amount, amountOld, err := calcItemAmount(
2024-05-23 18:10:31 +00:00
&ProductAndCount{
product: product,
count: item.Count,
},
)
if err != nil {
return nil, err
}
res = append(
res,
2024-05-29 20:54:12 +00:00
&proto.CartItem{
2024-05-23 18:10:31 +00:00
Id: product.Id,
Article: product.Article,
Name: product.Name,
Uri: product.Uri,
Images: product.Images,
Unit: product.Unit,
Inventory: product.Inventory,
Count: item.Count,
Amount: amount,
2024-05-29 20:24:20 +00:00
AmountOld: amountOld,
2024-09-04 20:54:59 +00:00
Discount: amountOld - amount,
2024-05-29 20:24:20 +00:00
Variants: product.Variants,
Labels: product.Labels,
2024-05-23 18:10:31 +00:00
},
)
2024-05-29 20:54:12 +00:00
cartAmount += amount
cartAmountOld += amountOld
2024-05-23 18:10:31 +00:00
}
2024-05-29 20:54:12 +00:00
return &proto.CartRsp{
Items: res,
Amount: cartAmount,
AmountOld: cartAmountOld,
2024-09-04 20:54:59 +00:00
Discount: cartAmountOld - cartAmount,
2024-05-29 20:54:12 +00:00
}, nil
2024-05-23 18:10:31 +00:00
}
2024-05-29 20:24:20 +00:00
func calcItemAmount(item *ProductAndCount) (int64, int64, error) {
variantOld := item.product.Variants[0]
2024-05-23 18:10:31 +00:00
var variant *proto.Variant
for _, v := range item.product.Variants {
check := true
for _, property := range v.Properties {
if property.Name == "min" {
minBorder, err := strconv.ParseInt(property.Value, 10, 64)
if err != nil {
2024-05-29 20:24:20 +00:00
return 0, 0, err
2024-05-23 18:10:31 +00:00
}
if item.count < minBorder {
check = false
}
}
if property.Name == "max" {
maxBorder, err := strconv.ParseInt(property.Value, 10, 64)
if err != nil {
2024-05-29 20:24:20 +00:00
return 0, 0, err
2024-05-23 18:10:31 +00:00
}
if item.count > maxBorder {
check = false
}
}
if check {
variant = v
break
}
}
}
2024-05-29 20:24:20 +00:00
variant.Active = true
2024-05-23 18:10:31 +00:00
if variant == nil {
2024-05-29 20:24:20 +00:00
return 0, 0, errors.New("variant not found")
2024-05-23 18:10:31 +00:00
}
2024-05-29 20:24:20 +00:00
return variant.Price * item.count, variantOld.Price * item.count, nil
2024-05-23 18:10:31 +00:00
}