Skip to content

Addon Purchase Validations - #2706

Merged
GAlexIHU merged 3 commits into
mainfrom
galexi/sub-addon-plan-validations-1
Apr 28, 2025
Merged

GAlexIHU merged 3 commits into
mainfrom
galexi/sub-addon-plan-validations-1

Conversation

@GAlexIHU

@GAlexIHU GAlexIHU commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor

Overview

Check linking of Addon to plan, validating quantity, phase, fixing tests...

Summary by CodeRabbit

  • New Features

    • Enforced validation that subscription addons can only be added if they are linked to the subscription’s plan and within allowed quantity limits.
    • Added validation to prevent addons on custom subscriptions (subscriptions without a plan).
  • Bug Fixes

    • Improved error handling and validation messages when creating or modifying subscription addons under invalid conditions.
  • Tests

    • Enhanced and expanded test coverage for addon creation, quantity changes, and validation scenarios.
    • Refactored test utilities and helpers for more realistic and consistent plan, addon, and subscription setup.
  • Chores

    • Refactored internal test setup for improved maintainability and clarity.

@GAlexIHU GAlexIHU added the release-note/misc Miscellaneous changes label Apr 22, 2025
@GAlexIHU GAlexIHU self-assigned this Apr 22, 2025
@GAlexIHU
GAlexIHU requested a review from a team as a code owner April 22, 2025 12:50
@coderabbitai

coderabbitai Bot commented Apr 22, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This change integrates the planaddon.Service into the subscription add-on service layer, enforcing that add-ons can only be added to subscriptions if they are linked to the subscription's plan and within allowed quantity limits. The NewSubscriptionServices constructor and related initializations are updated to accept and wire the new planaddon.Service dependency. Test utilities and test cases are refactored to create plans with associated add-ons and to validate plan-addon linkage and quantity constraints. Internal validation logic is added to the subscription add-on service to check plan compatibility and maximum quantity before allowing add-on creation or quantity changes.

Changes

Files/Paths Change Summary
app/common/subscription.go Added planaddon.Service as a parameter to NewSubscriptionServices and passed it to the subscription add-on service configuration.
cmd/billing-worker/wire_gen.go
cmd/jobs/internal/wire_gen.go
cmd/server/wire_gen.go
Updated application/service initialization to create and inject planaddonService via common.NewPlanAddonService, passing it to NewSubscriptionServices. Adjusted error handling and cleanup accordingly.
openmeter/subscription/addon/service/service.go Updated Config struct to include PlanAddonService. Enhanced Create and ChangeQuantity methods to validate that add-ons are linked to the subscription’s plan, enforce maximum allowed quantity, and restrict add-ons on custom subscriptions.
openmeter/subscription/testutils/service.go Added PlanAddonService field to SubscriptionDependencies and instantiated/configured planAddonService in the test service setup, injecting it into the add-on service config.
openmeter/subscription/testutils/helpers.go Added CreatePlanWithAddon helper to create plans with linked add-ons and publish them. Refactored subscription and add-on creation helpers to use this and to accept IDs instead of input structs, aligning with new plan-addon linkage and cadence requirements.
openmeter/subscription/addon/service/create_test.go Refactored tests to use createPlanWithAddon for consistent plan/addon creation and plan-addon linkage. Added/expanded tests for input validation, plan-addon linkage, maximum quantity, and custom subscription restrictions. Improved error assertions. Added helper for plan/addon creation.
openmeter/subscription/addon/service/change_test.go Added test to verify add-on quantity cannot exceed plan-defined maximum. Refactored helper to use realistic plan/addon/subscription creation flow and corrected subscription ID reference.
openmeter/subscription/addon/service/list_test.go Refactored test setup to use published plans with linked add-ons for subscription creation. Enhanced tests to operate on realistic plan-addon-subscription relationships.
openmeter/subscription/addon/diff/apply_test.go Refactored tests to use CreatePlanWithAddon and explicit cadence models for add-on activation, ensuring plan-addon linkage and more uniform test setup.
openmeter/subscription/workflow/service/addon_test.go Updated tests to create plans with associated add-ons and subscriptions from those plans, ensuring realistic plan-addon linkage and integration. Expanded setup for multi-addon tests.
openmeter/subscription/workflow/service/subscription_test.go Made test setup explicit and self-contained, creating plans with add-ons and subscriptions from those plans, and asserting forbidden errors when editing subscriptions with purchased add-ons.
openmeter/subscription/testutils/addon.go Set FeatureKey field in ExampleAddonRateCard1 to align with other rate card test data.
test/billing/subscription_suite.go Added plan-addon repository and service initialization in test suite setup, injecting it into the subscription add-on service configuration.

Possibly related PRs

  • openmeterio/openmeter#2675: Introduces the foundational adapter and service interface for the planaddon domain, which this PR extends by integrating planaddon.Service into subscription services.
  • openmeterio/openmeter#2684: Implements the HTTP API and server integration for the planaddon service, which relates to this PR’s wiring and usage of planaddon.Service in subscription logic.
  • openmeterio/openmeter#2663: Adds the database schema and Ent client code for the planaddon entity, which this PR depends on for plan-addon validation and linkage.

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 golangci-lint (1.64.8)

Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2
Failed executing command with error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2

✨ Finishing Touches
  • 📝 Generate Docstrings

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.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@GAlexIHU
GAlexIHU force-pushed the galexi/sub-addon-plan-validations-1 branch from af3e681 to fe71485 Compare April 22, 2025 15:13

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
openmeter/subscription/addon/service/create_test.go (1)

362-401: Consider using the global helper instead of local implementation.

This local helper function createPlanWithAddon is nearly identical to the global helper in helpers.go. Consider removing this local implementation and updating the tests to use the global helper for better code maintainability.

-func createPlanWithAddon(
-	t *testing.T,
-	deps subscriptiontestutils.SubscriptionDependencies,
-	planInp plan.CreatePlanInput,
-	addonInp addon.CreateAddonInput,
-) (subscription.Plan, addon.Addon) {
-	t.Helper()
-
-	_ = deps.FeatureConnector.CreateExampleFeatures(t)
-
-	p, err := deps.PlanService.CreatePlan(context.Background(), planInp)
-	require.Nil(t, err)
-	require.NotNil(t, p)
-
-	add := deps.AddonService.CreateTestAddon(t, addonInp)
-
-	_, err = deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{
-		NamespacedModel: models.NamespacedModel{
-			Namespace: subscriptiontestutils.ExampleNamespace,
-		},
-		PlanID:        p.ID,
-		AddonID:       add.ID,
-		FromPlanPhase: p.Phases[0].Key,
-	})
-	require.Nil(t, err, "received error: %s", err)
-
-	p, err = deps.PlanService.PublishPlan(context.Background(), plan.PublishPlanInput{
-		NamespacedID: p.NamespacedID,
-		EffectivePeriod: productcatalog.EffectivePeriod{
-			EffectiveFrom: lo.ToPtr(clock.Now()),
-			EffectiveTo:   lo.ToPtr(testutils.GetRFC3339Time(t, "2099-01-01T00:00:00Z")),
-		},
-	})
-	require.Nil(t, err, "received error: %s", err)
-
-	return &plansubscription.Plan{
-		Plan: p.AsProductCatalogPlan(),
-		Ref:  &p.NamespacedID,
-	}, add
-}

Then update the test cases to use subscriptiontestutils.CreatePlanWithAddon instead.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af3e681 and fe71485.

