@@ -0,0 +1,93 @@
|
||||
package card
|
||||
|
||||
import (
|
||||
"cake_crm/internal/modules/storage"
|
||||
"cake_crm/proto"
|
||||
"context"
|
||||
"errors"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type ProductAndCount struct {
|
||||
product *proto.Product
|
||||
count int64
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
storage storage.IStorage
|
||||
}
|
||||
|
||||
func NewService(storage storage.IStorage) *Service {
|
||||
return &Service{
|
||||
storage: storage,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) GetCard(ctx context.Context, items []*proto.OrderItem) ([]*proto.CardItem, error) {
|
||||
res := make([]*proto.CardItem, 0, len(items))
|
||||
for _, item := range items {
|
||||
product, err := s.storage.GetProduct(ctx, item.ProductId)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
amount, err := calcItemAmount(
|
||||
&ProductAndCount{
|
||||
product: product,
|
||||
count: item.Count,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
res = append(
|
||||
res,
|
||||
&proto.CardItem{
|
||||
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,
|
||||
},
|
||||
)
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
func calcItemAmount(item *ProductAndCount) (int64, error) {
|
||||
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 {
|
||||
return 0, err
|
||||
}
|
||||
if item.count < minBorder {
|
||||
check = false
|
||||
}
|
||||
}
|
||||
if property.Name == "max" {
|
||||
maxBorder, err := strconv.ParseInt(property.Value, 10, 64)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
if item.count > maxBorder {
|
||||
check = false
|
||||
}
|
||||
}
|
||||
if check {
|
||||
variant = v
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
if variant == nil {
|
||||
return 0, errors.New("variant not found")
|
||||
}
|
||||
return variant.Price * item.count, nil
|
||||
}
|
||||
Reference in New Issue
Block a user