Skip to content

Commit

Permalink
refactor(subs): remove inactive items from the current phase in api r…
Browse files Browse the repository at this point in the history
…esponse
  • Loading branch information
GAlexIHU committed Jan 22, 2025
1 parent acc207f commit 579f5ec
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 1 deletion.
2 changes: 1 addition & 1 deletion openmeter/productcatalog/subscription/http/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func (h *handler) GetSubscription() GetSubscriptionHandler {
return def, err
}

return MapSubscriptionViewToAPI(view.WithoutItemHistory())
return MapSubscriptionViewToAPI(view.WithOnlyActivesInCurrentPhase())
},
commonhttp.JSONResponseEncoderWithStatus[GetSubscriptionResponse](http.StatusOK),
httptransport.AppendOptions(
Expand Down
29 changes: 29 additions & 0 deletions openmeter/subscription/subscriptionview.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
customerentity "github.com/openmeterio/openmeter/openmeter/customer/entity"
"github.com/openmeterio/openmeter/openmeter/entitlement"
meteredentitlement "github.com/openmeterio/openmeter/openmeter/entitlement/metered"
"github.com/openmeterio/openmeter/pkg/clock"
"github.com/openmeterio/openmeter/pkg/convert"
"github.com/openmeterio/openmeter/pkg/datex"
"github.com/openmeterio/openmeter/pkg/models"
Expand Down Expand Up @@ -57,6 +58,7 @@ func (s *SubscriptionView) Validate(includePhases bool) error {
return nil
}

// WithoutItemHistory returns a copy of the SubscriptionView with only the last item present for each key.
func (v SubscriptionView) WithoutItemHistory() SubscriptionView {
v2 := v
for i, phase := range v.Phases {
Expand All @@ -73,6 +75,33 @@ func (v SubscriptionView) WithoutItemHistory() SubscriptionView {
return v2
}

func (v SubscriptionView) WithOnlyActivesInCurrentPhase() SubscriptionView {
v2 := v.WithoutItemHistory()

// If there is a current phase, lets remove all inactive items from that
current, ok := v.Spec.GetCurrentPhaseAt(clock.Now())
if ok {
for i, phase := range v.Phases {
if phase.SubscriptionPhase.Key == current.PhaseKey {
phase2 := phase
phase2.ItemsByKey = make(map[string][]SubscriptionItemView)

for key, items := range phase.ItemsByKey {
for _, item := range items {
if item.SubscriptionItem.IsActiveAt(clock.Now()) {
phase2.ItemsByKey[key] = append(phase2.ItemsByKey[key], item)
}
}
}

v2.Phases[i] = phase2
}
}
}

return v2
}

type SubscriptionPhaseView struct {
SubscriptionPhase SubscriptionPhase `json:"subscriptionPhase"`
Spec SubscriptionPhaseSpec `json:"spec"`
Expand Down

0 comments on commit 579f5ec

Please sign in to comment.