shortcut quantity change
All checks were successful
Build and Publish / BuildAndDeploy (push) Successful in 2m1s

This commit is contained in:
matst80
2024-11-11 19:01:21 +01:00
parent 33fba76bda
commit 011a8c0e8e
2 changed files with 75 additions and 11 deletions

View File

@@ -160,6 +160,17 @@ func (c *CartGrain) ItemsWithoutDelivery() []int {
return ret
}
func (c *CartGrain) FindItemWithSku(sku string) (*CartItem, bool) {
c.mu.RLock()
defer c.mu.RUnlock()
for _, item := range c.Items {
if item.Sku == sku {
return item, true
}
}
return nil, false
}
func (c *CartGrain) HandleMessage(message *Message, isReplay bool) ([]byte, error) {
if message.TimeStamp == nil {
now := time.Now().Unix()
@@ -173,26 +184,28 @@ func (c *CartGrain) HandleMessage(message *Message, isReplay bool) ([]byte, erro
if !ok {
err = fmt.Errorf("expected AddRequest")
} else {
return c.AddItem(msg.Sku, 1) // extent AddRequest to include quantity
existingItem, found := c.FindItemWithSku(msg.Sku)
if found {
existingItem.Quantity += int(msg.Quantity)
c.TotalPrice += existingItem.Price * int64(msg.Quantity)
} else {
return c.AddItem(msg.Sku, int(msg.Quantity)) // extent AddRequest to include quantity
}
}
case AddItemType:
msg, ok := message.Content.(*messages.AddItem)
if !ok {
err = fmt.Errorf("expected AddItem")
} else {
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 {
existingItem, found := c.FindItemWithSku(msg.Sku)
if found {
existingItem.Quantity += int(msg.Quantity)
c.TotalPrice += existingItem.Price * int64(msg.Quantity)
} else {
c.mu.Lock()
c.lastItemId++
c.Items = append(c.Items, &CartItem{