File size: 8,760 Bytes
d6f631f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
package subscriptionaddon

import (
	"fmt"
	"reflect"

	"github.com/samber/lo"

	"github.com/openmeterio/openmeter/openmeter/entitlement"
	"github.com/openmeterio/openmeter/openmeter/productcatalog"
	"github.com/openmeterio/openmeter/openmeter/subscription"
	"github.com/openmeterio/openmeter/pkg/models"
)

// Apply applies the addon rate card to the target rate card
func (a SubscriptionAddonRateCard) Apply(target productcatalog.RateCard, annotations models.Annotations) error {
	typ := reflect.TypeOf(target)
	if typ == nil {
		return fmt.Errorf("target must not be nil")
	}

	if typ.Kind() != reflect.Pointer {
		return fmt.Errorf("target must be a pointer")
	}

	if annotations == nil {
		return fmt.Errorf("annotations must not be nil")
	}

	if err := productcatalog.NewRateCardWithOverlay(a.AddonRateCard.RateCard, target).ValidateWith(
		productcatalog.ValidateRateCardsShareSameKey,
		productcatalog.ValidateRateCardsHaveCompatiblePrice,
		productcatalog.ValidateRateCardsHaveCompatibleFeatureKey,
		// productcatalog.ValidateRateCardsHaveCompatibleFeatureID, // FIXME(OM-1337): subscriptions handles feature ID incorrectly
		productcatalog.ValidateRateCardsHaveCompatibleBillingCadence,
		productcatalog.ValidateRateCardsHaveCompatibleEntitlementTemplate,
		productcatalog.ValidateRateCardsHaveCompatibleDiscounts,
		productcatalog.ValidateRateCardsHaveCompatibleUnitConfig,
	); err != nil {
		return err
	}

	return target.ChangeMeta(func(m productcatalog.RateCardMeta) (productcatalog.RateCardMeta, error) {
		aMeta := a.AddonRateCard.AsMeta()
		tMeta := m.Clone()

		// Let's update the price
		if aMeta.Price != nil {
			switch {
			case tMeta.Price == nil:
				m.Price = aMeta.Price
			case tMeta.Price.Type() == productcatalog.FlatPriceType:
				tFlat, _ := tMeta.Price.AsFlat()
				aFlat, _ := aMeta.Price.AsFlat()

				m.Price = productcatalog.NewPriceFrom(productcatalog.FlatPrice{
					Amount:      tFlat.Amount.Add(aFlat.Amount),
					PaymentTerm: tFlat.PaymentTerm,
				})
			default:
				return m, fmt.Errorf("not supported price type: %s", tMeta.Price.Type())
			}
		}

		// Let's update the entitlement template
		if aMeta.EntitlementTemplate != nil {
			switch {
			case tMeta.EntitlementTemplate == nil:
				m.EntitlementTemplate = aMeta.EntitlementTemplate
				if aMeta.EntitlementTemplate.Type() == entitlement.EntitlementTypeBoolean {
					if _, err := subscription.AnnotationParser.SetBooleanEntitlementCount(annotations, 1); err != nil {
						return m, err
					}
				}
			case tMeta.EntitlementTemplate.Type().String() == entitlement.EntitlementTypeBoolean.String():
				var err error
				count := subscription.AnnotationParser.GetBooleanEntitlementCount(annotations)
				annotations, err = subscription.AnnotationParser.SetBooleanEntitlementCount(annotations, count+1)
				if err != nil {
					return m, err
				}
			case tMeta.EntitlementTemplate.Type().String() == entitlement.EntitlementTypeMetered.String():
				tMetered, _ := tMeta.EntitlementTemplate.AsMetered()
				aMetered, _ := aMeta.EntitlementTemplate.AsMetered()

				tMetered.IssueAfterReset = lo.ToPtr(lo.FromPtrOr(tMetered.IssueAfterReset, 0) + lo.FromPtrOr(aMetered.IssueAfterReset, 0))
				m.EntitlementTemplate = productcatalog.NewEntitlementTemplateFrom(tMetered)
			default:
				return m, fmt.Errorf("not supported entitlement template type: %s", tMeta.EntitlementTemplate.Type())
			}
		}

		// Let's update the discounts
		if aMeta.Discounts.Usage != nil {
			targetDiscount := lo.FromPtrOr(tMeta.Discounts.Usage, productcatalog.UsageDiscount{})
			targetDiscount.Quantity = targetDiscount.Quantity.Add(aMeta.Discounts.Usage.Quantity)
			m.Discounts.Usage = &targetDiscount
		}

		return m, nil
	})
}

// Restore restores the addon rate card to the target rate card
// TODO(galexi): instead of instance parameter, change SubscriptionAddonInstance type
func (a SubscriptionAddonRateCard) Restore(target productcatalog.RateCard, annotations models.Annotations, instanceType productcatalog.AddonInstanceType) error {
	// Target has has to be implemented by a pointer otherwise we can't use it as a receiver. Let's check that
	typ := reflect.TypeOf(target)
	if typ == nil {
		return fmt.Errorf("target must not be nil")
	}

	if typ.Kind() != reflect.Pointer {
		return fmt.Errorf("target must be a pointer")
	}

	if annotations == nil {
		return fmt.Errorf("annotations must not be nil")
	}

	if err := productcatalog.NewRateCardWithOverlay(a.AddonRateCard.RateCard, target).ValidateWith(
		productcatalog.ValidateRateCardsShareSameKey,
		// productcatalog.ValidateRateCardsHaveCompatiblePrice, // Its okay, we just need to check if single instance, and if so, then set nill
		productcatalog.ValidateRateCardsHaveCompatibleFeatureKey,
		// productcatalog.ValidateRateCardsHaveCompatibleFeatureID, // FIXME(OM-1337): subscriptions handles feature ID incorrectly
		productcatalog.ValidateRateCardsHaveCompatibleBillingCadence,
		productcatalog.ValidateRateCardsHaveCompatibleEntitlementTemplate,
		productcatalog.ValidateRateCardsHaveCompatibleDiscounts,
		// No unit_config compatibility check here (as with price): restore is teardown and never
		// reapplies it, so gating on it could strand a removable addon if the target's config drifted.
	); err != nil {
		return err
	}

	return target.ChangeMeta(func(m productcatalog.RateCardMeta) (productcatalog.RateCardMeta, error) {
		aMeta := a.AddonRateCard.AsMeta()
		tMeta := m.Clone()

		// Let's update the price
		if aMeta.Price != nil {
			switch {
			case tMeta.Price == nil:
				return m, fmt.Errorf("target price is nil, cannot restore price without addon")
			case tMeta.Price.Type() == productcatalog.FlatPriceType:
				tFlat, _ := tMeta.Price.AsFlat()
				aFlat, _ := aMeta.Price.AsFlat()

				newAmount := tFlat.Amount.Sub(aFlat.Amount)
				if newAmount.IsNegative() {
					return m, fmt.Errorf("restoring flat price would yield a negative amount: %s - %s = %s", tFlat.Amount, aFlat.Amount, newAmount)
				}

				m.Price = productcatalog.NewPriceFrom(productcatalog.FlatPrice{
					Amount:      newAmount,
					PaymentTerm: tFlat.PaymentTerm,
				})
			case instanceType == productcatalog.AddonInstanceTypeSingle:
				m.Price = nil
			default:
				return m, fmt.Errorf("not supported price type: %s", tMeta.Price.Type())
			}
		}

		// Let's update the entitlement template
		if aMeta.EntitlementTemplate != nil {
			switch {
			case tMeta.EntitlementTemplate == nil:
				return m, fmt.Errorf("target entitlement template is nil, cannot restore entitlement template without addon")
			case tMeta.EntitlementTemplate.Type().String() == entitlement.EntitlementTypeBoolean.String():
				count := subscription.AnnotationParser.GetBooleanEntitlementCount(annotations)
				switch {
				case count < 0:
					return m, fmt.Errorf("received invalid entitlement count annotation value: %d", count)
				case count == 0:
					return m, fmt.Errorf("target doesn't have boolean entitlement count annotation while has a boolean entitlement template")
				case count == 1:
					m.EntitlementTemplate = nil
				}

				if _, err := subscription.AnnotationParser.SetBooleanEntitlementCount(annotations, count-1); err != nil {
					return m, err
				}
			case tMeta.EntitlementTemplate.Type().String() == entitlement.EntitlementTypeMetered.String():
				tMetered, _ := tMeta.EntitlementTemplate.AsMetered()
				aMetered, _ := aMeta.EntitlementTemplate.AsMetered()

				newIssueAfterReset := lo.FromPtrOr(tMetered.IssueAfterReset, 0) - lo.FromPtrOr(aMetered.IssueAfterReset, 0)

				if newIssueAfterReset < 0 {
					return m, fmt.Errorf("restoring entitlement template would yield a negative issue after reset: %.0f - %.0f = %.0f", lo.FromPtrOr(tMetered.IssueAfterReset, 0), lo.FromPtrOr(aMetered.IssueAfterReset, 0), newIssueAfterReset)
				}

				tMetered.IssueAfterReset = lo.ToPtr(newIssueAfterReset)
				m.EntitlementTemplate = productcatalog.NewEntitlementTemplateFrom(tMetered)
			default:
				return m, fmt.Errorf("not supported entitlement template type: %s", tMeta.EntitlementTemplate.Type())
			}
		}

		// Let's update the discounts
		if aMeta.Discounts.Usage != nil {
			if target.AsMeta().Discounts.Usage == nil {
				return m, fmt.Errorf("target doesn't have usage discount while addon has a usage discount template")
			}

			targetDiscount := target.AsMeta().Discounts.Usage.Clone()
			if targetDiscount.Quantity.LessThan(aMeta.Discounts.Usage.Quantity) {
				return m, fmt.Errorf("target has %.0f usage discount which is less than addon's %.0f", targetDiscount.Quantity.InexactFloat64(), aMeta.Discounts.Usage.Quantity.InexactFloat64())
			}

			targetDiscount.Quantity = targetDiscount.Quantity.Sub(aMeta.Discounts.Usage.Quantity)
			m.Discounts.Usage = &targetDiscount
		}

		return m, nil
	})
}