Skip to content

refactor: ratecards in productcatalog - #2607

Merged
chrisgacsal merged 5 commits into
mainfrom
refactor/productcatalog
Apr 7, 2025
Merged

chrisgacsal merged 5 commits into
mainfrom
refactor/productcatalog

Conversation

@chrisgacsal

@chrisgacsal chrisgacsal commented Apr 6, 2025 •

Copy link
Copy Markdown
Collaborator

Overview

Simplify ratecard types in plan and addon packages.

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced deletion event processing to prevent issues when certain fields are absent, improving system stability.
  • Refactor
    • Unifed the rate card handling across products by consolidating different rate card types into one structure.
    • Streamlined data conversion and error handling routines for more consistent performance.
    • Removed redundant code to simplify internal processes and improve maintainability.

@coderabbitai

coderabbitai Bot commented Apr 6, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request refactors the rate card functionality across the add-on and plan modules. It renames local variables for clarity, consolidates distinct rate card types (FlatFeeRateCard and UsageBasedRateCard) into a unified RateCard structure, and removes redundant helper functions. The changes update JSON marshaling/unmarshaling, error assignment, and billing cadence extraction by directly calling methods on the RateCard interface. Test cases are adjusted accordingly to align with the new type structure and conversion logic.

Changes

File(s) Change Summary
openmeter/.../addon/adapter/addon.go Renamed local variable in DeleteAddon and GetAddon methods (from p to add) with no change in functionality.
openmeter/.../addon/adapter/mapping.go, openmeter/.../addon/assert.go, openmeter/.../addon/httpdriver/mapping.go Refactored rate card handling by consolidating specific types into a unified interface; removed the getBillingCadence function; modified InstanceType conversion to pass the original type directly.
openmeter/.../addon/ratecard.go, openmeter/.../addon/ratecard_test.go Removed separate FlatFee and UsageBased types; introduced a unified RateCard that embeds managed fields; updated JSON marshal/unmarshal and test structures accordingly.
openmeter/.../plan/adapter/adapter_test.go, openmeter/.../plan/adapter/mapping.go, openmeter/.../plan/assert.go, openmeter/.../plan/event.go, openmeter/.../plan/httpdriver/mapping.go Changed rate card instantiation by removing redundant nested fields; unified rate card conversion and billing cadence retrieval via method calls; updated event metadata to use safe pointer handling (lo.FromPtr).
openmeter/.../plan/ratecard.go, openmeter/.../plan/ratecard_test.go Consolidated FlatFeeRateCard and UsageBasedRateCard into a single RateCard type with updated JSON and comparison methods; adjusted tests to use the unified type.
openmeter/.../plan/service/plan.go, openmeter/.../plan/service/service_test.go Modified error assignment in DeletePlan and updated test instantiations to reference rate card types from the productcatalog package.

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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai plan to trigger planning for file edits and PR creation.
  • @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.

@chrisgacsal chrisgacsal added release-note/ignore Ignore this change when generating release notes kind/refactor Code refactor, cleanup or minor improvement labels Apr 6, 2025
@chrisgacsal
chrisgacsal marked this pull request as ready for review April 6, 2025 22:31
@chrisgacsal
chrisgacsal requested a review from a team as a code owner April 6, 2025 22:31

@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 (8)
openmeter/productcatalog/plan/ratecard_test.go (2)

27-27: Nested RateCard references may cause naming confusion.

RateCard: &RateCard{ RateCard: &productcatalog.FlatFeeRateCard{...} } can be harder to follow due to the repeated “RateCard” fields. Consider renaming one layer for clarity.

Also applies to: 40-40


168-169: Validate pointer usage after JSON unmarshal.

Unmarshalling into var rc *RateCard is effective. As a minor safeguard, consider an extra assertion to ensure rc != nil.

openmeter/productcatalog/plan/service/service_test.go (1)

654-674: Clarify free trial payment terms.

Here, the amount is set to 0 for a flat-fee trial rate card, while InArrearsPaymentTerm is still used. Although functionally valid, consider explaining why an arrears term is used for a cost of zero. It might be helpful for future maintainers to clarify that the billing term is purposely set despite the zero cost.

openmeter/productcatalog/addon/ratecard_test.go (1)

168-169: Pointer usage in JSON unmarshal.

Unmarshaling directly into var rc *RateCard is fine, but ensure subsequent code checks for rc != nil if there's any risk of malformed JSON. Otherwise, all standard library usage for decoding pointers looks good.

openmeter/productcatalog/plan/ratecard.go (1)

156-392: Removing or commenting out the legacy code.

You’ve effectively replaced all the old FlatFeeRateCard and UsageBasedRateCard wrappers with the new unified RateCard approach. If these lines are genuinely deprecated, consider permanently deleting them to keep your repository clean unless there's a near-future plan to reinstate or reference them.

-// Large code block of legacy wrappers is currently commented out.
-// ...
-// Consider removing them permanently
+// Remove deprecated code if no longer needed for reference or rollback
openmeter/productcatalog/addon/ratecard.go (3)

21-21: Refine the field documentation comment.
The phrase "the Addon the RateCard assigned to" could be slightly improved for clarity.

Consider updating it as shown:

-	// AddonID defines the Addon the RateCard assigned to.
+	// AddonID is the identifier of the Addon to which this RateCard is assigned.

69-81: Consider consistent equality checks for non-ManagedRateCard types.
The logic that checks managed fields only when v implements ManagedRateCard works, but if there's a scenario where v does not implement ManagedRateCard, the managed fields are silently skipped. Ensure this is desired behavior.


117-144: Unmarshal error message might be misleading.
When json.Unmarshal fails on a FlatFeeRateCard, the error message refers to UsageBasedRateCard. A more generic or dynamic error message would reflect the actual type being deserialized.

Consider this adjustment:

-	return fmt.Errorf("failed to JSON deserialize UsageBasedRateCard: %w", err)
+	return fmt.Errorf("failed to JSON deserialize RateCard (%s): %w", s.Type, err)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 4529975 and ebed2fc.

📒 Files selected for processing (15)
  • openmeter/productcatalog/addon/adapter/addon.go (3 hunks)
  • openmeter/productcatalog/addon/adapter/mapping.go (1 hunks)
  • openmeter/productcatalog/addon/assert.go (1 hunks)
  • openmeter/productcatalog/addon/httpdriver/mapping.go (1 hunks)
  • openmeter/productcatalog/addon/ratecard.go (2 hunks)
  • openmeter/productcatalog/addon/ratecard_test.go (13 hunks)
  • openmeter/productcatalog/plan/adapter/adapter_test.go (2 hunks)
  • openmeter/productcatalog/plan/adapter/mapping.go (2 hunks)
  • openmeter/productcatalog/plan/assert.go (1 hunks)
  • openmeter/productcatalog/plan/event.go (2 hunks)
  • openmeter/productcatalog/plan/httpdriver/mapping.go (1 hunks)
  • openmeter/productcatalog/plan/ratecard.go (1 hunks)
  • openmeter/productcatalog/plan/ratecard_test.go (13 hunks)
  • openmeter/productcatalog/plan/service/plan.go (1 hunks)
  • openmeter/productcatalog/plan/service/service_test.go (3 hunks)
🧰 Additional context used
🧬 Code Definitions (8)
openmeter/productcatalog/addon/httpdriver/mapping.go (1)
openmeter/productcatalog/addon.go (1)
  • AddonInstanceType (202-202)
openmeter/productcatalog/plan/httpdriver/mapping.go (2)
openmeter/productcatalog/ratecard.go (1)
  • RateCards (350-350)
openmeter/productcatalog/http/mapping.go (1)
  • AsRateCards (411-428)
openmeter/productcatalog/plan/adapter/adapter_test.go (2)
openmeter/productcatalog/price.go (10)
  • Price (80-87)
  • NewPriceFrom (338-360)
  • FlatPrice (362-369)
  • TieredPrice (480-490)
  • VolumeTieredPrice (448-448)
  • PriceTier (594-604)
  • PriceTierFlatPrice (651-654)
  • UnitPrice (405-410)
  • PriceTierUnitPrice (670-673)
  • Commitments (687-693)
openmeter/productcatalog/plan/service/service_test.go (1)
  • MonthPeriod (623-623)
openmeter/productcatalog/addon/adapter/addon.go (3)
openmeter/productcatalog/addon/service.go (1)
  • GetAddonInput (211-224)
openmeter/ent/db/addon.go (2)
  • Addon (18-54)
  • Addon (75-94)
openmeter/productcatalog/addon/addon.go (1)
  • Addon (13-21)
openmeter/productcatalog/plan/ratecard_test.go (2)
openmeter/productcatalog/plan/ratecard.go (1)
  • RateCard (64-67)
openmeter/productcatalog/ratecard.go (3)
  • RateCard (28-38)
  • FlatFeeRateCard (161-168)
  • UsageBasedRateCard (256-262)
openmeter/productcatalog/plan/service/service_test.go (2)
openmeter/productcatalog/ratecard.go (3)
  • UsageBasedRateCard (256-262)
  • RateCardMeta (49-77)
  • FlatFeeRateCard (161-168)
openmeter/productcatalog/price.go (10)
  • Price (80-87)
  • NewPriceFrom (338-360)
  • TieredPrice (480-490)
  • VolumeTieredPrice (448-448)
  • PriceTier (594-604)
  • FlatPrice (362-369)
  • PriceTierFlatPrice (651-654)
  • UnitPrice (405-410)
  • PriceTierUnitPrice (670-673)
  • Commitments (687-693)
openmeter/productcatalog/addon/ratecard_test.go (2)
openmeter/productcatalog/addon/ratecard.go (1)
  • RateCard (60-63)
openmeter/productcatalog/ratecard.go (3)
  • RateCard (28-38)
  • FlatFeeRateCard (161-168)
  • UsageBasedRateCard (256-262)
openmeter/productcatalog/plan/ratecard.go (2)
openmeter/productcatalog/ratecard.go (6)
  • RateCard (28-38)
  • RateCardSerde (40-42)
  • FlatFeeRateCardType (15-15)
  • FlatFeeRateCard (161-168)
  • UsageBasedRateCardType (16-16)
  • UsageBasedRateCard (256-262)
pkg/models/error.go (1)
  • NewNillableGenericValidationError (129-135)
🔇 Additional comments (41)
openmeter/productcatalog/plan/service/plan.go (1)

213-213: Proper variable reuse with assignment operator

The change from := to = is appropriate here since the err variable is already declared earlier in the function. This prevents variable shadowing and makes the error handling more consistent.

openmeter/productcatalog/addon/httpdriver/mapping.go (1)

22-22: Removed redundant type conversion

The change eliminates an unnecessary string conversion when assigning a.InstanceType to api.AddonInstanceType. Since AddonInstanceType is already defined as a string type, the direct assignment is cleaner and more efficient.

openmeter/productcatalog/plan/event.go (2)

9-9: Added import for lo utility package

The addition of the lo library import supports the safer pointer handling implemented below.


139-139: Improved nil pointer safety with lo.FromPtr

Replacing direct pointer dereferencing with lo.FromPtr() is a more robust approach that prevents potential nil pointer panics. This is particularly important for timestamp fields like DeletedAt that may be nil in some cases.

openmeter/productcatalog/addon/adapter/addon.go (4)

266-271: Improved variable naming clarity

Renaming the variable from p to add makes the code more readable and self-documenting, accurately reflecting that the variable represents an addon object.


284-285: Consistent variable naming

Continuing with the variable renaming pattern, using add.ID and add.Namespace instead of p.ID and p.Namespace maintains consistency throughout the function.


395-395: More descriptive variable naming

Changing from p to add for the result of fromAddonRow() makes the code's intent clearer to readers.


400-400: Consistent variable naming in return statement

The variable renaming is consistently applied to the return statement, completing the refactoring pattern throughout the function.

openmeter/productcatalog/plan/assert.go (1)

200-201: Improved rate card billing cadence comparison with polymorphism

The code now directly calls GetBillingCadence() on the rate cards and converts them to ISO string pointers, which is a cleaner approach compared to using type switches or assertions. This change reduces complexity while making future rate card type additions easier.

openmeter/productcatalog/plan/httpdriver/mapping.go (1)

153-155: Improved code modularity with helper function

The code now uses the http.AsRateCards() utility function to convert rate cards instead of implementing inline conversion logic. This simplifies the code while improving maintainability through centralized conversion.

The error handling is now more direct without wrapping in additional context, which is a reasonable tradeoff for simplicity as the caller can still add context if needed.

openmeter/productcatalog/addon/assert.go (1)

131-132: Simplified rate card billing cadence comparison with interface method

The code now directly calls GetBillingCadence() on the rate cards and converts them to ISO string pointers. This change eliminates the need for a separate getBillingCadence helper function that used type assertions, resulting in cleaner and more maintainable code.

openmeter/productcatalog/plan/adapter/adapter_test.go (2)

52-70: Simplified rate card struct initialization in test data

The test data initialization is now cleaner with the removal of the redundant RateCardManagedFields struct. The FlatFeeRateCard is directly initialized with the essential fields, making the test more readable and maintainable.


83-125: Simplified initialization of complex rate card in test data

The complex UsageBasedRateCard with tiered pricing is now initialized more directly without unnecessary nesting. This simplification aligns with the overall refactoring goal of streamlining rate card management while preserving the business logic of different pricing tiers and commitments.

openmeter/productcatalog/plan/adapter/mapping.go (3)

184-186: Use consistent approach for pointer vs. non-pointer fields.

These lines ensure a nil-friendly billing cadence for the flat-fee case by assigning it directly instead of wrapping with lo.FromPtr(...). This is correct given that flat-fee rate cards can have an unset (nil) cadence.


192-194: Check usage-based rate card initialization.

The usage-based rate card requires a non-nil cadence, so using lo.FromPtr(billingCadence) handles nil checks gracefully.


237-237: Consistent usage of the GetBillingCadence() interface method.

Using r.GetBillingCadence().ISOStringPtrOrNil() avoids switch-case logic for retrieving the billing cadence and keeps rate-card handling uniform.

openmeter/productcatalog/addon/adapter/mapping.go (2)

123-125: Refactored initialization of FlatFeeRateCard.

Aligns with the consolidated rate card pattern by assigning a single RateCard field that wraps the underlying flat-fee struct.


131-133: Unified approach for UsageBasedRateCard instantiation.

Similarly wraps usage-based rate cards in the new central RateCard struct, maintaining consistency across add-ons and plans.

openmeter/productcatalog/plan/ratecard_test.go (5)

86-86: Consistent usage-based rate card test initialization.

Presents a parallel structure to the flat-fee case, ensuring similar coverage and reducing test duplication.

Also applies to: 99-99


181-181: Well-structured test for a valid flat-fee rate card.

Thoroughly covers metadata, feature details, and billing cadence in the new embedded format.

Also applies to: 186-186, 199-199


245-246: Invalid flat-fee rate card scenario fully tested.

Tests negative pricing and incorrect payment terms, confirming the validator catches these errors.

Also applies to: 258-258


323-323: Usage-based rate card (valid scenario).

Verifies correct serialization/deserialization and validation for typical usage-based inputs.

Also applies to: 328-328, 341-341


395-395: Comprehensive invalid usage-based rate card testing.

Ensures negative amounts, reversed min/max commitments, and invalid codes trigger errors as expected.

Also applies to: 408-408

openmeter/productcatalog/plan/service/service_test.go (2)

252-295: Double-check boundary conditions in usage-based tier pricing.

This usage-based rate card defines a first tier with an upper boundary of 1000 units and a minimum commitment of 1000 units, which might lead to edge-case scenarios if the usage exactly equals 1000. Ensure the intended behavior accommodates inclusive tier boundaries without off-by-one or overlapping tier concerns.

Would you like a script to scan references to your tiered-pricing logic in the repository and confirm consistent boundary usage?


685-729: Maintain consistency in usage-based tier boundaries.

