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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
package service_test

import (
	"context"
	"testing"
	"time"

	"github.com/samber/lo"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"

	"github.com/openmeterio/openmeter/openmeter/customer"
	"github.com/openmeterio/openmeter/openmeter/productcatalog"
	"github.com/openmeterio/openmeter/openmeter/subscription"
	subscriptiontestutils "github.com/openmeterio/openmeter/openmeter/subscription/testutils"
	subscriptionworkflow "github.com/openmeterio/openmeter/openmeter/subscription/workflow"
	"github.com/openmeterio/openmeter/openmeter/testutils"
	"github.com/openmeterio/openmeter/pkg/clock"
	"github.com/openmeterio/openmeter/pkg/currencyx"
	"github.com/openmeterio/openmeter/pkg/datetime"
	"github.com/openmeterio/openmeter/pkg/filter"
	"github.com/openmeterio/openmeter/pkg/models"
)

func TestEdit(t *testing.T) {
	type TDeps struct {
		CurrentTime time.Time
		Customer    customer.Customer
		ExamplePlan subscription.Plan
		ServiceDeps subscriptiontestutils.SubscriptionDependencies
		Service     subscription.Service
	}

	tt := []struct {
		Name    string
		Handler func(t *testing.T, deps TDeps)
	}{
		{
			Name: "Should do nothing if no changes",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				require.Nil(t, err)
			},
		},
		{
			Name: "Should error if plan changes",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				require.NotNil(t, spec.Plan)
				// Let's remove the plan reference
				spec.Plan = nil

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				assert.Error(t, err)
				assert.ErrorContains(t, err, "cannot change plan")
			},
		},
		{
			Name: "Should error if customer changes",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				// Let's change the customer reference
				spec.CustomerId = "new-customer-id"

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				assert.Error(t, err)
				assert.ErrorContains(t, err, "cannot change customer")
			},
		},
		{
			Name: "Should error if subscription start changes",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				// Let's change the start time of the subscription
				spec.ActiveFrom = spec.ActiveFrom.Add(time.Hour)

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				assert.Error(t, err)
				assert.ErrorContains(t, err, "cannot change subscription start")
			},
		},
		{
			Name: "Should update contents of future phases when phase start changes",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				_, err = deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's change the start time of the last phase so phase contents must change for both the last and one before last phase
				require.Equal(t, 3, len(spec.Phases))

				pKey := "test_phase_3"
				_, ok := spec.Phases[pKey]
				require.True(t, ok)

				// Let's make sure that the phase we're changing is actually in the future
				st, _ := spec.Phases[pKey].StartAfter.AddTo(sub.ActiveFrom)
				require.True(t, st.After(clock.Now()))

				// Let's make it start one month later
				spec.Phases[pKey].StartAfter, err = spec.Phases[pKey].StartAfter.Add(datetime.MustParseDuration(t, "P1M"))
				require.Nil(t, err)

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				require.Nil(t, err)

				v2, err := deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's validate the update
				subscriptiontestutils.ValidateSpecAndView(t, spec, v2)
			},
		},
		{
			Name: "Should delete item from future phase",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				_, err = deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's delete an item from the 2nd phase
				require.Equal(t, 3, len(spec.Phases))

				pKey := "test_phase_2"
				_, ok := spec.Phases[pKey]
				require.True(t, ok)

				// Let's make sure it has the item we want to delete
				iKey := subscriptiontestutils.ExampleFeatureKey

				v, ok := spec.Phases[pKey].ItemsByKey[iKey]
				require.True(t, ok)
				require.Greater(t, len(v), 0)

				// Let's delete the item
				delete(spec.Phases[pKey].ItemsByKey, iKey)

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				require.Nil(t, err)

				v2, err := deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's validate the update
				subscriptiontestutils.ValidateSpecAndView(t, spec, v2)
			},
		},
		{
			Name: "Should add item to future phase",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				_, err = deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's add an extra item to the last phase
				require.Equal(t, 3, len(spec.Phases))

				pKey := "test_phase_3"
				_, ok := spec.Phases[pKey]
				require.True(t, ok)

				// Let's make sure it doesn't have the item we want to add
				iKey := subscriptiontestutils.ExampleRateCard2.Key()

				_, ok = spec.Phases[pKey].ItemsByKey[iKey]
				require.False(t, ok)

				rc := subscriptiontestutils.ExampleRateCard2

				// Let's add the item
				spec.Phases[pKey].ItemsByKey[iKey] = []*subscription.SubscriptionItemSpec{
					{
						CreateSubscriptionItemInput: subscription.CreateSubscriptionItemInput{
							CreateSubscriptionItemPlanInput: subscription.CreateSubscriptionItemPlanInput{
								PhaseKey: pKey,
								ItemKey:  iKey,
								RateCard: &rc,
							},
							CreateSubscriptionItemCustomerInput: subscription.CreateSubscriptionItemCustomerInput{},
						},
					},
				}

				_, err = deps.Service.Update(ctx, sub.NamespacedID, spec)
				require.Nil(t, err)

				v2, err := deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's validate the update
				subscriptiontestutils.ValidateSpecAndView(t, spec, v2)
			},
		},
		{
			Name: "Should update item entitlement",
			Handler: func(t *testing.T, deps TDeps) {
				ctx, cancel := context.WithCancel(context.Background())
				defer cancel()

				spec, err := subscription.NewSpecFromPlan(deps.ExamplePlan, subscription.CreateSubscriptionCustomerInput{
					Name:          "Test",
					CustomerId:    deps.Customer.ID,
					Currency:      currencyx.Code("USD"),
					ActiveFrom:    deps.CurrentTime,
					BillingAnchor: deps.CurrentTime,
				})
				require.Nil(t, err)

				sub, err := deps.Service.Create(ctx, deps.Customer.Namespace, spec)
				require.Nil(t, err)

				v1, err := deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)
				require.NotEmpty(t, v1.Subscription.ID)

				// Let's validate we have an item with an entitlement template
				require.Equal(t, 3, len(spec.Phases))

				pKey := "test_phase_1"
				_, ok := spec.Phases[pKey]
				require.True(t, ok)

				// Let's make sure it has the item we want to change
				iKey := subscriptiontestutils.ExampleRateCard1.Key()

				v, ok := spec.Phases[pKey].ItemsByKey[iKey]
				require.True(t, ok)
				require.Greater(t, len(v), 0)

				item := v[0]

				// Let's unset the entitlement template
				require.NoError(t, item.RateCard.ChangeMeta(func(m productcatalog.RateCardMeta) (productcatalog.RateCardMeta, error) {
					m.EntitlementTemplate = nil
					return m, nil
				}))

				// Let's add the item
				spec.Phases[pKey].ItemsByKey[iKey] = []*subscription.SubscriptionItemSpec{
					item,
				}

				u, err := deps.Service.Update(ctx, sub.NamespacedID, spec)
				require.Nil(t, err)
				require.NotEmpty(t, u.ID)

				v2, err := deps.Service.GetView(ctx, sub.NamespacedID)
				require.Nil(t, err)

				// Let's validate the update
				subscriptiontestutils.ValidateSpecAndView(t, spec, v2)
			},
		},
	}

	for _, tc := range tt {
		t.Run(tc.Name, func(t *testing.T) {
			currentTime := testutils.GetRFC3339Time(t, "2021-01-01T00:00:00Z")
			clock.SetTime(currentTime)

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

			deps := subscriptiontestutils.NewService(t, dbDeps)
			service := deps.SubscriptionService

			cust := deps.CustomerAdapter.CreateExampleCustomer(t)
			require.NotNil(t, cust)

			_ = deps.FeatureConnector.CreateExampleFeatures(t, deps.ExampleMeterID)
			plan := deps.PlanHelper.CreatePlan(t, subscriptiontestutils.GetExamplePlanInput(t))

			tc.Handler(t, TDeps{
				CurrentTime: currentTime,
				Customer:    *cust,
				ExamplePlan: plan,
				ServiceDeps: deps,
				Service:     service,
			})
		})
	}
}

func TestDeleteScheduledDowngradeCanExpandDeletedSubscriptionForSync(t *testing.T) {
	ctx := t.Context()
	currentTime := time.Date(2026, 5, 15, 12, 0, 0, 0, time.UTC)
	clock.FreezeTime(currentTime)
	defer clock.UnFreeze()

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

	deps := subscriptiontestutils.NewService(t, dbDeps)
	customerEntity := deps.CustomerAdapter.CreateExampleCustomer(t)
	_ = deps.FeatureConnector.CreateExampleFeatures(t, deps.ExampleMeterID)

	billingAnchor := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)
	premiumPlanInput := subscriptiontestutils.GetExamplePlanInput(t)
	premiumPlanInput.Key = "premium-plan"
	premiumPlanInput.Name = "Premium"
	premiumPlan := deps.PlanHelper.CreatePlan(t, premiumPlanInput)

	basicPlanInput := subscriptiontestutils.GetExamplePlanInput(t)
	basicPlanInput.Key = "basic-plan"
	basicPlanInput.Name = "Basic"
	basicPlan := deps.PlanHelper.CreatePlan(t, basicPlanInput)

	var premiumSubscription subscription.SubscriptionView
	var scheduledSubscription subscription.SubscriptionView

	t.Run("given a customer with a premium subscription", func(t *testing.T) {
		// given:
		// - a customer with a premium subscription anchored to the first day of the month
		// - a lower-priced basic plan available for the next billing cycle
		// when:
		// - the premium subscription is created from its plan
		// then:
		// - the active subscription exists
		var err error
		premiumSubscription, err = deps.WorkflowService.CreateFromPlan(ctx, subscriptionworkflow.CreateSubscriptionWorkflowInput{
			ChangeSubscriptionWorkflowInput: subscriptionworkflow.ChangeSubscriptionWorkflowInput{
				Timing: subscription.Timing{
					Custom: &currentTime,
				},
			},
			Namespace:     subscriptiontestutils.ExampleNamespace,
			CustomerID:    customerEntity.ID,
			BillingAnchor: &billingAnchor,
		}, premiumPlan)
		require.NoError(t, err)
		require.NotNil(t, premiumSubscription)
	})

	t.Run("when a downgrade is scheduled for the next billing cycle", func(t *testing.T) {
		// given:
		// - an active premium subscription
		// when:
		// - the customer schedules a downgrade to the basic plan
		// then:
		// - the current subscription is capped
		// - a scheduled basic subscription is created
		currentSubscription, nextSubscription, err := deps.WorkflowService.ChangeToPlan(ctx, premiumSubscription.Subscription.NamespacedID, subscriptionworkflow.ChangeSubscriptionWorkflowInput{
			Timing: subscription.Timing{
				Enum: lo.ToPtr(subscription.TimingNextBillingCycle),
			},
		}, basicPlan)
		require.NoError(t, err)
		require.NotNil(t, currentSubscription.ActiveTo)
		require.NotNil(t, nextSubscription)

		scheduledSubscription = nextSubscription
		require.Equal(t, subscription.SubscriptionStatusScheduled, scheduledSubscription.Subscription.GetStatusAt(clock.Now()))
	})

	t.Run("when the scheduled downgrade is deleted", func(t *testing.T) {
		// given:
		// - a scheduled downgrade subscription
		// when:
		// - the customer cancels the scheduled downgrade
		// then:
		// - the default read path no longer returns the deleted subscription
		// - the deleted subscription can still be listed and expanded for billing-side cleanup
		require.NoError(t, deps.SubscriptionService.Delete(ctx, scheduledSubscription.Subscription.NamespacedID))

		_, err := deps.SubscriptionService.GetView(ctx, scheduledSubscription.Subscription.NamespacedID)
		require.Error(t, err)

		deletedSubscription := getSubscriptionViewIncludingDeleted(t, ctx, deps.SubscriptionService, scheduledSubscription.Subscription.NamespacedID)
		require.Equal(t, scheduledSubscription.Subscription.ID, deletedSubscription.Subscription.ID)
		require.NotNil(t, deletedSubscription.Subscription.DeletedAt)
	})
}

func getSubscriptionViewIncludingDeleted(t *testing.T, ctx context.Context, service subscription.Service, subscriptionID models.NamespacedID) subscription.SubscriptionView {
	t.Helper()

	subscriptions, err := service.List(ctx, subscription.ListSubscriptionsInput{
		Namespaces:     []string{subscriptionID.Namespace},
		ID:             &filter.FilterULID{FilterString: filter.FilterString{Eq: &subscriptionID.ID}},
		IncludeDeleted: true,
	})
	require.NoError(t, err)
	require.Len(t, subscriptions.Items, 1)

	views, err := service.ExpandViews(ctx, subscriptions.Items)
	require.NoError(t, err)
	require.Len(t, views, 1)

	return views[0]
}