From d01b6675b44daa52ff99a18b17275e597fb786eb Mon Sep 17 00:00:00 2001 From: matst80 Date: Sun, 10 Nov 2024 22:54:56 +0100 Subject: [PATCH] quantity --- cart-grain.go | 52 +++++++++++++++++++++++++++++++++------------------ 1 file changed, 34 insertions(+), 18 deletions(-) diff --git a/cart-grain.go b/cart-grain.go index 9473581..34a19fd 100644 --- a/cart-grain.go +++ b/cart-grain.go @@ -25,11 +25,12 @@ func (id *CartId) UnmarshalJSON(data []byte) error { } type CartItem struct { - Id int `json:"id"` - Sku string `json:"sku"` - Name string `json:"name"` - Price int64 `json:"price"` - Image string `json:"image"` + Id int `json:"id"` + Sku string `json:"sku"` + Name string `json:"name"` + Price int64 `json:"price"` + Quantity int `json:"qty"` + Image string `json:"image"` } type CartDelivery struct { @@ -64,7 +65,7 @@ func (c *CartGrain) GetLastChange() int64 { return *c.storageMessages[len(c.storageMessages)-1].TimeStamp } -func getItemData(sku string) (*messages.AddItem, error) { +func getItemData(sku string, qty int) (*messages.AddItem, error) { item, err := FetchItem(sku) if err != nil { return nil, err @@ -87,7 +88,7 @@ func getItemData(sku string) (*messages.AddItem, error) { } return &messages.AddItem{ - Quantity: 1, + Quantity: int32(qty), Price: int64(price), Sku: sku, Name: item.Title, @@ -95,8 +96,8 @@ func getItemData(sku string) (*messages.AddItem, error) { }, nil } -func (c *CartGrain) AddItem(sku string) ([]byte, error) { - cartItem, err := getItemData(sku) +func (c *CartGrain) AddItem(sku string, qty int) ([]byte, error) { + cartItem, err := getItemData(sku, qty) if err != nil { return nil, err } @@ -130,21 +131,36 @@ func (c *CartGrain) HandleMessage(message *Message, isReplay bool) ([]byte, erro if !ok { err = fmt.Errorf("expected AddRequest") } else { - return c.AddItem(msg.Sku) + return c.AddItem(msg.Sku, 1) // extent AddRequest to include quantity } case AddItemType: msg, ok := message.Content.(*messages.AddItem) if !ok { err = fmt.Errorf("expected AddItem") } else { - c.lastItemId++ - c.Items = append(c.Items, CartItem{ - Id: c.lastItemId, - Sku: msg.Sku, - Name: msg.Name, - Price: msg.Price, - Image: msg.Image, - }) + found := false + if msg.Quantity < 1 { + return nil, fmt.Errorf("invalid quantity") + } + for _, item := range c.Items { + if item.Sku == msg.Sku { + found = true + item.Quantity += int(msg.Quantity) + c.TotalPrice += item.Price * int64(msg.Quantity) + break + } + } + if !found { + c.lastItemId++ + c.Items = append(c.Items, CartItem{ + Id: c.lastItemId, + + Sku: msg.Sku, + Name: msg.Name, + Price: msg.Price, + Image: msg.Image, + }) + } c.TotalPrice += msg.Price * int64(msg.Quantity) } case RemoveItemType: