File size: 26,697 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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
package addondiff_test

import (
	"context"
	"testing"
	"time"

	"github.com/alpacahq/alpacadecimal"
	"github.com/invopop/gobl/currency"
	"github.com/samber/lo"
	"github.com/stretchr/testify/require"

	"github.com/openmeterio/openmeter/openmeter/productcatalog"
	"github.com/openmeterio/openmeter/openmeter/productcatalog/addon"
	"github.com/openmeterio/openmeter/openmeter/productcatalog/plan"
	"github.com/openmeterio/openmeter/openmeter/subscription"
	subscriptionaddon "github.com/openmeterio/openmeter/openmeter/subscription/addon"
	addondiff "github.com/openmeterio/openmeter/openmeter/subscription/addon/diff"
	"github.com/openmeterio/openmeter/openmeter/subscription/patch"
	subscriptiontestutils "github.com/openmeterio/openmeter/openmeter/subscription/testutils"
	"github.com/openmeterio/openmeter/pkg/clock"
	"github.com/openmeterio/openmeter/pkg/datetime"
	"github.com/openmeterio/openmeter/pkg/models"
)

func TestRestore(t *testing.T) {
	type tcDeps struct {
		deps subscriptiontestutils.SubscriptionDependencies
	}

	withDeps := func(fn func(t *testing.T, deps *tcDeps)) func(t *testing.T) {
		return func(t *testing.T) {
			clock.FreezeTime(now.Add(time.Millisecond))
			defer func() {
				clock.UnFreeze()
				clock.ResetTime()
			}()

			dbDeps := subscriptiontestutils.SetupDBDeps(t)
			defer dbDeps.Cleanup(t)

			deps := subscriptiontestutils.NewService(t, dbDeps)

			fn(t, &tcDeps{
				deps: deps,
			})
		}
	}

	t.Run("Should do nothing if RateCard of addon is not present in the spec", withDeps(func(t *testing.T, deps *tcDeps) {
		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).AddPhase(nil, subscriptiontestutils.ExampleRateCard2.Clone()).Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard1.Clone()),
			models.CadencedModel{
				ActiveFrom: now,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Now let's NOT apply the diff, only restore the diff
		// err = spec.Apply(diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		// require.NoError(t, err)

		restore := env.diffable.GetRestores()
		err := spec.Apply(restore, subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should delete single RateCard that was created by the addon", withDeps(func(t *testing.T, deps *tcDeps) {
		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).AddPhase(nil, subscriptiontestutils.ExampleRateCard2.Clone()).Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard1.Clone()),
			models.CadencedModel{
				ActiveFrom: now,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Now let's apply the diff, then restore the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should delete a single RateCard that was created by the addon and leave in place the RateCard with the same key as that was part of the subscription", withDeps(func(t *testing.T, deps *tcDeps) {
		oneMonth := datetime.MustParseDuration(t, "P1M")

		oneMonthLater, _ := oneMonth.AddTo(now)

		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone(), subscriptiontestutils.ExampleRateCard2.Clone()).Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard1.Clone()),
			models.CadencedModel{
				ActiveFrom: oneMonthLater,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Let's add a manual EndDate to ExampleRateCard2
		spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth
		ogSpec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth

		// Now let's apply the diff, then restore the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should delete a single RateCard from a phase where it was created by the addon but leave RateCard with same key in another phase where it was already present", withDeps(func(t *testing.T, deps *tcDeps) {
		oneMonth := datetime.MustParseDuration(t, "P1M")

		oneMonthLater, _ := oneMonth.AddTo(now)

		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(&oneMonth, subscriptiontestutils.ExampleRateCard1.Clone(), subscriptiontestutils.ExampleRateCard2.Clone()).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard2.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard1.Clone()),
			models.CadencedModel{
				ActiveFrom: oneMonthLater, // will only affect the second phase
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Now let's apply the diff, then restore the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should restore a single RateCard by undoing the effects of the addon RateCard restoring original entitlement template", withDeps(func(t *testing.T, deps *tcDeps) {
		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard5.Clone()), // will add 50 usage
			models.CadencedModel{
				ActiveFrom: now,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Now let's apply the diff, then restore the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should restore a single RateCard and delete subsequent created RateCards", withDeps(func(t *testing.T, deps *tcDeps) {
		oneMonth := datetime.MustParseDuration(t, "P1M")

		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard5.Clone()), // will add 50 usage
			models.CadencedModel{
				ActiveFrom: now,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Let's change the spec so the one item ends a bit early
		spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth
		ogSpec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth

		// Now let's apply the diff, then restore the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should restore a single RateCard and then delete it in the later step", withDeps(func(t *testing.T, deps *tcDeps) {
		// First we add apply an AddonRateCard once,
		// then twice,
		// then remove it once, (which should leave the first addition in place)
		// then again (which should remove the added items)
		oneMonth := datetime.MustParseDuration(t, "P1M")

		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard5.Clone()), // will add 50 usage
			models.CadencedModel{
				ActiveFrom: now,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// We'll need an extra copy of it for the comparisons
		sView, err := deps.deps.SubscriptionService.GetView(context.Background(), env.subView.Subscription.NamespacedID)
		require.NoError(t, err)

		intermediateSpec := sView.AsSpec()

		// Let's change the spec so the one item ends a bit early
		spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth
		ogSpec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth
		intermediateSpec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleFeatureKey][0].ActiveToOverrideRelativeToPhaseStart = &oneMonth

		// Now let's apply the diff twice
		err = spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Now let's restore it once
		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = intermediateSpec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		subscriptiontestutils.SpecsEqual(t, intermediateSpec, spec)

		// Now let's restore it once more
		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should re-combine single split item when restoring", withDeps(func(t *testing.T, deps *tcDeps) {
		oneMonth := datetime.MustParseDuration(t, "P1M")

		oneMonthLater, _ := oneMonth.AddTo(now)

		env := buildSubAndAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard5.Clone()), // will add 50 usage
			models.CadencedModel{
				ActiveFrom: oneMonthLater,
				ActiveTo:   nil,
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Let's apply the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Now let's restore it
		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		// Let's assert that nothing changed
		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should not recombine different original items into one", withDeps(func(t *testing.T, deps *tcDeps) {
		twoMonths := datetime.MustParseDuration(t, "P2M")

		twoMonthsLater, _ := twoMonths.AddTo(now)

		// We need to create the resources separately as we will do an in-between edit
		p, a := subscriptiontestutils.CreatePlanWithAddon(
			t,
			deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				SetMeta(productcatalog.PlanMeta{
					Name:           "Test Plan",
					Key:            "test_plan",
					Version:        1,
					Currency:       currency.USD,
					BillingCadence: datetime.MustParseDuration(t, "P1M"),
					ProRatingConfig: productcatalog.ProRatingConfig{
						Enabled: true,
						Mode:    productcatalog.ProRatingModeProratePrices,
					},
					SettlementMode: productcatalog.CreditThenInvoiceSettlementMode,
				}).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeSingle, subscriptiontestutils.ExampleAddonRateCard5.Clone()),
		)

		sView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now)

		ogItem := sView.Spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleRateCard1.Key()][0]

		require.NoError(t, ogItem.RateCard.ChangeMeta(func(m productcatalog.RateCardMeta) (productcatalog.RateCardMeta, error) {
			m.Name = "Different Name for This one"
			return m, nil
		}))

		// Let's advance some time
		clock.FreezeTime(clock.Now().AddDate(0, 0, 1))

		// Let's make an edit to the sub effective at 1 month
		sView, err := deps.deps.WorkflowService.EditRunning(
			context.Background(),
			sView.Subscription.NamespacedID,
			[]subscription.Patch{
				patch.PatchRemoveItem{
					PhaseKey: "test_phase_1",
					ItemKey:  subscriptiontestutils.ExampleRateCard1.Key(),
				},
				patch.PatchAddItem{
					PhaseKey: "test_phase_1",
					ItemKey:  subscriptiontestutils.ExampleRateCard1.Key(),
					CreateInput: subscription.SubscriptionItemSpec{
						CreateSubscriptionItemInput: subscription.CreateSubscriptionItemInput{
							Annotations: ogItem.Annotations,
							CreateSubscriptionItemPlanInput: subscription.CreateSubscriptionItemPlanInput{
								PhaseKey: "test_phase_1",
								ItemKey:  subscriptiontestutils.ExampleRateCard1.Key(),
								RateCard: ogItem.RateCard,
							},
						},
					},
				},
			},
			subscription.Timing{
				Enum: lo.ToPtr(subscription.TimingNextBillingCycle),
			},
		)
		require.NoError(t, err)

		sViewCpy, err := deps.deps.SubscriptionService.GetView(context.Background(), sView.Subscription.NamespacedID)
		require.NoError(t, err)

		// Let's add the addon
		subsAdd := subscriptiontestutils.CreateAddonForSubscription(t, &deps.deps, sView.Subscription.NamespacedID, a.NamespacedID, models.CadencedModel{
			ActiveFrom: twoMonthsLater,
			ActiveTo:   nil,
		})

		diffable, err := addondiff.GetDiffableFromAddon(sView, subsAdd)
		require.NoError(t, err)

		spec := sView.AsSpec()
		ogSpec := sViewCpy.AsSpec()

		// Now, let's apply the diff
		err = spec.Apply(diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		err = spec.Apply(diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))

	t.Run("Should successfully restore boolean entitlement value", func(t *testing.T) {
		t.Run("When original item HAS boolean entitlement", withDeps(func(t *testing.T, deps *tcDeps) {
			env := buildSubAndAddon(
				t,
				&deps.deps,
				subscriptiontestutils.BuildTestPlanInput(t).
					AddPhase(nil, subscriptiontestutils.ExampleRateCard4ForAddons.Clone()).
					Build(),
				subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
					EffectiveFrom: &now,
				}, productcatalog.AddonInstanceTypeMultiple, subscriptiontestutils.ExampleAddonRateCard6.Clone()),
				models.CadencedModel{
					ActiveFrom: now,
					ActiveTo:   nil,
				},
			)

			spec := env.subView.Spec
			ogSpec := env.subViewCopy.Spec

			// Let's apply the diff twice
			err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			err = spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			// Now let's restore it twice as well
			err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
		}))

		t.Run("When original item DOES NOT have boolean entitlement", withDeps(func(t *testing.T, deps *tcDeps) {
			env := buildSubAndAddon(
				t,
				&deps.deps,
				subscriptiontestutils.BuildTestPlanInput(t).
					AddPhase(nil, subscriptiontestutils.ExampleRateCard5ForAddons.Clone()).
					Build(),
				subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
					EffectiveFrom: &now,
				}, productcatalog.AddonInstanceTypeMultiple, subscriptiontestutils.ExampleAddonRateCard6.Clone()),
				models.CadencedModel{
					ActiveFrom: now,
					ActiveTo:   nil,
				},
			)

			spec := env.subView.Spec
			ogSpec := env.subViewCopy.Spec

			// Let's apply the diff twice
			err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			err = spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			// Now let's restore it twice as well
			err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err)

			subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
		}))
	})

	t.Run("Should respect addon quantity when restoring", withDeps(func(t *testing.T, deps *tcDeps) {
		env := buildSubAndMultiInstanceAddon(
			t,
			&deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil, subscriptiontestutils.ExampleRateCard1.Clone()).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t, productcatalog.EffectivePeriod{
				EffectiveFrom: &now,
			}, productcatalog.AddonInstanceTypeMultiple, subscriptiontestutils.ExampleAddonRateCard5.Clone()),
			[]subscriptionaddon.CreateSubscriptionAddonQuantityInput{
				{
					ActiveFrom: now,
					Quantity:   3,
				},
			},
		)

		spec := env.subView.Spec
		ogSpec := env.subViewCopy.Spec

		// Let's apply the diff
		err := spec.Apply(env.diffable.GetApplies(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		item := spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleAddonRateCard5.Key()][0]
		mt, err := item.RateCard.AsMeta().EntitlementTemplate.AsMetered()
		require.NoError(t, err)

		// Let's check it was properly applied
		require.Equal(t, 250.0, *mt.IssueAfterReset)

		// Now let's restore it
		err = spec.Apply(env.diffable.GetRestores(), subscription.ApplyContext{CurrentTime: now})
		require.NoError(t, err)

		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)

		item = spec.Phases["test_phase_1"].ItemsByKey[subscriptiontestutils.ExampleAddonRateCard5.Key()][0]
		mt, err = item.RateCard.AsMeta().EntitlementTemplate.AsMetered()
		require.NoError(t, err)

		// Let's check it was properly removed
		require.Equal(t, 100.0, *mt.IssueAfterReset)
	}))

	t.Run("Should apply and remove same single instance addon 4 times in a row with slightly progressive times", withDeps(func(t *testing.T, deps *tcDeps) {
		// We will set up a subscriptionAddon which has a series of quantities set:
		// 1st, single quantity with 1 at t1
		// 2nd, two quantities, second with 0 at t2
		// 3rd, single quantity with 1 at t3
		// 4th, two quantities, second with 0 at t4
		// 5th, single quantity with 1 at t5
		// 6th, two quantities, second with 0 at t6
		// 7th, single quantity with 1 at t7
		// 8th, two quantities, second with 0 at t8

		// Each new quantity will only be added after a round of apply and restore

		// Let's start by creating a sub with some addon
		p, add := subscriptiontestutils.CreatePlanWithAddon(
			t,
			deps.deps,
			subscriptiontestutils.BuildTestPlanInput(t).
				AddPhase(nil,
					subscriptiontestutils.ExampleRateCard1.Clone(), // Flat price
					&productcatalog.UsageBasedRateCard{ // Dynamic price
						RateCardMeta: productcatalog.RateCardMeta{
							Key:        subscriptiontestutils.ExampleFeatureKey2,
							Name:       "Dynamic Rate Card 1",
							FeatureKey: &subscriptiontestutils.ExampleFeatureKey2,
							Price: productcatalog.NewPriceFrom(productcatalog.TieredPrice{
								Mode: productcatalog.VolumeTieredPrice,
								Tiers: []productcatalog.PriceTier{
									{
										UpToAmount: lo.ToPtr(alpacadecimal.NewFromInt(100)),
										FlatPrice: &productcatalog.PriceTierFlatPrice{
											Amount: alpacadecimal.NewFromInt(10),
										},
									},
									{
										// UpToAmount: nil for infinity
										UnitPrice: &productcatalog.PriceTierUnitPrice{
											Amount: alpacadecimal.NewFromInt(1),
										},
									},
								},
							}),
						},
						BillingCadence: subscriptiontestutils.ISOMonth,
					},
				).
				Build(),
			subscriptiontestutils.BuildAddonForTesting(t,
				productcatalog.EffectivePeriod{
					EffectiveFrom: &now,
					EffectiveTo:   nil,
				},
				productcatalog.AddonInstanceTypeSingle,
				&productcatalog.UsageBasedRateCard{ // Dynamic price for addon
					RateCardMeta: productcatalog.RateCardMeta{
						Key:        subscriptiontestutils.ExampleFeatureKey3,
						Name:       "Addon Dynamic Rate Card",
						FeatureKey: &subscriptiontestutils.ExampleFeatureKey3,
						Price: productcatalog.NewPriceFrom(productcatalog.TieredPrice{
							Mode: productcatalog.VolumeTieredPrice,
							Tiers: []productcatalog.PriceTier{
								{
									// UpToAmount: nil for infinity
									UnitPrice: &productcatalog.PriceTierUnitPrice{
										Amount: alpacadecimal.NewFromFloat(0.5),
									},
								},
							},
						}),
					},
					BillingCadence: subscriptiontestutils.ISOMonth,
				},
			),
		)

		subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, &deps.deps, p, now)

		subViewCopy, err := deps.deps.SubscriptionService.GetView(context.Background(), subView.Subscription.NamespacedID)
		require.NoError(t, err)

		ogSpec := subViewCopy.AsSpec()

		startTime := clock.Now()

		subsAdd := subscriptiontestutils.CreateMultiInstanceAddonForSubscription(
			t,
			&deps.deps,
			subView.Subscription.NamespacedID,
			add.NamespacedID,
			[]subscriptionaddon.CreateSubscriptionAddonQuantityInput{
				{
					ActiveFrom: startTime,
					Quantity:   1,
				},
			},
		)

		spec := subView.AsSpec() // We can reuse this in all iterations as if everything works as intended it always gets restored

		for idx := range 8 {
			// Lets pass time
			clock.FreezeTime(clock.Now().Add(time.Minute))
			diff, err := addondiff.GetDiffableFromAddon(subView, subsAdd)
			require.NoError(t, err, "failed to get diffable for iteration %d", idx)

			err = spec.Apply(diff.GetApplies(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err, "failed to apply for iteration %d", idx)

			err = spec.Apply(diff.GetRestores(), subscription.ApplyContext{CurrentTime: now})
			require.NoError(t, err, "failed to restore for iteration %d", idx)

			clock.FreezeTime(clock.Now().Add(time.Minute))

			// Finally lets toggle the quantity
			sAdd, err := deps.deps.SubscriptionAddonService.ChangeQuantity(context.Background(), subsAdd.NamespacedID, subscriptionaddon.CreateSubscriptionAddonQuantityInput{
				ActiveFrom: clock.Now(),
				Quantity:   lo.Ternary(idx%2 == 0, 1, 0),
			})
			require.NoError(t, err, "failed to change quantity for iteration %d", idx)

			subsAdd = *sAdd
		}

		subscriptiontestutils.SpecsEqual(t, ogSpec, spec)
	}))
}

type buildRes struct {
	subView     *subscription.SubscriptionView
	subViewCopy *subscription.SubscriptionView
	diffable    addondiff.Diffable
}

// buildSubAndAddon is a test setup helper
func buildSubAndAddon(
	t *testing.T,
	deps *subscriptiontestutils.SubscriptionDependencies,
	planInp plan.CreatePlanInput,
	addonInp addon.CreateAddonInput,
	subsAddCadence models.CadencedModel,
) *buildRes {
	t.Helper()

	p, a := subscriptiontestutils.CreatePlanWithAddon(
		t,
		*deps,
		planInp,
		addonInp,
	)

	subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, deps, p, now)

	subView2, err := deps.SubscriptionService.GetView(context.Background(), subView.Subscription.NamespacedID)
	require.NoError(t, err)

	subsAdd := subscriptiontestutils.CreateAddonForSubscription(t, deps, subView.Subscription.NamespacedID, a.NamespacedID, subsAddCadence)

	diffable, err := addondiff.GetDiffableFromAddon(subView, subsAdd)
	require.NoError(t, err)

	return &buildRes{
		subView:     &subView,
		subViewCopy: &subView2,
		diffable:    diffable,
	}
}

func buildSubAndMultiInstanceAddon(
	t *testing.T,
	deps *subscriptiontestutils.SubscriptionDependencies,
	planInp plan.CreatePlanInput,
	addonInp addon.CreateAddonInput,
	quants []subscriptionaddon.CreateSubscriptionAddonQuantityInput,
) *buildRes {
	t.Helper()

	p, a := subscriptiontestutils.CreatePlanWithAddon(
		t,
		*deps,
		planInp,
		addonInp,
	)

	subView := subscriptiontestutils.CreateSubscriptionFromPlan(t, deps, p, now)

	subView2, err := deps.SubscriptionService.GetView(context.Background(), subView.Subscription.NamespacedID)
	require.NoError(t, err)

	subsAdd := subscriptiontestutils.CreateMultiInstanceAddonForSubscription(t, deps, subView.Subscription.NamespacedID, a.NamespacedID, quants)

	diffable, err := addondiff.GetDiffableFromAddon(subView, subsAdd)
	require.NoError(t, err)

	return &buildRes{
		subView:     &subView,
		subViewCopy: &subView2,
		diffable:    diffable,
	}
}