📒 Files selected for processing (19)
  • app/common/subscription.go (3 hunks)
  • cmd/billing-worker/wire_gen.go (1 hunks)
  • cmd/jobs/internal/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/productcatalog/addon.go (1 hunks)
  • openmeter/productcatalog/planaddon.go (3 hunks)
  • openmeter/productcatalog/ratecard.go (1 hunks)
  • openmeter/subscription/addon/diff/apply_test.go (13 hunks)
  • openmeter/subscription/addon/service/change_test.go (4 hunks)
  • openmeter/subscription/addon/service/create_test.go (7 hunks)
  • openmeter/subscription/addon/service/list_test.go (8 hunks)
  • openmeter/subscription/addon/service/service.go (3 hunks)
  • openmeter/subscription/testutils/addon.go (1 hunks)
  • openmeter/subscription/testutils/helpers.go (3 hunks)
  • openmeter/subscription/testutils/service.go (4 hunks)
  • openmeter/subscription/workflow/service/addon_test.go (6 hunks)
  • openmeter/subscription/workflow/service/subscription_test.go (1 hunks)
  • pkg/slicesx/iteratee.go (1 hunks)
  • test/billing/subscription_suite.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • openmeter/productcatalog/addon.go
🚧 Files skipped from review as they are similar to previous changes (10)
  • openmeter/subscription/addon/service/change_test.go
  • test/billing/subscription_suite.go
  • cmd/billing-worker/wire_gen.go
  • openmeter/subscription/testutils/addon.go
  • cmd/server/wire_gen.go
  • openmeter/subscription/addon/service/list_test.go
  • cmd/jobs/internal/wire_gen.go
  • openmeter/subscription/addon/service/service.go
  • app/common/subscription.go
  • openmeter/subscription/testutils/service.go
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/subscription/workflow/service/subscription_test.go (9)
openmeter/testutils/time.go (1)
  • GetRFC3339Time (10-17)
pkg/clock/clock.go (1)
  • SetTime (23-27)
openmeter/subscription/testutils/service.go (1)
  • NewService (58-198)
openmeter/subscription/testutils/helpers.go (2)
  • CreatePlanWithAddon (24-63)
  • CreateAddonForSubscription (109-127)
openmeter/subscription/timing.go (1)
  • Timing (14-17)
openmeter/subscription/testutils/global.go (1)
  • ExampleNamespace (5-5)
openmeter/subscription/patch/removeitem.go (1)
  • PatchRemoveItem (10-13)
openmeter/subscription/testutils/feature.go (1)
  • ExampleFeatureKey (13-13)
pkg/models/error.go (2)
  • GenericForbiddenError (104-106)
  • IsGenericForbiddenError (117-125)
openmeter/subscription/workflow/service/addon_test.go (10)
openmeter/subscription/testutils/helpers.go (3)
  • CreatePlanWithAddon (24-63)
  • CreateSubscriptionFromPlan (65-81)
  • CreateAddonForSubscription (109-127)
openmeter/subscription/testutils/addon.go (1)
  • BuildAddonForTesting (16-41)
openmeter/productcatalog/planaddon/service.go (1)
  • CreatePlanAddonInput (88-108)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/subscription/testutils/global.go (1)
  • ExampleNamespace (5-5)
openmeter/productcatalog/plan/service.go (1)
  • PublishPlanInput (276-281)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/testutils/time.go (1)
  • GetRFC3339Time (10-17)
pkg/models/cadence.go (1)
  • CadencedModel (23-27)
openmeter/subscription/workflow/service.go (1)
  • AddAddonWorkflowInput (34-42)
openmeter/subscription/addon/service/create_test.go (14)
openmeter/subscription/testutils/plan.go (1)
  • GetExamplePlanInput (72-80)
openmeter/subscription/testutils/addon.go (1)
  • GetExampleAddonInput (90-92)
openmeter/productcatalog/effectiveperiod.go (1)
  • EffectivePeriod (19-25)
openmeter/customer/adapter.go (1)
  • CustomerAdapter (16-23)
openmeter/subscription/subscriptionspec.go (2)
  • NewSpecFromPlan (825-910)
  • CreateSubscriptionCustomerInput (36-44)
openmeter/subscription/testutils/global.go (1)
  • ExampleNamespace (5-5)
openmeter/subscription/addon/addon.go (1)
  • CreateSubscriptionAddonInput (105-112)
openmeter/subscription/testutils/service.go (1)
  • SubscriptionDependencies (41-56)
pkg/clock/clock.go (2)
  • SetTime (23-27)
  • Now (14-21)
openmeter/subscription/addon/quantity.go (1)
  • CreateSubscriptionAddonQuantityInput (25-28)
pkg/models/error.go (1)
  • GenericValidationError (145-147)
openmeter/productcatalog/plan/service.go (2)
  • CreatePlanInput (98-101)
  • PublishPlanInput (276-281)
openmeter/productcatalog/planaddon/service.go (1)
  • CreatePlanAddonInput (88-108)
openmeter/testutils/time.go (1)
  • GetRFC3339Time (10-17)
openmeter/subscription/testutils/helpers.go (12)
openmeter/subscription/testutils/service.go (1)
  • SubscriptionDependencies (41-56)
openmeter/productcatalog/plan/service.go (2)
  • CreatePlanInput (98-101)
  • PublishPlanInput (276-281)
openmeter/productcatalog/addon/service.go (1)
  • CreateAddonInput (98-101)
openmeter/productcatalog/planaddon/service.go (1)
  • CreatePlanAddonInput (88-108)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/subscription/testutils/global.go (1)
  • ExampleNamespace (5-5)
openmeter/productcatalog/effectiveperiod.go (1)
  • EffectivePeriod (19-25)
pkg/clock/clock.go (1)
  • Now (14-21)
openmeter/testutils/time.go (1)
  • GetRFC3339Time (10-17)
openmeter/subscription/addon/quantity.go (1)
  • CreateSubscriptionAddonQuantityInput (25-28)
openmeter/subscription/addon/addon.go (1)
  • CreateSubscriptionAddonInput (105-112)
pkg/models/cadence.go (1)
  • CadencedModel (23-27)
⏰ Context from checks skipped due to timeout of 90000ms (11)
  • GitHub Check: Artifacts / Container image
  • GitHub Check: Test
  • GitHub Check: Quickstart
  • GitHub Check: Migration Checks
  • GitHub Check: Lint
  • GitHub Check: E2E
  • GitHub Check: Developer environment
  • GitHub Check: CI
  • GitHub Check: Commit hooks
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (22)
pkg/slicesx/iteratee.go (1)

3-7: Well-designed generic utility function.

This helper elegantly adapts a simple predicate to a more complex iteratee interface, enabling the use of simple predicates with functions that expect both value and index parameters.

openmeter/productcatalog/ratecard.go (1)

633-659: Improved entitlement template validation logic.

This change enhances the validation by only checking entitlement template compatibility when both templates exist, making the compatibility check more precise and flexible.

openmeter/subscription/workflow/service/subscription_test.go (1)

1016-1070: Improved test case with more explicit setup.

The refactored test now directly validates that editing a subscription with purchased addons fails with a GenericForbiddenError. The self-contained setup makes the test easier to understand and maintains better isolation.

openmeter/productcatalog/planaddon.go (2)

112-114: Enhanced validation approach with better error reporting.

Replaced the bulk compatibility check with a call to the new granular validation method that provides detailed per-rate-card validation.


124-152: Well-implemented granular validation with clear error messages.

This new method significantly improves the rate card compatibility validation by:

  1. Checking each plan rate card individually against affecting addon rate cards
  2. Enforcing that at most one addon rate card can affect a single plan rate card
  3. Providing specific error messages that pinpoint exactly which rate cards are incompatible
  4. Using the new utility function AsFilterIteratee to adapt the matcher function

The implementation follows best practices by:

  • Explicitly documenting assumptions
  • Handling edge cases (no affecting rate cards)
  • Collecting and returning all validation errors for a complete error report
  • Using meaningful error messages with context (rate card keys)
openmeter/subscription/addon/diff/apply_test.go (5)

22-22: Added model imports to support CadencedModel.

The import of the models package adds support for the CadencedModel struct which is now used for explicitly specifying addon activation time ranges.


50-58: Improved test setup with standardized helper function.

Refactored to use the new CreatePlanWithAddon helper function which creates a properly linked plan and addon, making the test more realistic by testing the actual plan-addon relationship that would exist in production.


62-65: Enhanced addon creation with explicit cadence model.

Using models.CadencedModel provides a clearer, more explicit representation of addon activation periods with properly typed fields for ActiveFrom and ActiveTo times.


271-275: Reference to cadence model in test assertions.

The test has been updated to correctly assert against the new cadence model's fields when verifying time-based functionality.


516-519: Improved cadence definition for addon tests.

Using structured models.CadencedModel for defining addon activation periods makes the test more readable and type-safe compared to separate time variables.

openmeter/subscription/workflow/service/addon_test.go (4)

11-13: Added necessary imports for improved plan-addon validation.

These additional imports enable the proper testing of plan-addon relationships, which is crucial for the addon purchase validation feature being implemented.


44-57: Improved test setup with standardized plan-addon creation.

Using CreatePlanWithAddon helper ensures that the addon is properly linked to the plan before testing, which is essential for validating the new requirement that addons must be linked to the subscription's plan.


80-147: Comprehensive test for addon compatibility with plans.

This test setup correctly creates a plan with two linked addons and verifies that the addon purchase workflow properly validates addon-plan relationships. The test is thorough in creating the plan, addons, and subscription with realistic relationships.


151-157: Verify error on attempting to add already purchased addon.

The test now properly checks that attempting to add an addon that's already been purchased results in a conflict error, with appropriate error type validation.

openmeter/subscription/addon/service/create_test.go (5)

15-17: Added imports for improved plan-addon validation.

These imports support the new validation of plan-addon relationships during addon purchase, which is the core focus of this PR.


34-41: Standardized test setup with plan-addon creation.

Using a consistent approach to create plans with linked addons across all tests makes the code more maintainable and accurately represents real-world scenarios where addons must be linked to plans.


191-239: Added test for plan-addon linking validation.

This test is critical as it verifies the core feature of this PR: ensuring that addons can only be purchased if they are linked to the subscription's plan. The test properly validates both the error type and the specific error message content.


250-297: Validate custom subscription restrictions for addons.

This test properly verifies that addons cannot be added to custom subscriptions (those without a plan reference), which is an important constraint for maintaining data integrity and proper plan-addon relationships.


300-359: Comprehensive test for addon creation and retrieval.

This test thoroughly validates the successful creation and retrieval of a subscription addon, ensuring that the addon is properly stored and can be retrieved with all expected properties.

openmeter/subscription/testutils/helpers.go (3)

24-63: Added comprehensive helper for plan-addon creation.

This helper function is crucial for implementing the addon purchase validations in this PR. It creates a plan, an addon, links them with a plan-addon association, and publishes the plan to create a realistic test scenario.


84-107: Improved addon creation helper with namespaced IDs.

Updated the CreateMultiInstanceAddonForSubscription function to work with namespaced IDs, making it more consistent with the API design and improving type safety.


109-127: Enhanced subscription addon creation with cadence model.

The CreateAddonForSubscription helper now uses models.CadencedModel for specifying activation periods, providing a more consistent and type-safe way to define addon lifetimes.

@GAlexIHU GAlexIHU changed the title Addon Purchase Validations Part I Addon Purchase Validations Apr 22, 2025
@GAlexIHU
GAlexIHU changed the base branch from main to galexi/fix-rx-compare April 22, 2025 15:48
@GAlexIHU
GAlexIHU force-pushed the galexi/fix-rx-compare branch from d9ea552 to d542bc8 Compare April 23, 2025 09:26
@GAlexIHU
GAlexIHU force-pushed the galexi/sub-addon-plan-validations-1 branch from 1ad30db to 87da814 Compare April 23, 2025 09:27
Base automatically changed from galexi/fix-rx-compare to main April 25, 2025 10:02
@GAlexIHU
GAlexIHU force-pushed the galexi/sub-addon-plan-validations-1 branch from 87da814 to a3dff42 Compare April 25, 2025 10:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (3)
openmeter/subscription/addon/service/list_test.go (1)

141-141: Consider removing redundant error messages in require statements.

The error messages in the require.Nil statements are redundant as require.Nil already logs the error on failure.

-require.Nil(t, err, "received error: %s", err)
+require.Nil(t, err)

Also applies to: 152-152

openmeter/subscription/addon/service/create_test.go (1)

313-313: Avoid hardcoded phase names in assertions.

The error message assertion contains hardcoded phase names which could break if the test data changes.

-require.ErrorContains(t, err, fmt.Sprintf("addon %s@%d can be only added starting with phase %s, current phase is %s", add.Key, add.Version, "test_phase_3", "test_phase_1"))
+require.ErrorContains(t, err, fmt.Sprintf("addon %s@%d can be only added starting with phase %s, current phase is %s", add.Key, add.Version, p.Phases[len(p.Phases)-1].Key, p.Phases[0].Key))
openmeter/subscription/testutils/helpers.go (1)

46-46: Consider parameterizing the plan phase for addon linking.

The helper function always links the addon to the first phase (p.Phases[0].Key), which might not be suitable for all test scenarios (like phase validation tests that need addons linked to later phases).

func CreatePlanWithAddon(
	t *testing.T,
	deps SubscriptionDependencies,
	planInp plan.CreatePlanInput,
	addonInp addon.CreateAddonInput,
+	phaseIndex int,
) (subscription.Plan, addon.Addon) {
	t.Helper()

	_ = deps.FeatureConnector.CreateExampleFeatures(t)

	p, err := deps.PlanService.CreatePlan(context.Background(), planInp)
	require.Nil(t, err)
	require.NotNil(t, p)

	add := deps.AddonService.CreateTestAddon(t, addonInp)

	_, err = deps.PlanAddonService.CreatePlanAddon(context.Background(), planaddon.CreatePlanAddonInput{
		NamespacedModel: models.NamespacedModel{
			Namespace: ExampleNamespace,
		},
		PlanID:        p.ID,
		AddonID:       add.ID,
-		FromPlanPhase: p.Phases[0].Key,
+		FromPlanPhase: p.Phases[phaseIndex].Key,
	})
	require.Nil(t, err, "received error: %s", err)

Then update calling code to provide the desired phase index (defaulting to 0 for most cases).

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1ad30db and a3dff42.

📒 Files selected for processing (15)
  • app/common/subscription.go (3 hunks)
  • cmd/billing-worker/wire_gen.go (1 hunks)
  • cmd/jobs/internal/wire_gen.go (1 hunks)
  • cmd/server/wire_gen.go (1 hunks)
  • openmeter/subscription/addon/diff/apply_test.go (13 hunks)
  • openmeter/subscription/addon/service/change_test.go (5 hunks)
  • openmeter/subscription/addon/service/create_test.go (7 hunks)
  • openmeter/subscription/addon/service/list_test.go (8 hunks)
  • openmeter/subscription/addon/service/service.go (4 hunks)
  • openmeter/subscription/testutils/addon.go (1 hunks)
  • openmeter/subscription/testutils/helpers.go (3 hunks)
  • openmeter/subscription/testutils/service.go (4 hunks)
  • openmeter/subscription/workflow/service/addon_test.go (6 hunks)
  • openmeter/subscription/workflow/service/subscription_test.go (1 hunks)
  • test/billing/subscription_suite.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • openmeter/subscription/testutils/addon.go
🚧 Files skipped from review as they are similar to previous changes (11)
  • cmd/billing-worker/wire_gen.go
  • test/billing/subscription_suite.go
  • cmd/jobs/internal/wire_gen.go
  • cmd/server/wire_gen.go
  • openmeter/subscription/testutils/service.go
  • app/common/subscription.go
  • openmeter/subscription/workflow/service/addon_test.go
  • openmeter/subscription/workflow/service/subscription_test.go
  • openmeter/subscription/addon/service/service.go
  • openmeter/subscription/addon/service/change_test.go
  • openmeter/subscription/addon/diff/apply_test.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
openmeter/subscription/addon/service/list_test.go (9)
openmeter/subscription/testutils/plan.go (1)
  • GetExamplePlanInput (72-80)
openmeter/subscription/testutils/addon.go (1)
  • GetExampleAddonInput (90-92)
openmeter/subscription/subscriptionspec.go (2)
  • NewSpecFromPlan (827-912)
  • CreateSubscriptionCustomerInput (36-44)
openmeter/subscription/testutils/global.go (1)
  • ExampleNamespace (5-5)
openmeter/productcatalog/planaddon/service.go (1)
  • CreatePlanAddonInput (88-108)
pkg/models/model.go (1)
  • NamespacedModel (180-182)
openmeter/productcatalog/plan/service.go (1)
  • PublishPlanInput (276-281)
openmeter/testutils/time.go (1)
  • GetRFC3339Time (10-17)
openmeter/subscription/addon/addon.go (1)
  • CreateSubscriptionAddonInput (105-112)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Lint
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (12)
openmeter/subscription/addon/service/list_test.go (4)

11-15: Well-structured imports for the enhanced validation model.

The new imports appropriately support the plan-addon relationship model, enabling the tests to validate addon purchases against plans.


31-38: Good refactoring using the new helper function.

This refactoring improves test readability by encapsulating the complex setup of creating a plan with an addon, linking them via plan-addons, and publishing the plan.


99-163: Well-structured test setup for comprehensive addon validation.

The enhanced test now properly creates features, a plan, two addons, links them via plan-addons, and publishes the plan with an effective period. This realistic setup ensures proper validation of the plan-addon relationship.


165-180: Comprehensive subscription creation from published plan.

The test now properly creates a subscription from the published plan, which is a more realistic representation of how subscriptions are created and ensures proper validation against the plan-addon relationship.

openmeter/subscription/addon/service/create_test.go (5)

191-240: Excellent validation test for plan-addon linkage.

This test properly validates that an addon can only be purchased if it's linked to the subscription's plan. It creates an unlinked addon and verifies that attempting to add it to a subscription results in the expected validation error with a clear message.


242-315: Well-implemented phase validation test.

This test properly validates that addons can only be purchased during phases where they're available. It creates a plan with multiple phases, links an addon only to the last phase, and verifies that attempting to add it during the first phase results in the expected validation error.


317-391: Comprehensive maximum quantity validation test.

This test properly validates that addon quantities don't exceed the maximum allowed as defined in the plan-addon link. It creates a plan with an addon limited to 2 instances, and verifies that attempting to add 3 results in the expected validation error.


393-441: Good validation test for custom subscriptions.

This test ensures that addons cannot be added to custom subscriptions (those without a plan reference), which is an important validation for maintaining data integrity.


505-544: Well-structured helper function.

The createPlanWithAddon helper function effectively encapsulates the complex setup process of creating a plan with an addon, linking them, and publishing the plan. This improves code reuse and readability throughout the tests.

openmeter/subscription/testutils/helpers.go (3)

24-63: Good reusable helper function for creating plans with addons.

This exported helper function properly encapsulates the process of creating a plan with an addon, linking them, and publishing the plan, which supports the addon purchase validation requirements across the codebase.


65-81: Improved signature for CreateSubscriptionFromPlan.

The function now takes a fully constructed plan instead of plan input, which better supports the new validation model where plans must be linked to addons before subscriptions are created.


84-107: Streamlined addon creation functions.

These functions have been updated to accept addon IDs and cadence models rather than creating addons internally, which aligns with the new approach of linking addons to plans before creating subscriptions.

Also applies to: 109-127

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

release-note/misc Miscellaneous changes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants