Repository navigation
feat(api): add settlement mode to v1 api handlers - #4044
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds a CreditConfiguration flag to app config, wires it through DI and the router, and threads it into plan and subscription handlers which now reject requests using settlementMode "credit_only" when credits are disabled; mappings, plan equality, and tests updated accordingly. Changes
Sequence Diagram(s)mermaid Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (3)
app/config/config.go (1)
37-37: Consider addingCredit.Validate()to theValidate()method.I noticed that
Configuration.Validate()callsc.Customer.Validate()(line 163-165) but doesn't callc.Credit.Validate(). While the currentCreditConfiguration.Validate()is a no-op, adding the call maintains consistency and future-proofs the code if validation logic is added later.♻️ Suggested addition
Add this somewhere in the
Validate()method (e.g., after the Customer validation block):if err := c.Credit.Validate(); err != nil { errs = append(errs, errorsx.WithPrefix(err, "credit")) }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/config/config.go` at line 37, Configuration.Validate currently calls c.Customer.Validate() but omits c.Credit.Validate(), which risks missing future credit validation; update the Validate method (Configuration.Validate) to call c.Credit.Validate() and, on error, append it to errs using errorsx.WithPrefix(err, "credit") (mirroring the existing pattern used for c.Customer.Validate()) so credit validation is consistently handled.openmeter/productcatalog/plan/httpdriver/credit_test.go (1)
109-113: Nice test coverage — one extra assertion would make it even tighter.Could we also assert whether
CreatePlanwas called? That would explicitly prove the disabled path short-circuits before hitting the service.💡 Suggested tweak
for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { + createPlanCalled := false svc := &stubPlanService{ createPlan: func(_ context.Context, params plan.CreatePlanInput) (*plan.Plan, error) { + createPlanCalled = true return stubPlan(namespace, params.SettlementMode), nil }, } @@ require.Equal(t, tt.wantStatusCode, rec.Code, "response body: %s", rec.Body.String()) if !tt.creditEnabled { assert.Contains(t, rec.Body.String(), "credits are not enabled on this deployment of OpenMeter") + assert.False(t, createPlanCalled, "service should not be called when credit is disabled") + } else { + assert.True(t, createPlanCalled, "service should be called when credit is enabled") } }) }As per coding guidelines "
**/*_test.go: Make sure the tests are comprehensive and cover the changes."Also applies to: 125-131
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/plan/httpdriver/credit_test.go` around lines 109 - 113, Add an assertion that the stubbed service's CreatePlan path was invoked (or not) to prove the disabled path short-circuits: modify the stubPlanService used in credit_test.go to record calls to the createPlan function (e.g., increment a counter or set a boolean when createPlan is executed) and then assert on that counter/flag after the request—for the disabled-case test assert it remained zero/false, and for the enabled-case test assert it was called once/true; update both occurrences that construct stubPlanService (the createPlan closures around the current stubPlan(namespace, params.SettlementMode) returns, including the similar block at the other test region) to include this call-tracking and corresponding assertions.openmeter/productcatalog/plan/httpdriver/plan.go (1)
126-126: Optional: centralize the repeated “credits are not enabled…” error message.Tiny maintainability nit — this literal now appears in multiple handlers (
openmeter/productcatalog/plan/httpdriver/plan.go,openmeter/productcatalog/subscription/http/create.go,openmeter/productcatalog/subscription/http/change.go). A shared constant/helper would avoid drift later.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/plan/httpdriver/plan.go` at line 126, The repeated literal "credits are not enabled on this deployment of OpenMeter" should be centralized: add a single exported constant (e.g. CreditsNotEnabledMsg) or a small helper function (e.g. NewCreditsNotEnabledError() that returns models.NewGenericValidationError(fmt.Errorf(CreditsNotEnabledMsg))) in a shared package (productcatalog or a new errors package), then replace the inline string in plan.go (where CreatePlanRequest error is created via models.NewGenericValidationError), subscription/http/create.go and subscription/http/change.go with the new constant/helper so all three locations reference the same source of truth.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/productcatalog/subscription/http/credit_test.go`:
- Around line 199-211: Remove the redundant Credit configuration from the
handler construction: in the NewHandler call that builds a
httpdriver.HandlerConfig, drop the Credit:
appconfig.CreditConfiguration{Enabled: tt.creditEnabled} field and rely solely
on CreateSubscription().With(appconfig.CreditConfiguration{Enabled:
tt.creditEnabled}) to supply the credit config at request time; this keeps
NewHandler/HandlerConfig and the CreateSubscription().With(...) usage consistent
and avoids duplicate config application.
---
Nitpick comments:
In `@app/config/config.go`:
- Line 37: Configuration.Validate currently calls c.Customer.Validate() but
omits c.Credit.Validate(), which risks missing future credit validation; update
the Validate method (Configuration.Validate) to call c.Credit.Validate() and, on
error, append it to errs using errorsx.WithPrefix(err, "credit") (mirroring the
existing pattern used for c.Customer.Validate()) so credit validation is
consistently handled.
In `@openmeter/productcatalog/plan/httpdriver/credit_test.go`:
- Around line 109-113: Add an assertion that the stubbed service's CreatePlan
path was invoked (or not) to prove the disabled path short-circuits: modify the
stubPlanService used in credit_test.go to record calls to the createPlan
function (e.g., increment a counter or set a boolean when createPlan is
executed) and then assert on that counter/flag after the request—for the
disabled-case test assert it remained zero/false, and for the enabled-case test
assert it was called once/true; update both occurrences that construct
stubPlanService (the createPlan closures around the current stubPlan(namespace,
params.SettlementMode) returns, including the similar block at the other test
region) to include this call-tracking and corresponding assertions.
In `@openmeter/productcatalog/plan/httpdriver/plan.go`:
- Line 126: The repeated literal "credits are not enabled on this deployment of
OpenMeter" should be centralized: add a single exported constant (e.g.
CreditsNotEnabledMsg) or a small helper function (e.g.
NewCreditsNotEnabledError() that returns
models.NewGenericValidationError(fmt.Errorf(CreditsNotEnabledMsg))) in a shared
package (productcatalog or a new errors package), then replace the inline string
in plan.go (where CreatePlanRequest error is created via
models.NewGenericValidationError), subscription/http/create.go and
subscription/http/change.go with the new constant/helper so all three locations
reference the same source of truth.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 4ca56412-aab0-414a-bfe2-a102701b482f
📒 Files selected for processing (17)
app/common/config.goapp/config/config.goapp/config/config_test.goapp/config/credit.gocmd/server/main.goopenmeter/productcatalog/plan.goopenmeter/productcatalog/plan/httpdriver/credit_test.goopenmeter/productcatalog/plan/httpdriver/mapping.goopenmeter/productcatalog/plan/httpdriver/plan.goopenmeter/productcatalog/subscription/http/change.goopenmeter/productcatalog/subscription/http/create.goopenmeter/productcatalog/subscription/http/credit_test.goopenmeter/productcatalog/subscription/http/handler.goopenmeter/productcatalog/subscription/http/mapping.goopenmeter/server/router/plan.goopenmeter/server/router/router.goopenmeter/server/router/subscription.go
28477dd to
c46bb08
Compare
There was a problem hiding this comment.
🧹 Nitpick comments (1)
openmeter/productcatalog/plan/httpdriver/credit_test.go (1)
77-85: Add one more case to prove the guard iscredit_only-specific.Right now both rows send
credit_only. A third case (creditEnabled=false+ non-credit settlement mode) would guard against accidentally rejecting all settlement modes when credits are off.Suggested test extension
const planCreateCreditOnlyBody = `{ "key": "test-plan", "name": "Test Plan", "currency": "USD", "billingCadence": "P1M", "settlementMode": "credit_only", "phases": [{"key": "default", "name": "Default Phase", "rateCards": []}] }` + +const planCreateInArrearsBody = `{ + "key": "test-plan", + "name": "Test Plan", + "currency": "USD", + "billingCadence": "P1M", + "settlementMode": "in_arrears", + "phases": [{"key": "default", "name": "Default Phase", "rateCards": []}] +}` tests := []struct { name string creditEnabled bool + body string wantStatusCode int }{ { name: "credit disabled: credit_only settlement mode is rejected", creditEnabled: false, + body: planCreateCreditOnlyBody, wantStatusCode: http.StatusBadRequest, }, { name: "credit enabled: credit_only settlement mode is allowed", creditEnabled: true, + body: planCreateCreditOnlyBody, wantStatusCode: http.StatusCreated, }, + { + name: "credit disabled: in_arrears settlement mode is allowed", + creditEnabled: false, + body: planCreateInArrearsBody, + wantStatusCode: http.StatusCreated, + }, } ... -req := httptest.NewRequest(http.MethodPost, "/api/v1/plans", bytes.NewBufferString(planCreateCreditOnlyBody)) +req := httptest.NewRequest(http.MethodPost, "/api/v1/plans", bytes.NewBufferString(tt.body))As per coding guidelines,
**/*_test.go: "Make sure the tests are comprehensive and cover the changes."Also applies to: 90-105, 127-135
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@openmeter/productcatalog/plan/httpdriver/credit_test.go` around lines 77 - 85, Add a third test case that proves the guard is specific to "credit_only": when creditEnabled=false but the plan's settlementMode is a non-credit value (e.g., "invoice" or "cash"), the request should not be rejected. Create a new JSON test payload (e.g., planCreateNonCreditBody) with settlementMode set to a non-credit string and use it in the same test table/rows where planCreateCreditOnlyBody is used, asserting the expected success/accept behavior; mirror this addition in the other related test blocks referenced (the assertions around the ranges that start at lines ~90-105 and ~127-135) so all cases cover creditEnabled=true/false × settlementMode credit_only/non-credit.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@openmeter/productcatalog/plan/httpdriver/credit_test.go`:
- Around line 77-85: Add a third test case that proves the guard is specific to
"credit_only": when creditEnabled=false but the plan's settlementMode is a
non-credit value (e.g., "invoice" or "cash"), the request should not be
rejected. Create a new JSON test payload (e.g., planCreateNonCreditBody) with
settlementMode set to a non-credit string and use it in the same test table/rows
where planCreateCreditOnlyBody is used, asserting the expected success/accept
behavior; mirror this addition in the other related test blocks referenced (the
assertions around the ranges that start at lines ~90-105 and ~127-135) so all
cases cover creditEnabled=true/false × settlementMode credit_only/non-credit.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b4d9a7ba-c7ed-49aa-b99a-d3c7f35e1f21
📒 Files selected for processing (4)
app/config/config.goapp/config/credit.goopenmeter/productcatalog/plan/httpdriver/credit_test.goopenmeter/productcatalog/subscription/http/credit_test.go
✅ Files skipped from review due to trivial changes (2)
- app/config/credit.go
- openmeter/productcatalog/subscription/http/credit_test.go
There was a problem hiding this comment.
🧹 Nitpick comments (1)
e2e/productcatalog_test.go (1)
1200-1211: Consider validating the error message content.The test correctly checks for HTTP 400, but verifying the error message would ensure the right validation triggered (not some other 400 error). This would make the test more robust against future changes.
💡 Optional: Assert error message content
res, err := client.CreatePlanWithResponse(ctx, api.PlanCreate{ Key: "test_plan_settlement_credit_only", Name: "Credit Only Plan", Currency: "USD", BillingCadence: "P1M", SettlementMode: lo.ToPtr(api.BillingSettlementModeCreditOnly), Phases: []api.PlanPhase{defaultPhase}, }) require.Nil(t, err) assert.Equal(t, 400, res.StatusCode(), "received the following body: %s", res.Body) + require.NotNil(t, res.ApplicationproblemJSON400) + assert.Contains(t, res.ApplicationproblemJSON400.Detail, "credits are not enabled") })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@e2e/productcatalog_test.go` around lines 1200 - 1211, Enhance the "Should reject a plan with credit_only settlement mode when credit is disabled" test by asserting the returned error message/validation in the response body from client.CreatePlanWithResponse (res) in addition to the 400 status; locate the test that builds api.PlanCreate and after require.Nil(t, err) and assert.Equal(t, 400, res.StatusCode()) parse res.Body or use the response helper to extract the error payload and assert it contains the expected validation text (e.g., a message or code indicating credits are disabled or settlement mode is invalid) so the test ensures the specific validation triggered rather than any generic 400.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@e2e/productcatalog_test.go`:
- Around line 1200-1211: Enhance the "Should reject a plan with credit_only
settlement mode when credit is disabled" test by asserting the returned error
message/validation in the response body from client.CreatePlanWithResponse (res)
in addition to the 400 status; locate the test that builds api.PlanCreate and
after require.Nil(t, err) and assert.Equal(t, 400, res.StatusCode()) parse
res.Body or use the response helper to extract the error payload and assert it
contains the expected validation text (e.g., a message or code indicating
credits are disabled or settlement mode is invalid) so the test ensures the
specific validation triggered rather than any generic 400.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 65a6feb9-7fb9-486d-bdd0-036b9103ab83
📒 Files selected for processing (1)
e2e/productcatalog_test.go
9d6aebd to
07d9844
Compare
07d9844 to
303f180
Compare
303f180 to
eb3e295
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@openmeter/productcatalog/plan.go`:
- Around line 298-300: The new SettlementMode comparison in Plan equality
requires that the update-noop guard in UpdatePlanInput.Equal also compare
settlement mode; update the UpdatePlanInput.Equal(...) method (in
openmeter/productcatalog/plan/service.go) to include a check that the incoming
UpdatePlanInput.SettlementMode equals the existing Plan.SettlementMode (handling
any pointer/zero-value semantic your codebase uses), so a settlement-mode-only
change is no longer treated as unchanged and skipped.
In `@openmeter/productcatalog/subscription/http/mapping.go`:
- Line 470: When mapping a.SettlementMode in mapping.go, ensure you default
missing/ nil values to the documented default before converting to the domain
type: replace the direct
productcatalog.SettlementMode(lo.FromPtr(a.SettlementMode)) usage with logic
that reads the pointer (lo.FromPtr or equivalent), and if the result is
empty/zero, substitute the default "credit_then_invoice" (or the corresponding
constant) and then construct productcatalog.SettlementMode from that value so
you never store an empty settlement mode.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: c6b0efec-0545-48e6-9da1-487e9dcc2606
📒 Files selected for processing (18)
app/common/config.goapp/config/config.goapp/config/config_test.goapp/config/credit.gocmd/server/main.goe2e/productcatalog_test.goopenmeter/productcatalog/plan.goopenmeter/productcatalog/plan/httpdriver/credit_test.goopenmeter/productcatalog/plan/httpdriver/mapping.goopenmeter/productcatalog/plan/httpdriver/plan.goopenmeter/productcatalog/subscription/http/change.goopenmeter/productcatalog/subscription/http/create.goopenmeter/productcatalog/subscription/http/credit_test.goopenmeter/productcatalog/subscription/http/handler.goopenmeter/productcatalog/subscription/http/mapping.goopenmeter/server/router/plan.goopenmeter/server/router/router.goopenmeter/server/router/subscription.go
✅ Files skipped from review due to trivial changes (5)
- openmeter/server/router/plan.go
- openmeter/productcatalog/subscription/http/handler.go
- app/config/credit.go
- openmeter/productcatalog/plan/httpdriver/credit_test.go
- openmeter/productcatalog/subscription/http/credit_test.go
🚧 Files skipped from review as they are similar to previous changes (10)
- openmeter/server/router/subscription.go
- app/config/config_test.go
- app/common/config.go
- cmd/server/main.go
- openmeter/productcatalog/plan/httpdriver/mapping.go
- openmeter/server/router/router.go
- openmeter/productcatalog/subscription/http/change.go
- e2e/productcatalog_test.go
- openmeter/productcatalog/subscription/http/create.go
- openmeter/productcatalog/plan/httpdriver/plan.go
eb3e295 to
1b7aa29
Compare
turip
left a comment
There was a problem hiding this comment.
Additional issues:
- UpdatePlan is missing the credit_only guard entirely. plan.go:160-186 — the UpdatePlan handler doesn't validate credit_only settlement mode at all. A user could create a plan with credit_then_invoice, then update it to credit_only even when credits are disabled.
- For e2e tests, let's add the credits.enabled=false into the configuration file and add a comment that the e2e tc is depending on that.
521cd9d to
d347f32
Compare
d347f32 to
db89d36
Compare
db89d36 to
fb4023a
Compare
|
@tothandras, @turip comments are resolved |
Adds settlement mode to subscription and plan handlers, mapping.
Summary by CodeRabbit
New Features
Tests