Repository navigation
feat: add plan-addon compatibility - #2635
Conversation
📝 WalkthroughWalkthroughThis pull request introduces several enhancements to the product catalog module. A new file defines the Changes
Possibly related PRs
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 ✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
6201e3c to
1452628
Compare
ce89303 to
fd697f1
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (5)
openmeter/productcatalog/plan.go (2)
66-66: Clarify or complete the “FIXME” comment.
This placeholder suggests a rename to “publishable,” but it is unclear whether it is planned or needed. Consider creating a dedicated task or removing the comment if no longer relevant.
75-75: Elaborate on the “FIXME”.
This line has a lone “FIXME” without further details, which may lead to confusion. Provide a more specific description or remove if not required.openmeter/productcatalog/ratecard.go (3)
526-564: Comprehensive approach to combining and validating rate cards.
This function merges both base and overlay rate cards by key, maintaining a clear structure for subsequent compatibility checks. If the project ever needs pairwise overlay checks (overlay vs. overlay), consider extending this logic.
571-583: Validating base vs. overlays is straightforward.
However, ensure that if overlay-to-overlay compatibility is required, it is handled. Currently only base-to-each overlay is checked.
585-669: Robust compatibility checks.
This function covers price types, features, billing cadence, and entitlements. To improve maintainability, consider modularizing each check into smaller helper functions (e.g., checkPriceCompatibility, checkEntitlementCompatibility, etc.).
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
openmeter/productcatalog/assignment.go(1 hunks)openmeter/productcatalog/entitlement.go(1 hunks)openmeter/productcatalog/plan.go(5 hunks)openmeter/productcatalog/ratecard.go(5 hunks)openmeter/productcatalog/ratecard_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/productcatalog/assignment.go (3)
pkg/models/validator.go (2)
ValidatorFunc(10-10)Validate(16-26)openmeter/productcatalog/plan.go (1)
Plan(39-44)openmeter/productcatalog/ratecard.go (1)
RateCards(435-435)
openmeter/productcatalog/plan.go (4)
openmeter/productcatalog/subscription/plan.go (1)
Plan(50-53)openmeter/productcatalog/plan/plan.go (1)
Plan(16-24)pkg/models/validator.go (4)
ValidatorFunc(10-10)Validate(16-26)Validator(5-8)CustomValidator(12-14)pkg/models/equaler.go (1)
Equaler(3-6)
openmeter/productcatalog/ratecard_test.go (5)
openmeter/productcatalog/ratecard.go (4)
RateCard(28-40)UsageBasedRateCard(328-334)RateCardMeta(51-82)FlatFeeRateCard(214-221)openmeter/productcatalog/price.go (4)
Price(84-91)NewPriceFrom(342-364)FlatPrice(383-390)UnitPrice(426-431)openmeter/productcatalog/entitlement.go (2)
EntitlementTemplate(34-39)MeteredEntitlementTemplate(253-273)pkg/isodate/date.go (1)
MustParse(151-158)pkg/models/error.go (1)
GenericValidationError(145-147)
openmeter/productcatalog/ratecard.go (4)
pkg/models/error.go (1)
NewNillableGenericValidationError(129-135)openmeter/productcatalog/price.go (1)
Price(84-91)openmeter/productcatalog/entitlement.go (1)
EntitlementTemplate(34-39)openmeter/ent/db/entitlement/entitlement.go (2)
EntitlementTypeStatic(176-176)EntitlementTypeMetered(175-175)
⏰ Context from checks skipped due to timeout of 90000ms (7)
- GitHub Check: Test
- GitHub Check: CI
- GitHub Check: Lint
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Analyze (go)
🔇 Additional comments (17)
openmeter/productcatalog/ratecard_test.go (4)
839-840: Test function definition looks good.
The newly introducedTestRateCardsCompatiblefunction is a clear and well-structured table-driven test that covers multiple compatibility scenarios.
847-892: Comprehensive coverage of a 'compatible' scenario.
This test case checks a straightforward situation where both rate cards share the same pricing model, feature key, and feature ID, along with matching billing cadence. The logic is sound and confirms no errors for truly compatible rate cards.
893-1166: Thorough negative testing for incompatibilities.
All mismatch scenarios (e.g., price type, feature key, feature ID, billing cadence, template type, usage period) are properly validated. This extensive coverage ensures robust error-handling and clarifies user expectations when rate cards diverge. The test naming is descriptive, aiding maintainability.
1169-1183: Final loop validates test expectations correctly.
Usingt.Run(test.name, ...)withassert.Errororassert.NoErrorconfirms each scenario’s outcome precisely. The additionalassert.ErrorAscheck is excellent for verifying the specific error type.openmeter/productcatalog/assignment.go (3)
15-27: Struct definition provides clear add-on assignment.
ThePlanAddonAssignmentstruct logically organizes plan/add-on relationship details (e.g.,FromPlanPhase,MaxQuantity), making the assignment semantics straightforward.
29-31: Sensible custom validation entry point.
ValidateWithuses the existing validation framework, allowing for flexible extension of checks onPlanAddonAssignmentwithout duplicating logic.
33-91: Robust validation ensures correctness and alignment.
- Requiring
MaxQuantityfor multiple-instance add-ons prevents under-defined states.- Checking plan and add-on statuses reduces risk of referencing inactive or scheduled items.
- Currency matching and rate card compatibility checks help unify billing logic across phases.
Overall, the aggregated errors provide clear feedback.openmeter/productcatalog/entitlement.go (3)
170-184: Type-safe retrieval of metered entitlements.
The switch-case handling inAsMeteredgracefully isolates type mismatch scenarios. Reporting uninitialized entitlements with descriptive errors further enhances clarity.
185-199: Static entitlement checks mirror the metered approach.
AsStaticensures the calling code cannot accidentally use a non-static type. The error messaging is self-explanatory, minimizing confusion when the template is missing or typed incorrectly.
200-214: Boolean entitlement logic aligns with the same pattern.
AsBooleanprovides a parallel, type-specific retrieval method. The default and mismatch cases help avoid silent errors or misinterpretation of templates.openmeter/productcatalog/plan.go (3)
46-48: Method appears correct and straightforward.
The newly introducedValidateWithmethod cleanly delegates tomodels.Validate, fulfilling themodels.CustomValidator[Plan]interface without adding unnecessary complexity.
146-148: Interfaces successfully implemented.
Confirming thatPlanimplementsCustomValidator[Plan]and thatPlanMetaremains a validValidatorandEqualeris a good practice for maintainability.
265-274: Validator function is well-structured.
PlanWithAllowedStatuscleanly checks plan status against a list of allowed statuses. The usage oflo.Containsis concise and legible.openmeter/productcatalog/ratecard.go (4)
9-9: New import path looks valid.
Theentitlementreferences appear to be in line with the newly introduced compatibility checks. No issues found.
223-225: Consistent compatibility delegation for FlatFeeRateCard.
Forwarding torateCardsCompatiblefollows the emerging pattern and stays consistent with the usage-based approach.
336-338: Consistent compatibility delegation for UsageBasedRateCard.
Maintains symmetry with the FlatFee version. No concerns here.
566-569: Struct neatly groups base and overlays.
rateCardWithOverlayscleanly represents this relationship, aiding clarity in compatibility checks.
fd697f1 to
9ca6257
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (2)
openmeter/productcatalog/assignment.go (1)
78-81: Enhance error message with additional contextThe error message for currency mismatch is very generic compared to other error messages in this file.
Consider enhancing it with more context:
- if c.Addon.Currency != c.Plan.Currency { - errs = append(errs, errors.New("currency mismatch")) - } + if c.Addon.Currency != c.Plan.Currency { + errs = append(errs, fmt.Errorf("currency mismatch: addon currency %s does not match plan currency %s", + c.Addon.Currency, c.Plan.Currency)) + }openmeter/productcatalog/ratecard.go (1)
585-669: Comprehensive compatibility checks in rateCardsCompatible functionThe
rateCardsCompatiblefunction is well-implemented with thorough checks for various attributes including price types, feature keys/IDs, billing cadence, and entitlement templates. The error messages are clear and include relevant context.One minor improvement suggestion: consider using constant error messages for common errors to make them more consistent and easier to test against.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
openmeter/productcatalog/assignment.go(1 hunks)openmeter/productcatalog/entitlement.go(1 hunks)openmeter/productcatalog/plan.go(5 hunks)openmeter/productcatalog/ratecard.go(5 hunks)openmeter/productcatalog/ratecard_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
- openmeter/productcatalog/entitlement.go
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/productcatalog/ratecard_test.go (4)
openmeter/productcatalog/ratecard.go (3)
RateCard(28-40)UsageBasedRateCard(328-334)RateCardMeta(51-82)openmeter/productcatalog/entitlement.go (2)
EntitlementTemplate(34-39)MeteredEntitlementTemplate(253-273)pkg/isodate/date.go (1)
MustParse(151-158)pkg/models/error.go (1)
GenericValidationError(145-147)
openmeter/productcatalog/assignment.go (4)
pkg/models/validator.go (3)
CustomValidator(12-14)ValidatorFunc(10-10)Validate(16-26)openmeter/productcatalog/plan.go (2)
Plan(39-44)PlanStatusActive(17-17)openmeter/productcatalog/ratecard.go (1)
RateCards(435-435)pkg/models/error.go (1)
NewNillableGenericValidationError(129-135)
openmeter/productcatalog/ratecard.go (4)
pkg/models/error.go (1)
NewNillableGenericValidationError(129-135)openmeter/productcatalog/price.go (1)
Price(84-91)openmeter/productcatalog/entitlement.go (1)
EntitlementTemplate(34-39)openmeter/ent/db/entitlement/entitlement.go (3)
EntitlementTypeStatic(176-176)EntitlementTypeMetered(175-175)EntitlementTypeBoolean(177-177)
openmeter/productcatalog/plan.go (5)
openmeter/productcatalog/subscription/plan.go (1)
Plan(50-53)openmeter/productcatalog/plan/plan.go (1)
Plan(16-24)openmeter/ent/db/plan.go (2)
Plan(17-51)Plan(83-102)pkg/models/validator.go (4)
ValidatorFunc(10-10)Validate(16-26)Validator(5-8)CustomValidator(12-14)pkg/models/equaler.go (1)
Equaler(3-6)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (13)
openmeter/productcatalog/ratecard_test.go (1)
840-1183: Well-structured test cases for rate card compatibilityThe new test function provides comprehensive coverage for the
rateCardsCompatiblefunction, with clearly named test cases covering both compatible and incompatible scenarios. The test cases systematically check different compatibility aspects including price types, feature keys/IDs, billing cadence, entitlement template types, and usage periods.I appreciate the detailed test setup and assertions, particularly the verification that errors are of the expected type (
GenericValidationError).openmeter/productcatalog/assignment.go (4)
10-14: Good interface implementation checksThese interface implementation checks ensure at compile-time that
PlanAddonAssignmentcorrectly implements the required validator interfaces, which is a good practice.
15-27: Well-defined struct for Plan-Addon relationshipThe
PlanAddonAssignmentstruct cleanly models the relationship between plans and add-ons, with clear field names and types.
29-31: Clean implementation of custom validationThe
ValidateWithmethod provides a good extension point for applying custom validators toPlanAddonAssignmentinstances.
83-96: Phase compatibility checking logicThe logic for validating compatibility between plan phases and addon rate cards is well-implemented. I like how it skips phases before the
FromPlanPhaseindex and uses the existingCompatiblemethod to check if rate cards can be merged.openmeter/productcatalog/plan.go (4)
46-48: Good implementation of custom validation for PlanThe
ValidateWithmethod provides a clean way to apply custom validators toPlaninstances, consistent with the implementation inPlanAddonAssignment.
66-76: TODO comments for future refactoringThere are TODO comments indicating the need to rename
ValidForCreatingSubscriptions. While this doesn't affect functionality now, make sure to address these comments in a future update.Consider creating a tracking issue to rename this method to "publishable" as indicated in the comment.
145-149: Updated interface implementation checksGood update to include the
models.CustomValidator[Plan]interface implementation check, while maintaining the existing validator and equaler implementation checks.
265-274: Well-designed validator function for Plan statusThe
PlanWithAllowedStatusfunction is a well-designed validator that encapsulates status validation logic and can be composed with other validators. This is a good example of functional programming in Go.openmeter/productcatalog/ratecard.go (4)
223-225: Clean implementation of Compatible method for FlatFeeRateCardThe implementation delegates to the common
rateCardsCompatiblefunction, which is a good approach for code reuse.
336-338: Clean implementation of Compatible method for UsageBasedRateCardSimilar to the FlatFeeRateCard implementation, this appropriately delegates to the common
rateCardsCompatiblefunction.
526-564: Comprehensive compatibility check for RateCards collectionsThe
Compatiblemethod onRateCardsis well-implemented, with proper validation of both the current and overlay rate cards before checking compatibility. The approach of collecting rate cards by keys and using a helper struct is clean and maintainable.
566-583: Clean helper struct for rate card validationThe
rateCardWithOverlaysstruct and itsValidatemethod provide a clean abstraction for validating a base rate card against multiple overlays.
9ca6257 to
0d553c0
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
openmeter/productcatalog/ratecard_test.go (1)
840-1183: Well-structured test suite for rate card compatibilityThe test suite covers comprehensive scenarios for rate card compatibility validation, including price type compatibility, feature metadata matching, billing cadence alignment, entitlement template type compatibility, and usage period consistency.
There's significant code duplication in the test setup that could be refactored to improve maintainability. Consider creating helper functions to generate commonly used test rate cards.
Here's a suggestion to reduce duplication:
func TestRateCardsCompatible(t *testing.T) { + // Helper function to create a base metered rate card + createMeteredRateCard := func(opts ...func(*UsageBasedRateCard)) *UsageBasedRateCard { + rc := &UsageBasedRateCard{ + RateCardMeta: RateCardMeta{ + Price: NewPriceFrom(FlatPrice{ + Amount: decimal.NewFromInt(1000), + }), + FeatureKey: lo.ToPtr("feature1"), + FeatureID: lo.ToPtr("id1"), + EntitlementTemplate: NewEntitlementTemplateFrom( + MeteredEntitlementTemplate{ + Metadata: map[string]string{ + "name": "metered-1", + }, + IsSoftLimit: false, + IssueAfterReset: lo.ToPtr(500.0), + IssueAfterResetPriority: lo.ToPtr[uint8](1), + PreserveOverageAtReset: lo.ToPtr(false), + UsagePeriod: isodate.MustParse(t, "P1M"), + }), + }, + BillingCadence: isodate.MustParse(t, "P1M"), + } + + // Apply customizations + for _, opt := range opts { + opt(rc) + } + + return rc + } tests := []struct { name string rCard RateCard vCard RateCard wantErr bool }{ // Use the helper function in test cases } // Rest of the test implementation... }
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (5)
openmeter/productcatalog/assignment.go(1 hunks)openmeter/productcatalog/entitlement.go(1 hunks)openmeter/productcatalog/plan.go(5 hunks)openmeter/productcatalog/ratecard.go(5 hunks)openmeter/productcatalog/ratecard_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
- openmeter/productcatalog/entitlement.go
- openmeter/productcatalog/assignment.go
🧰 Additional context used
🧬 Code Graph Analysis (3)
openmeter/productcatalog/ratecard_test.go (4)
openmeter/productcatalog/ratecard.go (3)
RateCard(28-40)UsageBasedRateCard(328-334)RateCardMeta(51-82)openmeter/productcatalog/entitlement.go (3)
EntitlementTemplate(34-39)MeteredEntitlementTemplate(253-273)BooleanEntitlementTemplate(393-396)pkg/isodate/date.go (1)
MustParse(151-158)pkg/models/error.go (1)
GenericValidationError(145-147)
openmeter/productcatalog/plan.go (4)
openmeter/productcatalog/subscription/plan.go (1)
Plan(50-53)openmeter/productcatalog/plan/plan.go (1)
Plan(16-24)pkg/models/validator.go (4)
ValidatorFunc(10-10)Validate(16-26)Validator(5-8)CustomValidator(12-14)pkg/models/equaler.go (1)
Equaler(3-6)
openmeter/productcatalog/ratecard.go (4)
pkg/models/error.go (1)
NewNillableGenericValidationError(129-135)openmeter/ent/db/entitlement/where.go (1)
FeatureKey(105-107)openmeter/productcatalog/entitlement.go (1)
EntitlementTemplate(34-39)openmeter/ent/db/entitlement/entitlement.go (2)
EntitlementTypeStatic(176-176)EntitlementTypeMetered(175-175)
⏰ Context from checks skipped due to timeout of 90000ms (10)
- GitHub Check: Test
- GitHub Check: Quickstart
- GitHub Check: Lint
- GitHub Check: Migration Checks
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (8)
openmeter/productcatalog/plan.go (4)
46-48: Added custom validator support to Plan typeThe
ValidateWithmethod enables custom validation for Plan objects using the validator pattern, which enhances flexibility and reusability of validation logic.
66-76: Address TODOs before finalizing PRThere are two FIXME comments that suggest incomplete work or planned future changes. The comment "rename to publishable" indicates this method will be renamed, but this hasn't been done yet.
Consider either implementing these changes now or adding more context to the TODOs with ticket numbers or more detailed explanations.
146-148: Updated interface assertionsProperly updated the variable declarations to include the new
models.CustomValidator[Plan]implementation for thePlanstruct.
265-274: New function for validating plan statusThe
PlanWithAllowedStatusfunction provides a clean, functional approach to create a validator that checks if a plan's status is within a set of allowed statuses. This is useful for implementing the plan-addon assignment validation.openmeter/productcatalog/ratecard.go (4)
38-38: Enhanced RateCard interface with compatibility checkAdded a
Compatiblemethod to theRateCardinterface to verify compatibility between rate cards, which is essential for the plan-addon assignment feature.
223-225: Implemented compatibility check for both rate card typesBoth
FlatFeeRateCardandUsageBasedRateCarddelegate to the commonrateCardsCompatiblefunction. This approach ensures consistent compatibility checking logic across rate card types.Also applies to: 336-338
566-583: Created helper struct for validating rate cards with overlaysThe
rateCardWithOverlaysstruct provides a clean way to group a base rate card with its overlays and validate their compatibility.
585-669: Comprehensive compatibility checking logicThe
rateCardsCompatiblefunction performs thorough validation of various attributes between rate cards. However, I noticed a few issues:
On line 642, the function always rejects static entitlements with the error "static entitlement are not allowed". Is this an intentional restriction?
For boolean entitlements (line 663-664), there are no specific compatibility checks implemented. If no checks are needed, consider adding a comment explaining why.
The
IssueAfterResetcheck on lines 660-662 only verifies that the reference value is not greater than the overlay value. Is this the correct validation logic?Please verify if these implementation details align with the intended compatibility rules.
Overview
PlanAddonAssignmenttype which describes the association ofAddonto aPlanAddonandPlanresources and their ratecardsSummary by CodeRabbit