Repository navigation
refactor: ratecards in productcatalog - #2607
Conversation
📝 WalkthroughWalkthroughThis 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
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
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. 🪧 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 (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (8)
openmeter/productcatalog/plan/ratecard_test.go (2)
27-27: NestedRateCardreferences 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 *RateCardis effective. As a minor safeguard, consider an extra assertion to ensurerc != 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
InArrearsPaymentTermis 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 *RateCardis fine, but ensure subsequent code checks forrc != nilif 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
FlatFeeRateCardandUsageBasedRateCardwrappers with the new unifiedRateCardapproach. 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 rollbackopenmeter/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-ManagedRateCardtypes.
The logic that checks managed fields only whenvimplementsManagedRateCardworks, but if there's a scenario wherevdoes not implementManagedRateCard, the managed fields are silently skipped. Ensure this is desired behavior.
117-144: Unmarshal error message might be misleading.
Whenjson.Unmarshalfails on aFlatFeeRateCard, the error message refers toUsageBasedRateCard. 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
📒 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 operatorThe change from
:=to=is appropriate here since theerrvariable 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 conversionThe change eliminates an unnecessary string conversion when assigning
a.InstanceTypetoapi.AddonInstanceType. SinceAddonInstanceTypeis 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 packageThe addition of the lo library import supports the safer pointer handling implemented below.
139-139: Improved nil pointer safety with lo.FromPtrReplacing direct pointer dereferencing with
lo.FromPtr()is a more robust approach that prevents potential nil pointer panics. This is particularly important for timestamp fields likeDeletedAtthat may be nil in some cases.openmeter/productcatalog/addon/adapter/addon.go (4)
266-271: Improved variable naming clarityRenaming the variable from
ptoaddmakes the code more readable and self-documenting, accurately reflecting that the variable represents an addon object.
284-285: Consistent variable namingContinuing with the variable renaming pattern, using
add.IDandadd.Namespaceinstead ofp.IDandp.Namespacemaintains consistency throughout the function.
395-395: More descriptive variable namingChanging from
ptoaddfor the result offromAddonRow()makes the code's intent clearer to readers.
400-400: Consistent variable naming in return statementThe 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 polymorphismThe 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 functionThe 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 methodThe code now directly calls
GetBillingCadence()on the rate cards and converts them to ISO string pointers. This change eliminates the need for a separategetBillingCadencehelper 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 dataThe test data initialization is now cleaner with the removal of the redundant
RateCardManagedFieldsstruct. TheFlatFeeRateCardis directly initialized with the essential fields, making the test more readable and maintainable.
83-125: Simplified initialization of complex rate card in test dataThe complex
UsageBasedRateCardwith 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 theGetBillingCadence()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
RateCardfield that wraps the underlying flat-fee struct.
131-133: Unified approach for UsageBasedRateCard instantiation.Similarly wraps usage-based rate cards in the new central
RateCardstruct, 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
RateCardwrapper. 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
Commitmentsand 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
RateCardstruct 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.RateCardalongsideRateCardManagedFields, 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
ManagedRateCardequality checks first and then calls the underlyingRateCard.Equal. This layering is logical. Just be cautious if future rate card expansions need deeper field-by-field checks that bypass the embeddedEqual.
87-103: Validate() merges rate card and managed field checks.The combination of
r.RateCard.Validate()withr.RateCardManagedFields.Validate()is properly consolidated. The final check ofphaseIdis 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
RateCardSerdefor 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.
EnsuringRateCardimplements bothManagedRateCardandproductcatalog.RateCardat compile time is a clean approach.
60-63: Concise struct embedding.
Mergingproductcatalog.RateCardandRateCardManagedFieldsinto a singleRateCardstruct 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 embeddedRateCardandRateCardManagedFields, then adds an extra check to ensureAddonIDis non-empty. This approach thoroughly covers all required fields.
Overview
Simplify ratecard types in plan and addon packages.
Summary by CodeRabbit