87 lines
1.7 KiB
Go
87 lines
1.7 KiB
Go
package cart
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
|
|
messages "git.tornberg.me/go-cart-actor/pkg/messages"
|
|
"google.golang.org/protobuf/types/known/anypb"
|
|
)
|
|
|
|
func UpsertSubscriptionDetails(g *CartGrain, m *messages.UpsertSubscriptionDetails) error {
|
|
if m == nil {
|
|
return nil
|
|
}
|
|
|
|
// Helper to get data bytes from Data field
|
|
getDataBytes := func(data *anypb.Any) ([]byte, error) {
|
|
if data == nil {
|
|
return nil, nil
|
|
}
|
|
if len(data.Value) > 0 {
|
|
return data.Value, nil
|
|
}
|
|
if data.TypeUrl != "" {
|
|
return []byte(data.TypeUrl), nil
|
|
}
|
|
return nil, nil
|
|
}
|
|
|
|
// Create new subscription details when Id is nil.
|
|
if m.Id == nil {
|
|
// Validate JSON if provided.
|
|
var meta json.RawMessage
|
|
dataBytes, err := getDataBytes(m.Data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if dataBytes != nil {
|
|
if !json.Valid(dataBytes) {
|
|
return fmt.Errorf("subscription details invalid json")
|
|
}
|
|
meta = json.RawMessage(dataBytes)
|
|
}
|
|
|
|
id := MustNewCartId().String()
|
|
|
|
g.SubscriptionDetails[id] = &SubscriptionDetails{
|
|
Id: id,
|
|
Version: 1,
|
|
OfferingCode: m.OfferingCode,
|
|
SigningType: m.SigningType,
|
|
Meta: meta,
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// Update existing entry.
|
|
existing, ok := g.SubscriptionDetails[*m.Id]
|
|
if !ok {
|
|
return fmt.Errorf("subscription details not found")
|
|
}
|
|
changed := false
|
|
if m.OfferingCode != "" {
|
|
existing.OfferingCode = m.OfferingCode
|
|
changed = true
|
|
}
|
|
if m.SigningType != "" {
|
|
existing.SigningType = m.SigningType
|
|
changed = true
|
|
}
|
|
dataBytes, err := getDataBytes(m.Data)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if dataBytes != nil {
|
|
if !json.Valid(dataBytes) {
|
|
return fmt.Errorf("subscription details invalid json")
|
|
}
|
|
existing.Meta = dataBytes
|
|
changed = true
|
|
}
|
|
if changed {
|
|
existing.Version++
|
|
}
|
|
return nil
|
|
}
|