Implement Usage Discounts for Addons
Overview
- RateCard compatibility validations were broken up as there's an issue subscription management where we manage FeatureID incorrectly (will be resolved separately)
- These validations were also extended to check for discounts
- These validations were also changed as Price type was incorrectly handled (e.g. Tiered Prices were allowed in compatibilty check while they cannot be merged)
- Implements extend's apply and restore logic for usage discounts
Notes for reviewer
- Only usage discounts are allowed for as per spec.
Summary by CodeRabbit
-
Refactor
- Improved rate card compatibility checks with a modular validation approach, providing clearer error messages for incompatibilities.
- Validation logic for add-on and plan rate cards is now more structured and extensible.
- Add-on rate cards no longer support tiered pricing in tests, reflecting current limitations.
-
Bug Fixes
- Enhanced handling of usage discounts when applying or restoring add-on rate cards, ensuring correct updates and error handling for discount quantities.
-
Tests
- Expanded test coverage for usage discount scenarios and billing cadence validation.
- Updated test expectations to reflect new error messages and validation logic.
📝 Walkthrough
Walkthrough
This change refactors the compatibility validation logic for rate cards in the product catalog and subscription add-on modules. The previous approach, which used a monolithic function for compatibility checks, is replaced by a new RateCardWithOverlay struct and a set of granular validator functions, each responsible for a specific aspect of compatibility. The validation logic is modularized, and new exported methods and validators are introduced. Test cases are updated to use the new validation approach, and error message expectations are refined. Handling of usage discounts in add-on application and restoration is added, with corresponding tests to ensure correct discount logic.
Changes
| Files / Paths | Change Summary |
|---|---|
| openmeter/productcatalog/ratecard.go | Refactored rate card compatibility checks by introducing the RateCardWithOverlay struct and modular validator functions (e.g., for key, price, feature key, billing cadence, entitlement template, and discounts). Added new exported methods and validators. Replaced the previous compatibility function with this structured approach, and updated the Compatible methods of rate card types to use the new validation logic. |
| openmeter/productcatalog/planaddon.go | Updated compatibility validation between plan and add-on rate cards to use the new RateCardWithOverlay and its Validate() method instead of the previous function. Enhanced error reporting for incompatibility. |
| openmeter/subscription/addon/compatible.go | Deleted the file and removed the validateRateCards function, as its logic is now superseded by the new modular validators in the product catalog. |
| openmeter/subscription/addon/extend.go | Refactored Apply and Restore methods to extract validation logic into a new Validate method, using the new modular validators for compatibility checks. Added logic to handle usage discounts during apply and restore operations, including error handling for discount mismatches. |
| openmeter/productcatalog/ratecard_test.go | Updated tests to use NewRateCardWithOverlay(...).Validate() instead of the previous compatibility function. Maintained the same test logic for error assertions. |
| openmeter/subscription/addon/extend_test.go | Updated error message expectations in tests to match new validator error messages. Added new tests for billing cadence compatibility and for correct application and restoration of usage discounts, including error cases and successful scenarios. |
| openmeter/productcatalog/plan/service/service_test.go openmeter/productcatalog/planaddon/service/service_test.go |
Simplified test setup for add-on rate cards by removing tiered pricing structures and explicitly setting the Price field to nil, with comments clarifying that tiered pricing is not supported for add-ons. No changes to test logic or flow. |
[!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
📜 Recent review details
Configuration used: CodeRabbit UI Review profile: CHILL Plan: Pro
📥 Commits
Reviewing files that changed from the base of the PR and between 6a123de7840fe02bde0476b285fc6aac9458be49 and 23de2f9ef6e4905d8509d193d596b62188a0bbdd.
📒 Files selected for processing (8)
openmeter/productcatalog/plan/service/service_test.go(1 hunks)openmeter/productcatalog/planaddon.go(1 hunks)openmeter/productcatalog/planaddon/service/service_test.go(1 hunks)openmeter/productcatalog/ratecard.go(5 hunks)openmeter/productcatalog/ratecard_test.go(1 hunks)openmeter/subscription/addon/compatible.go(0 hunks)openmeter/subscription/addon/extend.go(3 hunks)openmeter/subscription/addon/extend_test.go(7 hunks)
💤 Files with no reviewable changes (1)
- openmeter/subscription/addon/compatible.go
🧰 Additional context used
🧬 Code Graph Analysis (4)
openmeter/productcatalog/ratecard_test.go (2)
openmeter/productcatalog/ratecard.go (1)
NewRateCardWithOverlay(574-579)pkg/models/validator.go (1)
Validate(16-26)
openmeter/productcatalog/plan/service/service_test.go (3)
api/api.gen.go (1)
Price(5455-5457)openmeter/productcatalog/price.go (1)
Price(84-91)openmeter/billing/invoiceline.go (1)
Price(701-701)
openmeter/subscription/addon/extend_test.go (3)
openmeter/productcatalog/ratecard.go (2)
UsageBasedRateCard(350-356)RateCardMeta(52-83)openmeter/testutils/time.go (1)
GetISODuration(19-26)openmeter/productcatalog/price.go (1)
NewPriceFrom(363-385)
openmeter/productcatalog/planaddon.go (1)
openmeter/productcatalog/ratecard.go (1)
NewRateCardWithOverlay(574-579)
⏰ Context from checks skipped due to timeout of 90000ms (6)
- GitHub Check: Test
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: CI
- GitHub Check: Commit hooks
- GitHub Check: Analyze (go)
🔇 Additional comments (28)
openmeter/productcatalog/ratecard_test.go (1)
1146-1146: Good refactoring to structured validation!The change from direct compatibility function call to using
NewRateCardWithOverlay(test.rCard, test.vCard).Validate()improves code organization by encapsulating validation logic in a dedicated struct. This approach is more maintainable and allows for better separation of concerns.openmeter/productcatalog/planaddon/service/service_test.go (1)
236-236: Clarifying constraint with explicit nil valueSetting the Price to nil with the explanatory comment clearly documents that tiered pricing is not supported for add-ons. This makes the test code more accurate and aligns with the validation constraints in the codebase.
openmeter/productcatalog/plan/service/service_test.go (1)
94-94: Clarifying constraint with explicit nil valueSetting the Price to nil with the explanatory comment clearly documents that tiered pricing is not supported for add-ons. This makes the test code more accurate and aligns with the validation constraints that are now being enforced in the codebase.
openmeter/productcatalog/planaddon.go (1)
146-146: Good refactoring to structured validation!The change from direct compatibility function call to using
NewRateCardWithOverlay(phaseRateCard, affectingRateCards[0]).Validate()is consistent with the broader refactoring effort. This approach provides a more structured and maintainable validation mechanism, allowing for better modularity in the compatibility checks between plan rate cards and add-on rate cards.openmeter/subscription/addon/extend.go (5)
17-19: Clean validation pattern applied.Extraction of the validation logic into a separate
Validatemethod is a good refactoring that improves code organization and reusability.
71-76: Good implementation of usage discount application.This new code properly applies usage discounts from the addon to the target rate card. The implementation correctly:
- Checks if the addon has a usage discount
- Retrieves the target's current discount (defaulting to empty if nil)
- Adds the addon's quantity to the target's quantity
- Updates the target with the new discount
84-86: Consistent validation pattern applied.The Restore method now uses the same validation pattern as Apply, maintaining consistency throughout the codebase.
151-164: Well-structured usage discount restoration logic.The implementation for restoring (removing) usage discounts is thorough and includes proper error handling:
- Checks if the addon has a usage discount
- Verifies the target has a usage discount to restore from
- Ensures the target's discount is sufficient to cover the addon's
- Subtracts the addon's quantity from the target's
- Updates the target with the adjusted discount
170-198: Solid validation implementation with clear error messages.The new
Validatemethod provides comprehensive validation:
- Ensures target is a non-nil pointer
- Verifies annotations are provided
- Utilizes the new
RateCardWithOverlayvalidation framework with appropriate validatorsThe FIXME comment on line 189 correctly addresses the known issue with feature ID handling that will be fixed separately (referenced as OM-1337 in the comment).
openmeter/subscription/addon/extend_test.go (9)
107-108: Updated error message expectations in tests.Test assertions now use more generic error message matching that aligns with the refactored validation system.
135-136: Consistent error message update for entitlement template type validation.The test now expects the standardized error message from the new modular validation system.
160-161: Updated key validation error message.Test now properly checks for the new error message format from the modular validators.
196-197: Updated payment term validation error message.The assertion now checks for the standardized error message format for price payment term compatibility.
207-225: Good test coverage for billing cadence validation.New test case properly verifies that applying an addon with a different billing cadence results in an error. This test is important for ensuring rate card compatibility validation is working correctly.
438-466: Comprehensive test for usage discount application.This test thoroughly verifies the new usage discount application functionality:
- Creates an addon with a usage discount of 100 units
- Creates a target with no existing discount
- Applies the addon and verifies the target now has the correct discount quantity
777-805: Good error case testing for usage discount restoration.This test verifies the appropriate error is returned when attempting to restore a usage discount from a target that doesn't have one. This is important validation to prevent unexpected behavior.
807-839: Complete validation for insufficient discount quantity.The test correctly verifies that attempting to restore more discount than is available on the target results in an appropriate error message with the exact quantities displayed.
841-873: Thorough test for successful usage discount restoration.This test provides a complete verification of the discount restoration logic:
- Creates an addon with a usage discount of 100 units
- Creates a target with a larger existing discount (150 units)
- Restores the addon discount and verifies the target's remaining discount is calculated correctly (50 units)
openmeter/productcatalog/ratecard.go (10)
220-225: Simplified compatibility check using the new validation framework.The
Compatiblemethod now leverages the newRateCardWithOverlaytype to perform validation, which is cleaner and more maintainable than the previous approach.
358-363: Consistent compatibility implementation across rate card types.The same validation pattern is applied to the
UsageBasedRateCard.Compatiblemethod, ensuring consistency in how compatibility is checked.
569-579: Well-designed overlay validation structure.The new
RateCardWithOverlaystruct and its constructor provide a clean way to validate compatibility between two rate cards.
581-599: Flexible validation approach with composition.The
ValidateWithmethod provides a way to run specific validators, while theValidatemethod applies all standard validators. This design is flexible and allows for customization when needed.
601-611: Clear and focused key validation.This validator ensures that rate cards share the same key, with a clear error message that helps identify compatibility issues.
613-642: Comprehensive price compatibility validation.This validator carefully checks price type compatibility and payment term compatibility for flat prices. The error messages are specific and helpful for debugging compatibility issues.
644-670: Well-separated feature key and ID validators.Breaking the feature compatibility checks into separate validators for key and ID improves modularity and allows for selective validation when needed.
672-702: Thorough billing cadence validation.This validator handles all possible combinations of billing cadence compatibility with clear error messages that include the actual values being compared.
704-742: Detailed entitlement template compatibility checks.The validator correctly handles different entitlement types and performs specific validation for metered entitlements, including usage period compatibility.
744-758: Appropriate discount compatibility rules.This validator enforces the rule that percentage discounts cannot be combined, which aligns with the business requirements for discount handling.
✨ 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.
🪧 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
@coderabbitaiin 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
@coderabbitaiin 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 pauseto pause the reviews on a PR.@coderabbitai resumeto resume the paused reviews.@coderabbitai reviewto trigger an incremental review. This is useful when automatic reviews are disabled for the repository.@coderabbitai full reviewto do a full review from scratch and review all the files again.@coderabbitai summaryto regenerate the summary of the PR.@coderabbitai generate docstringsto generate docstrings for this PR.@coderabbitai generate sequence diagramto generate a sequence diagram of the changes in this PR.@coderabbitai resolveresolve all the CodeRabbit review comments.@coderabbitai configurationto show the current CodeRabbit configuration for the repository.@coderabbitai helpto get help.
Other keywords and placeholders
- Add
@coderabbitai ignoreanywhere in the PR description to prevent this PR from being reviewed. - Add
@coderabbitai summaryto generate the high-level summary at a specific location in the PR description. - Add
@coderabbitaianywhere in the PR title to generate the title automatically.
CodeRabbit Configuration File (.coderabbit.yaml)
- You can programmatically configure CodeRabbit by adding a
.coderabbit.yamlfile 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.
Mistakenly closed
Nice! :shipit: