File size: 9,659 Bytes
b47934a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 e2e

import (
	"net/http"
	"testing"

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

	api "github.com/openmeterio/openmeter/api/client/go"
	v3sdk "github.com/openmeterio/openmeter/api/v3/client"
)

const unitConfigNotRepresentableCode = "unit_config_not_representable"

// Flow:
//   - v1 plan GET on a unit_config plan β†’ 400 with the typed code (not a stripped 200)
//   - v1 plan GET on a plain plan β†’ 200 (exclusion is content-derived, not blanket)
//   - v1 plan LIST omits the unit_config plan, keeps the plain one, and reports an exact TotalCount
//   - v1 subscribe-by-plan-key from the unit_config plan still succeeds (read β‰  subscribe; OM-399)
//   - v1 subscription GET on that subscription β†’ 400 with the same typed code
func TestV1ReadSurfaceExcludesUnitConfig(t *testing.T) {
	c := newV3Client(t)
	v1 := initClient(t)

	uniq := uniqueKey("ucread")
	meterKey := "ucread_meter_" + uniq
	eventType := "ucread_event_" + uniq
	featureKey := "ucread_feature_" + uniq
	customerKey := "ucread_customer_" + uniq
	subjectKey := "ucread_subject_" + uniq
	ucPlanKey := "ucread_uc_plan_" + uniq
	plainPlanKey := "ucread_plain_plan_" + uniq

	var ucPlan *v3sdk.Plan
	var plainPlan *v3sdk.Plan

	// given:
	// - a unit_config plan (usage-based rate card, divide-by-1000 ceiling) and a plain plan, both
	//   authored and published via v3 (v1 cannot author unit_config).
	runRequired(t, "creates a unit_config plan and a plain plan", func(t *testing.T) {
		meter, err := c.Meters.Create(t.Context(), v3sdk.CreateMeterRequest{
			Key:           meterKey,
			Name:          "UC Read Meter " + uniq,
			Aggregation:   v3sdk.MeterAggregationSum,
			EventType:     eventType,
			ValueProperty: lo.ToPtr("$.value"),
		})
		c.requireStatus(http.StatusCreated, err)
		require.NotNil(t, meter)

		feature, err := c.Features.Create(t.Context(), v3sdk.CreateFeatureRequest{
			Key:   featureKey,
			Name:  "UC Read Feature " + uniq,
			Meter: &v3sdk.FeatureMeterReferenceInput{ID: meter.ID},
		})
		c.requireStatus(http.StatusCreated, err)
		require.NotNil(t, feature)

		cadence := "P1M"
		term := v3sdk.PricePaymentTermInArrears
		price := lo.Must(v3sdk.PriceFromPriceUnit(v3sdk.PriceUnit{
			Amount: "0.10",
		}))
		ucRateCard := v3sdk.RateCardInput{
			Key:            feature.Key,
			Name:           "UC Read Rate Card " + uniq,
			Price:          price,
			BillingCadence: &cadence,
			PaymentTerm:    &term,
			Feature:        &v3sdk.FeatureReference{ID: feature.ID},
			UnitConfig: &v3sdk.UnitConfig{
				Operation:        v3sdk.UnitConfigOperationDivide,
				ConversionFactor: "1000",
				Rounding:         lo.ToPtr(v3sdk.UnitConfigRoundingModeCeiling),
				Precision:        lo.ToPtr(int64(0)),
			},
		}

		createdUC, err := c.Plans.Create(t.Context(), v3sdk.CreatePlanRequest{
			Key:            ucPlanKey,
			Name:           "UC Read Plan " + uniq,
			Currency:       "USD",
			BillingCadence: "P1M",
			Phases: []v3sdk.PlanPhaseInput{{
				Key:       "phase_1",
				Name:      "UC Phase",
				RateCards: []v3sdk.RateCardInput{ucRateCard},
			}},
		})
		c.requireStatus(http.StatusCreated, err)
		require.NotNil(t, createdUC)
		ucPlan, err = c.Plans.Publish(t.Context(), createdUC.ID)
		c.requireStatus(http.StatusOK, err)
		require.NotNil(t, ucPlan)

		createdPlain, err := c.Plans.Create(t.Context(), v3sdk.CreatePlanRequest{
			Key:            plainPlanKey,
			Name:           "Plain Read Plan " + uniq,
			Currency:       "USD",
			BillingCadence: "P1M",
			Phases:         []v3sdk.PlanPhaseInput{validPlanPhase("plain_phase", true /* isLast */)},
		})
		c.requireStatus(http.StatusCreated, err)
		require.NotNil(t, createdPlain)
		plainPlan, err = c.Plans.Publish(t.Context(), createdPlain.ID)
		c.requireStatus(http.StatusOK, err)
		require.NotNil(t, plainPlan)
	})

	// then:
	// - v1 GET on the unit_config plan is rejected with the typed code (not a silently-stripped 200).
	runRequired(t, "v1 plan GET rejects the unit_config plan", func(t *testing.T) {
		resp, err := v1.GetPlanWithResponse(t.Context(), ucPlan.ID, nil)
		require.NoError(t, err)
		require.Equal(t, http.StatusBadRequest, resp.StatusCode(), "body: %s", string(resp.Body))
		require.NotNil(t, resp.ApplicationproblemJSON400)
		assert.Contains(t, string(resp.Body), unitConfigNotRepresentableCode, "the 400 must carry the typed unit_config code")
	})

	// and:
	// - the plain plan is still gettable via v1 (the exclusion is content-derived, not a blanket block).
	runRequired(t, "v1 plan GET returns the plain plan", func(t *testing.T) {
		resp, err := v1.GetPlanWithResponse(t.Context(), plainPlan.ID, nil)
		require.NoError(t, err)
		require.Equal(t, http.StatusOK, resp.StatusCode(), "body: %s", string(resp.Body))
		require.NotNil(t, resp.JSON200)
		assert.Equal(t, plainPlanKey, resp.JSON200.Key)
	})

	// and:
	// - v1 LIST omits the unit_config plan, keeps the plain one, and TotalCount reflects the filtered set
	//   (the exclusion runs at the query layer, before the COUNT β€” so the count stays exact).
	runRequired(t, "v1 plan LIST excludes the unit_config plan with an exact TotalCount", func(t *testing.T) {
		resp, err := v1.ListPlansWithResponse(t.Context(), &api.ListPlansParams{
			Key:      &[]string{ucPlanKey, plainPlanKey},
			PageSize: lo.ToPtr(api.PaginationPageSize(1000)),
		})
		require.NoError(t, err)
		require.Equal(t, http.StatusOK, resp.StatusCode(), "body: %s", string(resp.Body))
		require.NotNil(t, resp.JSON200)

		keys := lo.Map(resp.JSON200.Items, func(p api.Plan, _ int) string { return p.Key })
		assert.NotContains(t, keys, ucPlanKey, "unit_config plan must be excluded from the v1 list")
		assert.Contains(t, keys, plainPlanKey, "plain plan must remain in the v1 list")
		assert.Equal(t, 1, resp.JSON200.TotalCount, "TotalCount must reflect the filtered set, not the raw count")
	})

	// and:
	// - v1 mutations on the unit_config plan are rejected BEFORE any side effect. The guard runs
	//   pre-commit in the service (not in the response mapper), so a 400 means nothing committed β€”
	//   the plan is left exactly as it was. This is the core OM-409 follow-up: no commit-then-400.
	runRequired(t, "v1 plan mutations reject the unit_config plan with no side effect", func(t *testing.T) {
		// archive: the guard runs before the active-status check, so an active plan is still rejected.
		archiveResp, err := v1.ArchivePlanWithResponse(t.Context(), ucPlan.ID)
		require.NoError(t, err)
		require.Equal(t, http.StatusBadRequest, archiveResp.StatusCode(), "body: %s", string(archiveResp.Body))
		assert.Contains(t, string(archiveResp.Body), unitConfigNotRepresentableCode, "archive 400 must carry the typed unit_config code")

		// publish: the guard runs before the publishable-status check.
		publishResp, err := v1.PublishPlanWithResponse(t.Context(), ucPlan.ID)
		require.NoError(t, err)
		require.Equal(t, http.StatusBadRequest, publishResp.StatusCode(), "body: %s", string(publishResp.Body))
		assert.Contains(t, string(publishResp.Body), unitConfigNotRepresentableCode, "publish 400 must carry the typed unit_config code")

		// next: the guard runs before the next draft version is created.
		nextResp, err := v1.NextPlanWithResponse(t.Context(), ucPlan.ID)
		require.NoError(t, err)
		require.Equal(t, http.StatusBadRequest, nextResp.StatusCode(), "body: %s", string(nextResp.Body))
		assert.Contains(t, string(nextResp.Body), unitConfigNotRepresentableCode, "next 400 must carry the typed unit_config code")

		// no side effect: after three rejected mutations the plan is unchanged β€” still the single
		// active version it was published as (a commit-then-400 mapper would have left it archived).
		after, err := c.Plans.Get(t.Context(), ucPlan.ID)
		c.requireStatus(http.StatusOK, err)
		require.NotNil(t, after)
		assert.Equal(t, v3sdk.PlanStatusActive, after.Status, "the plan must remain active β€” no mutation may have committed")
	})

	// and:
	// - a v1 subscription created from the unit_config plan BY KEY still succeeds (read β‰  subscribe; the
	//   server rates it correctly per OM-399, only the read surfaces are restricted).
	var subscriptionID string
	runRequired(t, "v1 subscribe-by-plan-key from the unit_config plan succeeds", func(t *testing.T) {
		customer := CreateCustomerWithSubject(t, v1, customerKey, subjectKey)
		require.NotNil(t, customer)

		timing := &api.SubscriptionTiming{}
		require.NoError(t, timing.FromSubscriptionTimingEnum(api.SubscriptionTimingEnumImmediate))

		body := api.SubscriptionCreate{}
		require.NoError(t, body.FromPlanSubscriptionCreate(api.PlanSubscriptionCreate{
			Timing:     timing,
			CustomerId: lo.ToPtr(customer.Id),
			Plan: api.PlanReferenceInput{
				Key:     ucPlanKey,
				Version: lo.ToPtr(1),
			},
		}))

		resp, err := v1.CreateSubscriptionWithResponse(t.Context(), body)
		require.NoError(t, err)
		require.Equal(t, http.StatusCreated, resp.StatusCode(), "body: %s", string(resp.Body))
		require.NotNil(t, resp.JSON201)
		subscriptionID = resp.JSON201.Id
	})

	// then:
	// - v1 GET on that subscription is rejected with the same typed code (its items carry the unit_config).
	runRequired(t, "v1 subscription GET rejects the unit_config subscription", func(t *testing.T) {
		require.NotEmpty(t, subscriptionID)
		resp, err := v1.GetSubscriptionWithResponse(t.Context(), subscriptionID, nil)
		require.NoError(t, err)
		require.Equal(t, http.StatusBadRequest, resp.StatusCode(), "body: %s", string(resp.Body))
		require.NotNil(t, resp.ApplicationproblemJSON400)
		assert.Contains(t, string(resp.Body), unitConfigNotRepresentableCode, "the 400 must carry the typed unit_config code")
	})
}