Similar to the earlier usage-based rate card, this structure uses a tier boundary of 1000 with a matching minimum commitment. If you intend to allow usage exactly at 1000 units under the first tier, confirm that the boundary logic is inclusive. Otherwise, consider adjusting or documenting it to avoid confusion.

openmeter/productcatalog/addon/ratecard_test.go (6)

27-82: Looks good for FlatFee serialization test.

This block tests a flat-fee rate card embedded in a broader RateCard wrapper. The JSON round-trip approach is correct. No issues noted beyond ensuring the embedded references (tax config, feature) are consistently validated in other test scenarios.


85-158: Usage-based serialization test appears correct.

Here, the usage-based rate card is also embedded and tested via JSON serialization. The structure and fields align well with other usage-based cards across the codebase. The presence of discounts is well-covered in the test scenario.


181-242: Flat-fee validation test (valid case) is comprehensive.

This segment checks a valid flat-fee rate card with embedded feature metadata and tax config. The logic thoroughly ensures each component is tested. Code readability is strong, with clear usage of assert.NoError() for validation steps.


245-302: Flat-fee validation test (invalid case) is thorough.

Your test yields an error if config JSON is invalid or if the price is negative. This negative-case coverage is well-structured. Just ensure that newly introduced validation rules (if any) also get tested here in the future.


323-390: Usage-based validation test (valid case) looks solid.

This block verifies correct usage-based rate card fields, including Commitments and properly set billing cadence. The test is robust in ensuring that standard usage-based fields (e.g., pricing, feature references) remain valid.


394-457: Usage-based validation test (invalid case) properly captures edge scenarios.

This scenario handles negative amounts, mismatched minimum/maximum usage, and invalid tax codes, ensuring the validation logic is tested for typical misconfigurations. Nicely covers potential pitfalls.

openmeter/productcatalog/plan/ratecard.go (7)

59-63: Registering interfaces for ManagedRateCard & productcatalog.RateCard.

This ensures that your custom RateCard struct satisfies both the managed fields interface and the product catalog interface. No issues; it’s a clean approach to confirm compile-time adherence.


64-67: Inline embedding of rate card and managed fields.

By embedding productcatalog.RateCard alongside RateCardManagedFields, the code compactly unifies metadata management with rate card behavior. This fosters clarity, though watch for overshadowed fields if new ones are introduced.


69-71: Exposing managed fields via ManagedFields().

Simple getter for RateCardManagedFields. This is straightforward and doesn't appear to have any issues.


73-85: Implementation of Equal().

This method delegates to ManagedRateCard equality checks first and then calls the underlying RateCard.Equal. This layering is logical. Just be cautious if future rate card expansions need deeper field-by-field checks that bypass the embedded Equal.


87-103: Validate() merges rate card and managed field checks.

The combination of r.RateCard.Validate() with r.RateCardManagedFields.Validate() is properly consolidated. The final check of phaseId is consistent with your other validations. This is well-structured.


105-119: MarshalJSON() includes rate card serde and managed fields.

Wrapping the embedded fields and type discriminant in one structure is standard for correct JSON output. This approach is tidy and consistent with the underlying productcatalog serialization patterns.


121-153: UnmarshalJSON() handles type detection and sets embedded fields.

Splitting logic between reading the RateCardSerde for type, then populating the correct underlying struct, is the standard approach to polymorphic decoding. This is well-implemented; the error messages are helpful.

openmeter/productcatalog/addon/ratecard.go (3)

55-58: Good use of compile-time interface checks.
Ensuring RateCard implements both ManagedRateCard and productcatalog.RateCard at compile time is a clean approach.


60-63: Concise struct embedding.
Merging productcatalog.RateCard and RateCardManagedFields into a single RateCard struct is a concise way to unify common fields. This helps reduce boilerplate and improves readability.


83-99: Validation logic looks solid.
The code correctly validates both the embedded RateCard and RateCardManagedFields, then adds an extra check to ensure AddonID is non-empty. This approach thoroughly covers all required fields.

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

Labels

kind/refactor Code refactor, cleanup or minor improvement release-note/ignore Ignore this change when generating release notes

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants