This commit is contained in:
matst80
2024-11-14 22:53:32 +01:00
parent 0870a37d90
commit 69d92716c3
10 changed files with 283 additions and 47 deletions

View File

@@ -8,6 +8,7 @@ import (
"time"
messages "git.tornberg.me/go-cart-actor/proto"
klarna "github.com/Flaconi/go-klarna"
)
type CartId [16]byte
@@ -221,6 +222,11 @@ func (c *CartGrain) FindItemWithSku(sku string) (*CartItem, bool) {
return nil, false
}
func GetTaxAmount(total int, tax int) int {
taxD := 10000 / float64(tax)
return int(float64(total) / float64((1 + taxD)))
}
func (c *CartGrain) HandleMessage(message *Message, isReplay bool) (*FrameWithPayload, error) {
if message.TimeStamp == nil {
now := time.Now().Unix()
@@ -384,7 +390,52 @@ func (c *CartGrain) HandleMessage(message *Message, isReplay bool) (*FrameWithPa
break
}
}
}
case CreateCheckoutOrderType:
msg, ok := message.Content.(*messages.CreateCheckoutOrder)
if !ok {
err = fmt.Errorf("expected CreateCheckoutOrder")
} else {
orderLines := make([]*klarna.Line, 0, len(c.Items))
totalTax := 0
for _, item := range c.Items {
total := int(item.Price) * item.Quantity
taxAmount := GetTaxAmount(total, item.Tax)
totalTax += taxAmount
orderLines = append(orderLines, &klarna.Line{
Type: "physical",
Reference: item.Sku,
Name: item.Name,
Quantity: item.Quantity,
UnitPrice: int(item.Price),
TaxRate: int(item.Tax),
QuantityUnit: "st",
TotalAmount: total,
TotalTaxAmount: taxAmount,
ImageURL: item.Image,
})
}
order := klarna.CheckoutOrder{
PurchaseCountry: "SE",
PurchaseCurrency: "SEK",
Locale: "sv-se",
OrderAmount: int(c.TotalPrice),
OrderTaxAmount: totalTax,
OrderLines: orderLines,
MerchantReference1: c.Id.String(),
MerchantURLS: &klarna.CheckoutMerchantURLS{
Terms: msg.Terms,
Checkout: msg.Checkout,
Confirmation: msg.Confirmation,
Push: msg.Push,
},
}
orderPayload, err := json.Marshal(order)
if err != nil {
return nil, err
}
result := MakeFrameWithPayload(RemoteCreateOrderReply, 200, orderPayload)
return &result, nil
}
default:
err = fmt.Errorf("unknown message type %d", message.Type)