File size: 6,361 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
219
220
package addondiff

import (
	"fmt"
	"slices"

	"github.com/openmeterio/openmeter/openmeter/subscription"
	subscriptionaddon "github.com/openmeterio/openmeter/openmeter/subscription/addon"
	"github.com/openmeterio/openmeter/pkg/datetime"
	"github.com/openmeterio/openmeter/pkg/models"
	"github.com/openmeterio/openmeter/pkg/timeutil"
)

// getApplyForRateCard returns a function that applies a SubscriptionAddonRateCard to a SubscriptionSpec
func (d *diffable) getApplyForRateCard(rc subscriptionaddon.SubscriptionAddonRateCard) subscription.AppliesToSpec {
	return subscription.NewAppliesToSpec(func(spec *subscription.SubscriptionSpec, _ subscription.ApplyContext) error {
		phaseAtCadenceStart, ok := spec.GetCurrentPhaseAt(d.addon.ActiveFrom)
		if !ok {
			return fmt.Errorf("no phase found at %s", d.addon.ActiveFrom)
		}

		phases := spec.GetSortedPhases()

		lastPhaseKey := phases[len(phases)-1].PhaseKey
		lastPhase, ok := spec.Phases[lastPhaseKey]
		if !ok {
			return fmt.Errorf("no last phase found at %s", lastPhaseKey)
		}

		phaseAtCadenceEnd := lastPhase
		if d.addon.ActiveTo != nil {
			phaseAtCadenceEnd, ok = spec.GetCurrentPhaseAt(*d.addon.ActiveTo)
			if !ok {
				return fmt.Errorf("no phase found at %s", *d.addon.ActiveTo)
			}
		}

		// We're gonna go through all phases, and focus on the period in our cadence.
		// In that period:
		// - there must always be an item for the provided key
		// - any existing item must be updated
		reachedFinal := false
		reachedFirst := false
		for _, phase := range spec.GetSortedPhases() {
			if reachedFinal {
				break
			}

			if phase.PhaseKey == phaseAtCadenceStart.PhaseKey {
				reachedFirst = true
			}

			if phase.PhaseKey == phaseAtCadenceEnd.PhaseKey {
				reachedFinal = true
			}

			if !reachedFirst {
				continue
			}

			// Let's calculate periods
			addPer := d.addon.CadencedModel.AsPeriod()

			pCad, err := spec.GetPhaseCadence(phase.PhaseKey)
			if err != nil {
				return fmt.Errorf("failed to get phase cadence for %s: %w", phase.PhaseKey, err)
			}

			addInPhase := pCad.AsPeriod().Intersection(addPer)
			if addInPhase == nil {
				// If the addon is not effectual in the phase, nothing to do here
				continue
			}

			items := phase.ItemsByKey[rc.AddonRateCard.Key()]

			newItems := make([]*subscription.SubscriptionItemSpec, 0, len(items))

			// We'll use gaps to track any items that need to be created
			gaps := []timeutil.OpenPeriod{
				*addInPhase, // We'll assume there's nothing in the phase, then keep subtracting from it
			}

			// We need to update all items
			for _, item := range items {
				itemPer := item.GetCadence(pCad).AsPeriod()

				{
					// Let's subtract the item from the gaps
					nGaps := make([]timeutil.OpenPeriod, 0, len(gaps))
					for _, g := range gaps {
						nGaps = append(nGaps, g.Difference(itemPer)...)
					}

					slices.SortFunc(nGaps, func(a, b timeutil.OpenPeriod) int {
						if a.From == nil {
							return 1
						}

						if b.From == nil {
							return -1
						}

						return a.From.Compare(*b.From)
					})

					gaps = nGaps
				}

				inter := itemPer.Intersection(addPer)
				if inter == nil {
					newItems = append(newItems, item)

					continue
				}

				// We need to split the item:
				// - the old shape will be kept for the difference
				diff := itemPer.Difference(*inter)

				for _, diffPer := range diff {
					inst := subscription.SubscriptionItemSpec{
						CreateSubscriptionItemInput: subscription.CreateSubscriptionItemInput{
							CreateSubscriptionItemPlanInput: subscription.CreateSubscriptionItemPlanInput{
								PhaseKey: phase.PhaseKey,
								ItemKey:  item.ItemKey,
								RateCard: item.RateCard.Clone(),
							},
							Annotations: item.Annotations,
						},
					}

					d.setItemRelativeCadence(&inst, pCad, diffPer)

					newItems = append(newItems, &inst)
				}

				// - the new shape will be calced for the intersection
				inst := subscription.SubscriptionItemSpec{
					CreateSubscriptionItemInput: subscription.CreateSubscriptionItemInput{
						CreateSubscriptionItemPlanInput: subscription.CreateSubscriptionItemPlanInput{
							PhaseKey: phase.PhaseKey,
							ItemKey:  item.ItemKey,
							RateCard: item.RateCard.Clone(),
						},
						Annotations: item.Annotations,
					},
				}

				if inst.Annotations == nil {
					inst.Annotations = models.Annotations{}
				}

				for range d.addon.Quantity {
					err := rc.Apply(inst.RateCard, inst.Annotations)
					if err != nil {
						return fmt.Errorf("failed to extend rate card %s: %w", rc.AddonRateCard.Key(), err)
					}
				}

				d.setItemRelativeCadence(&inst, pCad, *inter)

				newItems = append(newItems, &inst)
			}

			// Let's create new items for the gaps
			for _, gap := range gaps {
				inst := subscription.SubscriptionItemSpec{
					CreateSubscriptionItemInput: subscription.CreateSubscriptionItemInput{
						CreateSubscriptionItemPlanInput: subscription.CreateSubscriptionItemPlanInput{
							PhaseKey: phase.PhaseKey,
							ItemKey:  rc.AddonRateCard.Key(),
							RateCard: rc.AddonRateCard.RateCard.Clone(),
						},
						Annotations: models.Annotations{},
					},
				}

				for range d.addon.Quantity - 1 {
					err := rc.Apply(inst.RateCard, inst.Annotations)
					if err != nil {
						return fmt.Errorf("failed to extend gap rate card %s: %w", rc.AddonRateCard.Key(), err)
					}
				}

				d.setItemRelativeCadence(&inst, pCad, gap)

				newItems = append(newItems, &inst)
			}

			slices.SortFunc(newItems, func(a, b *subscription.SubscriptionItemSpec) int {
				return a.GetCadence(pCad).ActiveFrom.Compare(b.GetCadence(pCad).ActiveFrom)
			})

			phase.ItemsByKey[rc.AddonRateCard.Key()] = newItems
		}

		return nil
	})
}

// setItemRelativeCadence sets the cadence of an item to match target
func (d *diffable) setItemRelativeCadence(item *subscription.SubscriptionItemSpec, phaseCadence models.CadencedModel, target timeutil.OpenPeriod) {
	if target.From != nil {
		diff := datetime.ISODurationBetween(phaseCadence.ActiveFrom, *target.From)

		if !diff.IsZero() {
			item.ActiveFromOverrideRelativeToPhaseStart = &diff
		}
	}

	if target.To != nil {
		diff := datetime.ISODurationBetween(phaseCadence.ActiveFrom, *target.To)

		if phaseCadence.ActiveTo == nil || !target.To.Equal(*phaseCadence.ActiveTo) {
			item.ActiveToOverrideRelativeToPhaseStart = &diff
		}
	}
}