Skip to content

feat: discount correlation ID - #2636

Merged
turip merged 2 commits into
mainfrom
feat/discount-groups
Apr 9, 2025
Merged

turip merged 2 commits into
mainfrom
feat/discount-groups

Conversation

@turip

@turip turip commented Apr 9, 2025 •

Copy link
Copy Markdown
Member

Overview

This patch introduces the discount correlationID. This is an ephemeral ULID automatically added to line ratecard discounts, so that during creation and carried over during the whole line lifecycle.

Given that this ID is carried over when line splitting happens, we can identify the total discount given for a specific correlation ID (and thus discount).

This change allows for:

  • Implementation of Unit discounts
  • Implementation of Amount discounts (later)

This approach can unlock multi-line discounts if we ever need them.

Summary by CodeRabbit

  • New Features

    • Introduced new billing discount types, including BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage.
    • Added correlation ID management for discounts to ensure consistency across invoice processing and modifications.
  • Improvements

    • Enhanced discount conversion processes for better reliability and error handling.
    • Updated existing invoice models to utilize the new billing discount structures, improving clarity and functionality.
    • Refined test coverage for discount handling, ensuring robust validation of correlation ID logic and discount behavior across various scenarios.

@coderabbitai

coderabbitai Bot commented Apr 9, 2025 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

This pull request introduces comprehensive changes to the billing discount functionality. New interfaces and types—BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage—are defined and integrated into various schemas in the client, OpenAPI, and TSP definitions. Conversion functions are added to map these new types to existing discount representations. In addition, discount-related field types and method signatures are updated throughout the HTTP driver, billing adapter, service layers, database mutation logic, and schema definitions. Test suites are updated to verify the correlation ID handling and overall consistency of the new billing discount system.

Changes

File(s) Change Summary
api/client/.../schemas.ts, api/convert.gen.go, api/convert.go Introduces new billing discount interfaces/types and updates discount property references; adds conversion functions (e.g. FromBillingDiscountPercentageToDiscountPercentage).
api/openapi.cloud.yaml, api/openapi.yaml Defines new OpenAPI objects for billing discounts with a discriminator and revises discount references in invoice rate card schemas.
api/spec/src/billing/invoices/discounts.tsp, api/spec/src/billing/invoices/invoice.tsp Adds union type and metadata models for billing discounts and updates invoice rate card models to include optional discount fields.
openmeter/billing/adapter/invoice.go, openmeter/billing/adapter/invoicelines.go Adjusts invoice update behavior (preserving ExpandedFields) and refactors invoice line processing by shifting hierarchy expansion to a dedicated method.
openmeter/billing/discount.go Establishes a robust discount management system with new types (PercentageDiscount, UsageDiscount, Discount) and methods (Clone, Equal, JSON marshaling, conversion, and correlation ID handling).
openmeter/billing/httpdriver/deprecations.go, openmeter/billing/httpdriver/discounts.go Updates discount field types from productcatalog to billing and adds helper functions to convert API billing discounts to billing package types.
openmeter/billing/invoiceline.go, openmeter/billing/invoicelinediscount.go Changes discount field types to use billing types and adds a method to remove the progressive line hierarchy from invoice lines.
openmeter/billing/service/discounts.go, openmeter/billing/service/invoiceline.go Introduces a function to generate discount correlation IDs and integrates it into invoice line creation with updated error handling.
openmeter/billing/service/lineservice/* Updates discount handling in lineservice components—including discount iteration and reference formatting—and adjusts related test files for type changes and error checks.
.../ent/db/* Revises field types and method signatures (in invoiceline, discount mutations, runtime, and setter functions) to switch from productcatalog to billing discount types, including updates to value scanners and mutation methods.
.../ent/schema/billing.go Introduces new JSON string value scanners and revises schema definitions for BillingInvoiceLine and BillingInvoiceLineDiscount to use billing discount types.
openmeter/productcatalog/http/mapping.go Adds a new helper function AsUsageDiscount that encapsulates conversion of API discount usage to a productcatalog usage discount with updated error handling.
test/billing/adapter_test.go, test/billing/discount_test.go Updates test assertions to ignore progressive line hierarchy and adds a new test suite to validate discount correlation ID handling (including ULID verification).

Possibly related PRs

  • feat: persist rate card discounts #2588: The changes in the main PR, which introduce new interfaces and types for billing discounts, are directly related to the retrieved PR, as both involve modifications to discount structures, specifically the handling and persistence of RateCardDiscounts in the context of invoice lines.
  • feat: invoice discounts api v2 #2576: The changes in the main PR, which introduce new billing discount interfaces and types, are related to the retrieved PR as both involve modifications to discount structures, specifically the BillingDiscount and BillingDiscountPercentage types, which are referenced in the context of invoice line discounts.
  • feat: add discount reason #2606: The changes in the main PR, which introduce new billing discount interfaces and types, are related to the retrieved PR, as both involve modifications to discount structures in the schemas.ts file, specifically concerning the handling of discount properties and types.

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

🪧 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.

@turip
turip force-pushed the feat/discount-groups branch 2 times, most recently from 404fb0d to 5e40940 Compare April 9, 2025 13:08
@turip turip added release-note/feature Release note: Exciting New Features area/billing labels Apr 9, 2025
@turip
turip marked this pull request as ready for review April 9, 2025 13:11
@turip
turip requested a review from a team as a code owner April 9, 2025 13:11

@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 (3)
openmeter/billing/httpdriver/discounts.go (1)

22-34: Consider adding more specific error handling for the usage discount conversion.

While the function properly handles errors by returning an empty UsageDiscount, it might be helpful to log or provide more context about what failed during the conversion.

 func AsUsageDiscount(d api.BillingDiscountUsage) billing.UsageDiscount {
 	pcUsageDiscount := api.FromBillingDiscountUsageToDiscountUsage(d)
 
 	usageDiscount, err := productcataloghttp.AsUsageDiscount(pcUsageDiscount)
 	if err != nil {
+		// Consider logging the error or providing more context
 		return billing.UsageDiscount{}
 	}
 
 	return billing.UsageDiscount{
 		UsageDiscount: usageDiscount,
 		CorrelationID: lo.FromPtrOr(d.CorrelationId, ""),
 	}
 }
openmeter/billing/service/lineservice/feeline_test.go (1)

68-70: Consider adding test cases for more scenarios.

While the test verifies the basic functionality, consider adding additional test cases for:

  1. Auto-generated correlation IDs (when none is provided)
  2. Multiple discounts with different correlation IDs
  3. Edge cases like empty correlation IDs
openmeter/billing/discount.go (1)

29-46: PercentageDiscount methods: Clone and Equal
Implementation correctly copies fields and checks hashes plus correlation ID. Consider verifying correlation IDs for empty values if that’s a concern, but logic is otherwise sound.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1fdcea6 and 5e40940.

📒 Files selected for processing (36)
  • api/client/javascript/src/client/schemas.ts (4 hunks)
  • api/convert.gen.go (1 hunks)
  • api/convert.go (1 hunks)
  • api/openapi.cloud.yaml (3 hunks)
  • api/openapi.yaml (3 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (3 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/adapter/invoicelines.go (1 hunks)
  • openmeter/billing/discount.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (4 hunks)
  • openmeter/billing/httpdriver/discounts.go (1 hunks)
  • openmeter/billing/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/discounts.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (3 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (4 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (6 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline_create.go (4 hunks)
  • openmeter/ent/db/billinginvoiceline_update.go (2 hunks)
  • openmeter/ent/db/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_create.go (4 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_update.go (2 hunks)
  • openmeter/ent/db/mutation.go (8 hunks)
  • openmeter/ent/db/runtime.go (3 hunks)
  • openmeter/ent/db/setorclear.go (2 hunks)
  • openmeter/ent/schema/billing.go (3 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • test/billing/adapter_test.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (11)
openmeter/billing/service/discounts.go (3)
openmeter/billing/discount.go (2)
  • Discount (93-98)
  • NewDiscountFrom (100-133)
pkg/slicesx/map.go (1)
  • MapWithErr (23-47)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
api/convert.go (3)
api/client/javascript/src/client/schemas.ts (4)
  • BillingDiscountPercentage (9223-9224)
  • DiscountPercentage (9337-9337)
  • BillingDiscountUsage (9225-9225)
  • DiscountUsage (9338-9338)
api/api.gen.go (4)
  • BillingDiscountPercentage (1085-1098)
  • DiscountPercentage (1986-1992)
  • BillingDiscountUsage (1104-1119)
  • DiscountUsage (2005-2013)
api/client/go/client.gen.go (4)
  • BillingDiscountPercentage (977-990)
  • DiscountPercentage (1851-1857)
  • BillingDiscountUsage (996-1011)
  • DiscountUsage (1867-1875)
api/convert.gen.go (2)
api/convert.go (2)
  • FromBillingDiscountPercentageToDiscountPercentage (14-14)
  • FromBillingDiscountUsageToDiscountUsage (15-15)
api/api.gen.go (7)
  • BillingDiscountPercentage (1085-1098)
  • DiscountPercentage (1986-1992)
  • Percentage (4691-4691)
  • DiscountPercentageType (1995-1995)
  • BillingDiscountUsage (1104-1119)
  • DiscountUsage (2005-2013)
  • DiscountUsageType (2016-2016)
openmeter/billing/httpdriver/discounts.go (4)
openmeter/productcatalog/http/mapping.go (3)
  • AsPercentageDiscount (650-654)
  • AsUsageDiscount (639-648)
  • AsDiscounts (602-637)
api/api.gen.go (3)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
  • BillingDiscount (1080-1082)
openmeter/billing/discount.go (4)
  • PercentageDiscount (23-27)
  • UsageDiscount (48-52)
  • Discounts (295-295)
  • NewDiscountFrom (100-133)
api/convert.go (2)
  • FromBillingDiscountPercentageToDiscountPercentage (14-14)
  • FromBillingDiscountUsageToDiscountUsage (15-15)
test/billing/discount_test.go (6)
test/billing/profile.go (1)
  • MinimalCreateProfileInputTemplate (12-49)
openmeter/productcatalog/feature/connector.go (1)
  • CreateFeatureInputs (17-24)
openmeter/billing/invoiceline.go (7)
  • CreateInvoiceLinesInput (761-764)
  • LineWithCustomer (782-786)
  • Line (279-293)
  • LineBase (128-162)
  • Period (83-86)
  • UsageBasedLine (703-713)
  • Price (701-701)
openmeter/productcatalog/price.go (1)
  • NewPriceFrom (342-364)
openmeter/billing/invoicelinediscount.go (1)
  • LineDiscountReasonRatecardDiscount (28-28)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (3)
  • BillingDiscount (1080-1082)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
api/client/go/client.gen.go (3)
  • BillingDiscount (972-974)
  • BillingDiscountPercentage (977-990)
  • BillingDiscountUsage (996-1011)
openmeter/billing/httpdriver/deprecations.go (2)
openmeter/billing/discount.go (3)
  • Discounts (295-295)
  • Discount (93-98)
  • NewDiscountFrom (100-133)
openmeter/billing/httpdriver/discounts.go (2)
  • AsPercentageDiscount (15-20)
  • AsDiscounts (36-64)
openmeter/billing/service/lineservice/priceunit_test.go (3)
openmeter/billing/discount.go (3)
  • NewDiscountFrom (100-133)
  • PercentageDiscount (23-27)
  • Discount (93-98)
pkg/models/percentage.go (1)
  • NewPercentage (15-28)
openmeter/billing/invoicelinediscount.go (2)
  • AmountLineDiscount (100-108)
  • LineDiscountBase (62-69)
openmeter/ent/db/runtime.go (4)
openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
  • ValueScanner (240-242)
openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1)
  • ValueScanner (105-107)
openmeter/billing/discount.go (2)
  • Discounts (295-295)
  • Discount (93-98)
openmeter/productcatalog/discount.go (2)
  • Discounts (346-346)
  • Discount (54-58)
openmeter/productcatalog/http/mapping.go (2)
openmeter/productcatalog/discount.go (2)
  • NewDiscountFrom (234-247)
  • UsageDiscount (294-296)
api/api.gen.go (1)
  • DiscountUsage (2005-2013)
openmeter/billing/discount.go (4)
pkg/models/clonable.go (1)
  • Clonable (3-5)
openmeter/billing/invoiceline.go (1)
  • Price (701-701)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
pkg/models/validator.go (1)
  • Validate (16-26)
⏰ Context from checks skipped due to timeout of 90000ms (4)
  • GitHub Check: Developer environment
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Analyze (go)
🔇 Additional comments (115)
openmeter/billing/adapter/invoice.go (1)

609-609: Good addition for preserving expansion settings

This line ensures that subsequent calls to the updated invoice will maintain the same expansion settings as specified in the input parameter. This improves API consistency, especially when chaining operations on invoices with discount-related fields.

openmeter/billing/service/lineservice/usagebasedline_test.go (1)

33-33: Appropriate type change to support discount correlation ID

Changing the discounts field type from []productcatalog.Discount to []billing.Discount aligns with the PR's objective to introduce a discount correlation ID. This moves discount handling from product catalog to billing context, which better supports tracking discounts throughout line item lifecycles.

openmeter/ent/db/billinginvoiceline.go (1)

82-82: Consistent type change for discount handling

The change from *productcatalog.Discounts to *billing.Discounts is consistent with the overall design approach in this PR. This modification allows the ratecard discounts to carry correlation IDs throughout the line item lifecycle, including during line splitting events.

openmeter/billing/invoicelinediscount.go (1)

68-68: Updated discount type to support correlation tracking

Changing SourceDiscount from *productcatalog.Discount to *billing.Discount completes the migration of discount types to the billing package. This enables correlation IDs to be maintained consistently within the line discount structure, supporting the main objective of the PR.

openmeter/billing/service/lineservice/usagebasedline.go (1)

38-38: Updated reference ID format to include correlation ID.

The format string for RateCardDiscountChildUniqueReferenceID has been changed from a numeric ID format to one that explicitly includes a correlation ID string parameter. This change aligns with the discount correlation ID feature being introduced in this PR.

openmeter/ent/db/billinginvoicelinediscount.go (1)

50-50: Type changed from *productcatalog.Discount to *billing.Discount.

The SourceDiscount field type has been updated to reference the billing package instead of productcatalog. This change is part of the broader refactoring to enhance discount management in the billing context.

openmeter/billing/service/discounts.go (1)

13-52: Newly introduced function to handle discount correlation IDs.

This function ensures that all discounts have valid correlation IDs, either by generating new ULIDs for those without IDs or validating existing ones. The implementation correctly handles both percentage and usage discount types and returns meaningful errors for invalid correlation IDs.

api/convert.gen.go (1)

6-19: New conversion functions for billing discount types.

These conversion functions facilitate the transformation between billing-specific discount types and their API representations. The functions correctly map the essential properties while handling the type conversion between different enum types.

test/billing/adapter_test.go (4)

213-214: Test assertion updated to handle new line hierarchy exclusion.

The addition of WithoutProgressiveLineHierarchy() in the line equality check ensures that progressive line hierarchy data (which would now include discount correlation IDs) is properly excluded from the test comparison.


218-219: Consistent application of line hierarchy exclusion.

Same enhancement as the previous assertion, ensuring consistent handling of line hierarchy data in equality checks for split line comparisons.


263-265: Modified assertion format for better readability.

The assertion was restructured to use the multi-line format with consistent handling of progressive line hierarchy, improving code readability while maintaining the same test behavior.


272-274: Consistent hierarchy exclusion pattern applied to final assertion.

This completes the pattern of excluding progressive line hierarchy data from all line equality checks in the test suite, ensuring consistent test behavior with the new discount correlation ID feature.

openmeter/billing/invoiceline.go (2)

155-156: Updated discount type aligns with new correlation ID system.

The RateCardDiscounts field type has been changed to Discounts (from what was likely productcatalog.Discounts), moving discount handling from the product catalog context to the billing context. This change supports the new discount correlation ID feature.


332-335: Added helper method for excluding line hierarchy from comparisons.

The new WithoutProgressiveLineHierarchy() method allows for easy exclusion of hierarchy data (which now includes correlation IDs) during equality checks. This method pairs well with the existing WithoutDBState() method and is used in test assertions.

openmeter/ent/schema/billing.go (3)

21-24: Added scanners for new billing discount types.

These new JSON value scanners enable proper ORM serialization/deserialization for the billing package discount types that incorporate correlation IDs. This is a necessary infrastructure change to support the new discount model.


352-353: Updated field type and scanner for rate card discounts.

The ratecard_discounts field is now using the billing package's Discounts type and corresponding scanner instead of what was likely the product catalog's version. This ensures that discount correlation IDs are properly stored and retrieved.


573-574: Updated field type and scanner for source discount.

Similar to the previous change, the source_discount field is now using the billing package's Discount type and corresponding scanner. This ensures consistent handling of the new discount model with correlation IDs throughout the database layer.

api/convert.go (1)

1-17: Added type conversion support for billing discount types.

This new file establishes conversion functions between API discount types that include correlation IDs (BillingDiscount*) and their simpler counterparts (Discount*). These conversions are necessary for API compatibility while introducing the new correlation ID feature.

The goverter directive will generate the actual conversion implementation code, with configurations to ensure proper type handling while avoiding redundant copy operations.

openmeter/billing/service/invoiceline.go (1)

116-119: New discount correlation ID generation added to invoice line creation

This change introduces a call to generateDiscountCorrelationIDs that processes each line's rate card discounts during invoice line creation. The implementation assigns unique identifiers to discounts so they can be tracked throughout their lifecycle, even during line splitting events.

The error handling is properly implemented to propagate any issues that might occur during correlation ID generation.

openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1)

106-107: Type changed for source discount field

The SourceDiscount field type has been changed from *productcatalog.Discount to *billing.Discount, moving the responsibility for discount representation from the product catalog package to the billing package.

This change aligns with the overall architecture shift to handle discounts within the billing context, supporting the new correlation ID feature.

openmeter/productcatalog/http/mapping.go (2)

618-624: Code refactored for better separation of concerns

The discount conversion logic has been refactored to use the new AsUsageDiscount helper function, which improves code organization and maintainability.

The error handling has been updated appropriately with a more precise error message that indicates the failure point.


639-648: New helper function added for discount conversion

A new AsUsageDiscount function has been extracted to handle the conversion from API discount usage representation to the product catalog's usage discount model.

This function properly handles quantity parsing with appropriate error messages, making the code more maintainable and the error handling more robust.

api/spec/src/billing/invoices/invoice.tsp (4)

708-709: Removed discounts from required properties

The discounts field has been removed from the required properties in the InvoiceUsageBasedRateCard model, making it optional instead of mandatory.

This change allows for more flexibility when creating rate cards without discounts.


711-716: Added optional discounts property with BillingDiscount type

A new optional discounts property has been added to the InvoiceUsageBasedRateCard model using the BillingDiscount[] type, which supports the new correlation ID feature.

The property is correctly annotated with visibility for Read, Create, and Update lifecycle stages, ensuring it can be interacted with appropriately.


780-781: Removed discounts from required properties for flat fee rate card

Similar to the usage-based rate card change, the discounts field has been removed from the required properties in the InvoiceFlatFeeRateCard model.

This aligns with the pattern of making discounts optional across rate card types.


791-796: Added optional discounts property with BillingDiscountPercentage type

A new optional discounts property has been added to the InvoiceFlatFeeRateCard model using the BillingDiscountPercentage[] type, supporting the correlation ID feature for percentage-based discounts.

The visibility annotations are consistent with the usage-based rate card, ensuring a unified approach to discount handling.

openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)

241-241: LGTM: Successfully migrated to billing.Discounts

The field type has been updated from field.TypeValueScanner[*productcatalog.Discounts] to field.TypeValueScanner[*billing.Discounts], properly aligning with the discount correlation ID feature implementation.

openmeter/billing/adapter/invoicelines.go (1)

481-495: Improved line hierarchy management with explicit error handling

The restructuring of the fetchLines method now properly expands the line hierarchy after mapping DB entities to domain models. This improvement ensures that invoice calculations have access to the complete line hierarchy with all discount correlation IDs properly maintained.

The sequential error handling for both mapping and hierarchy expansion provides better clarity on where failures might occur during the process.

openmeter/billing/service/lineservice/priceunit_test.go (5)

206-209: LGTM: Properly implements discount correlation ID

The switch from product catalog discounts to billing discounts with explicit correlation IDs aligns with the feature's goal. The correlation ID will help track discounts across line splits.


227-229: LGTM: Updated discount slice type

The slice type has been properly changed to []billing.Discount to match the new implementation.


247-248: LGTM: Child discount references correlation ID

The ChildUniqueReferenceID now correctly includes the correlation ID in the format rateCardDiscount/correlationID=discount-50pct, enabling proper tracking of discounts.


268-275: LGTM: Consistent implementation for multiple discounts

The 33% discount implementation now creates separate instances with unique correlation IDs, allowing each discount to be tracked individually through line splitting operations.


307-325: LGTM: Properly references discount correlation IDs in expected test results

The test expectations correctly include the appropriate correlation IDs for each discount, ensuring that the test validates the proper persistence of these IDs.

openmeter/ent/db/billinginvoiceline_update.go (2)

355-359: LGTM: Updated method signature to use billing.Discounts

Method signature for SetRatecardDiscounts has been properly updated to use the new *billing.Discounts type, consistent with the migration from product catalog to billing package for discount management.


1473-1477: LGTM: Consistent update to BillingInvoiceLineUpdateOne

The corresponding method in BillingInvoiceLineUpdateOne has been updated in the same manner to use *billing.Discounts, maintaining consistency across the codebase.

openmeter/billing/httpdriver/discounts.go (2)

15-20: Well-structured conversion function with proper correlation ID handling.

This function correctly converts from api.BillingDiscountPercentage to billing.PercentageDiscount, properly handling the optional correlation ID with a sensible default.


36-64: The Discount type conversion logic is well-implemented.

The function properly discriminates between different discount types, converts them appropriately, and handles errors effectively. The error messages are clear and include the specific discount type for easier debugging.

openmeter/ent/db/billinginvoicelinediscount_update.go (1)

652-654: Parameter type change consistent with earlier method.

This change is consistent with the one made to the bulk update method, maintaining consistency across the codebase.

api/spec/src/billing/invoices/discounts.tsp (3)

126-136: Well-structured union type for discount types.

The BillingDiscount union with proper discriminator pattern is a good design for representing different types of discounts in a flexible way.


137-152: Excellent documentation for the correlation ID.

The comments for BillingDiscountMetadata provide clear and detailed information about the purpose and behavior of the correlation ID, including important considerations for progressive billing scenarios.


154-170: Good reuse of existing types with composition.

Both discount models effectively use composition to extend existing product catalog models with the new billing-specific metadata, avoiding code duplication and maintaining a clean hierarchy.

openmeter/billing/service/lineservice/feeline_test.go (3)

22-28: Test input updated to include correlation ID.

The test case has been properly updated to include a correlation ID in the discount structure, which verifies the new functionality.


39-46: Updated expected output with correlation tracking.

The expected JSON now correctly includes the correlation ID in the source discount and updates the child reference ID format to include the correlation ID. This ensures proper tracking of discounts.


55-55: Type definition updated for consistency.

The RateCardDiscounts field type has been updated to use the billing package's discount type, maintaining consistency with the rest of the changes.

openmeter/ent/db/runtime.go (3)

8-8: Import change aligns with the new discount correlation ID feature.

The addition of the billing package import is necessary to support the shift from using productcatalog discount types to billing discount types, which now include correlation ID functionality.


488-488: Updated scanner type to support discount correlation IDs.

The RatecardDiscounts field scanner now uses *billing.Discounts instead of *productcatalog.Discounts, enabling the correlation ID tracking capability for discount groups.


518-518: Updated scanner type to support discount correlation IDs.

The SourceDiscount field scanner now uses *billing.Discount instead of *productcatalog.Discount, enabling the correlation ID tracking capability for individual discounts.

openmeter/billing/httpdriver/deprecations.go (4)

101-101: Updated discount type to support correlation IDs.

Changed Discounts field type from productcatalog.Discounts to billing.Discounts to enable tracking correlation IDs for discount groups in flat fee rate cards.


169-173: Updated discount mapping to support correlation ID.

The discount mapping code now:

  1. Uses the new billing.Discounts type
  2. Takes api.BillingDiscountPercentage instead of api.DiscountPercentage
  3. Calls AsPercentageDiscount which preserves the correlation ID

This ensures that correlation IDs are properly maintained when processing flat fee rate card discounts.


256-256: Updated discount type to support correlation IDs.

Changed Discounts field type from productcatalog.Discounts to billing.Discounts to enable tracking correlation IDs for discount groups in usage-based rate cards.


298-301: Simplified discount processing while supporting correlation IDs.

The code now uses AsDiscounts directly, which processes all discount types (percentage and usage) and preserves correlation IDs. This approach is simpler and more consistent than the previous implementation.

test/billing/discount_test.go (6)

22-28: Well-structured test suite for the new discount correlation ID feature.

The test suite follows the standard Go testing patterns with proper setup and structure.


30-91: Comprehensive test setup for discount correlation ID testing.

The test properly sets up the necessary environment:

  1. Creates a billing profile with progressive billing enabled
  2. Creates a test customer
  3. Sets up a meter for usage tracking
  4. Registers usage events
  5. Creates a feature tied to the meter

This setup provides a realistic context for testing discount correlation IDs.


91-138: Verifies core functionality: automatic correlation ID assignment.

This test section confirms that:

  1. New discounts automatically get assigned a correlation ID
  2. The correlation ID is a valid ULID

This validates the fundamental behavior of auto-generating correlation IDs for discounts.


140-174: Verifies correlation ID persistence during invoice processing.

This test section confirms that:

  1. Correlation IDs persist when pending lines are converted to invoice lines
  2. In progressive billing scenarios, the correlation ID is preserved across all split lines
  3. Amount discounts generated from percentage discounts retain the same correlation ID

This validates the key PR objective of maintaining correlation IDs throughout line splitting events.


176-198: Verifies unique correlation IDs for new discounts.

This test section confirms that adding a new discount generates a new correlation ID distinct from existing ones, ensuring proper tracking of separate discount entities.


201-210: Well-designed helper function for discount correlation ID extraction.

The getDiscountCorrelationID function properly handles different discount types, making the tests more readable and maintainable. Good use of type switching to handle various discount implementations.

openmeter/ent/db/billinginvoicelinediscount_create.go (3)

180-181: Updated parameter type to support discount correlation IDs.

The SetSourceDiscount method now accepts *billing.Discount instead of *productcatalog.Discount, enabling support for the correlation ID feature when creating invoice line discounts.


659-660: Updated parameter type to support discount correlation IDs.

The SetSourceDiscount method in the upsert operation now accepts *billing.Discount instead of *productcatalog.Discount, maintaining consistent type usage across different database operations.


1421-1424: Updated parameter type to support discount correlation IDs.

The SetSourceDiscount method in bulk upsert operations now accepts *billing.Discount instead of *productcatalog.Discount, ensuring that all database operations consistently use the new discount types with correlation ID support.

api/openapi.yaml (3)

10568-10641: API Schema Enhancement: New BillingDiscount Types

The addition of the BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage objects is well-structured. The use of oneOf with a discriminator (based on the type property) clearly differentiates between the percentage and usage discount variants. The defined properties—including the ULID-compatible correlationId with its regex pattern—are appropriately specified. Please ensure that all consumers of these schemas are updated accordingly to handle the new structure.


14676-14680: Schema Update: InvoiceFlatFeeRateCard Discounts

In the InvoiceFlatFeeRateCard definition, the discounts property is now defined as an array of items referencing BillingDiscountPercentage. This change indicates that flat fee rate cards currently support only percentage discounts. Confirm that this decision aligns with the intended business logic and that no support for other discount types (such as usage-based discounts) is expected for flat fee items at this stage.


15809-15813: Schema Update: InvoiceUsageBasedRateCard Discounts

The discounts property for the InvoiceUsageBasedRateCard has been updated to reference the union type BillingDiscount. This provides flexibility to support multiple discount types (as defined in the union) for usage-based line items. The update is consistent with the overall design and facilitates the tracking of discount correlation IDs during line splitting.

api/openapi.cloud.yaml (3)

10741-10808: New Billing Discount Object Definitions: Well-Structured and Documented!

The new BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage objects are defined clearly. The use of oneOf along with the discriminator on the type property ensures that consumers of the API can correctly determine which subtype they are working with. The pattern for correlationId is properly constraining the expected ULID format, and the descriptive comments provide sufficient clarity—especially noting that the invoicing engine will auto-generate the ID if not provided. Make sure that the regex pattern stays consistent with any ULID standards or libraries in use.


14602-14607: Update to InvoiceFlatFeeRateCard Discounts Property:

The discounts property for the flat fee rate card has been updated to use an array of BillingDiscountPercentage. This aligns the schema with the new billing discount types and clearly communicates that only percentage-based discounts are applicable for flat fee lines. If future requirements expand support beyond percentage discounts on these lines, reconsider referencing the broader BillingDiscount union instead.


15735-15740: Update to InvoiceUsageBasedRateCard Discounts Property:

The discounts field now correctly references the union type BillingDiscount, accommodating both percentage and usage-based discounts. This update not only supports the current discount types but also leaves room for future enhancements (such as amount discounts or multi-line discounts). The description clearly indicates the purpose of the field.

openmeter/billing/service/lineservice/discountpercentage.go (6)

53-53: Updated struct embedding from productcatalog to billing package

The discountWithChildReferenceID struct now embeds billing.PercentageDiscount instead of productcatalog.PercentageDiscount, properly aligning with the new discount correlation ID feature.


57-57: Updated parameter type to use billing package

Function signature now uses billing.Discounts instead of productcatalog.Discounts, maintaining consistency with the package transition for discount handling.


59-62: Improved loop iteration approach

Changed from an index-based loop to a value-based loop, which simplifies the code and eliminates the unused index variable.


69-71: Added validation for correlation ID

Important addition that ensures correlation IDs are present for rate card discounts, which is essential for the proper functioning of the new discount tracking feature.


75-75: Updated reference ID generation to use correlation ID

Changed from using an index to using the correlation ID, which ensures consistent reference IDs even if the order of discounts changes.


101-101: Updated discount creation to use billing package

Changed from productcatalog.NewDiscountFrom to billing.NewDiscountFrom, completing the migration to the billing package for discount handling.

openmeter/ent/db/setorclear.go (2)

1052-1064: Updated method signature to use billing package types

The SetOrClearRatecardDiscounts method signatures now accept **billing.Discounts instead of **productcatalog.Discounts, maintaining consistency with the package transition for discount handling.


1248-1260: Updated method signature to use billing package types

The SetOrClearSourceDiscount method signatures now accept **billing.Discount instead of **productcatalog.Discount, completing the migration from productcatalog to billing package for discount handling.

api/client/javascript/src/client/schemas.ts (4)

2318-2368: Well-structured implementation of discount correlation ID types

The new interfaces for BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage are well-designed with appropriate documentation. The inclusion of the optional correlationId field with clear documentation about auto-generation aligns perfectly with the PR objective of introducing ephemeral ULIDs for discount tracking across invoices.

The union type approach for BillingDiscount provides flexibility for handling different discount types while maintaining type safety.


5149-5150: Correctly updated discount type reference

The discounts field is properly updated to use the new BillingDiscountPercentage type, maintaining consistency with the newly introduced types.


5894-5895: Correctly updated discount type reference

The discounts field is properly updated to use the new BillingDiscount union type, which will allow for both percentage and usage-based discounts as mentioned in the PR description.


9222-9225: Appropriate type exports added

The new BillingDiscount types are correctly exported, making them available for use throughout the codebase.

openmeter/ent/db/mutation.go (11)

15314-15314: Type migration for discount-related fields

The field type is being updated from **productcatalog.Discounts to **billing.Discounts, consistent with the PR's objective of enhancing discount management capabilities with correlation IDs.


16427-16429: Updated setter method to match new discount type

The parameter type has been updated from *productcatalog.Discounts to *billing.Discounts to align with the field type change, while preserving the same implementation pattern.


16432-16435: Updated getter method to match new discount type

Return type has been updated from *productcatalog.Discounts to *billing.Discounts to align with the field type change, maintaining functional consistency.


16443-16446: Updated method for retrieving old discount value

Return type has been updated from *productcatalog.Discounts to *billing.Discounts while preserving the operation validation logic.


17564-17567: Updated type assertion for dynamic field setting

Type check has been updated from *productcatalog.Discounts to *billing.Discounts to ensure type safety when dynamically setting the field value.


18096-18096: Type migration for source discount field

Similarly updating the field type from **productcatalog.Discount to **billing.Discount for consistency with the new billing discount structure.


18770-18772: Updated setter method for source discount

The parameter type has been updated from *productcatalog.Discount to *billing.Discount for consistency with the field type change.


18775-18778: Updated getter method for source discount

Return type has been updated from *productcatalog.Discount to *billing.Discount to align with the field type change.


18786-18789: Updated method for retrieving old source discount value

Return type has been updated from *productcatalog.Discount to *billing.Discount while preserving the operation validation logic.


19165-19168: Updated type assertion for source discount field

Type check has been updated from *productcatalog.Discount to *billing.Discount to ensure type safety when dynamically setting the field value.


15314-19168:

Details

❓ Verification inconclusive

Comprehensive type migration for discount handling

The changes across this file represent a systematic migration from using productcatalog package types to billing package types for discount handling. This aligns perfectly with the PR objective of introducing discount correlation IDs that persist through line splitting events.

The systematic approach ensures all code paths interacting with discount fields use the consistent type, reducing the risk of type-related errors. While not explicitly visible in this file, the correlation ID functionality is likely implemented in the billing.Discount type definition itself.


🏁 Script executed:

#!/bin/bash
# Verify the structure of the new billing.Discount type to confirm it includes correlation ID
# and maintains compatibility with the previous productcatalog.Discount type

echo "Checking for billing.Discount definition..."
rg -A 20 "type Discount struct" --type go | grep -A 20 "package billing"

echo "Comparing with productcatalog.Discount definition..."
rg -A 20 "type Discount struct" --type go | grep -A 20 "package productcatalog"

Length of output: 368


Confirm discount migration and correlation ID integration

The updated code reflects the intended migration from using productcatalog discount types to the new billing discount types to enable correlation IDs during line splitting events. However, our automated search for the billing.Discount and productcatalog.Discount definitions did not return any output, so we can’t confirm from the repository that the billing.Discount type includes the new correlation ID (or that it is directly compatible with the previous type). Please manually verify that:

  • The billing.Discount structure is defined as expected and includes a field for the correlation ID.
  • All relevant code paths (including those in file openmeter/ent/db/mutation.go around lines 15314-19168) consistently use the new billing.Discount type instead of the old productcatalog.Discount type.

Thanks for confirming these details.

openmeter/ent/db/billinginvoiceline_create.go (4)

243-245: Adopted billing.Discounts parameter successfully.
Switching the parameter type to *billing.Discounts aligns with the updated discount model and appears straightforward with no immediate issues. Good job!


1229-1233: Consistent update for SetRatecardDiscounts in Upsert.
Ensuring parity with the create logic by using *billing.Discounts maintains consistency across different creation/upsert flows.


1752-1756: Delegate approach within SetRatecardDiscounts for single upsert.
The pattern of calling Update to apply the discount is clear and cohesive. No concerns here.


2464-2468: Uniform application for bulk upserts.
This final piece ensures bulk upserts are aligned with the new billing.Discounts structure. Looks good.

openmeter/billing/discount.go (22)

1-2: Package declaration
The package is well-named. No issues here.


3-11: Imports
The imports are appropriate and keep dependencies focused.


13-17: discountType interface
An excellent use of constrained interfaces to unify cloning, equality, and validation.


19-20: Comment block
Provides clear context for extended discount types.


21-27: PercentageDiscount struct
Extends productcatalog.PercentageDiscount and adds a CorrelationID. Straightforward design.


48-52: UsageDiscount struct
Mirrors the percentage discount approach with a CorrelationID. No issues spotted.


54-73: UsageDiscount methods: Clone and Equal
Builds on the same pattern as PercentageDiscount. Implementation looks consistent.


75-90: discounter interface
Combines JSON (un)marshaling, cloning, equality, validation, and typed discount methods. This abstraction is well-structured.


91-98: Discount struct
Holds union-like references with a sub-discount pointer. This is a robust approach, though ensure partial states (e.g., both percentage and usage nil) are handled gracefully.


100-133: NewDiscountFrom function
Uses generics to handle multiple input discount types seamlessly. Nice approach for type safety.


135-165: MarshalJSON
Appropriately encodes discount type and sub-struct. Fails fast on invalid types, which is good.


167-198: UnmarshalJSON
Similarly robust in decoding JSON-strict discount type. Returns descriptive errors for invalid states.


200-215: Clone method on Discount
Clones the underlying struct via lo.ToPtr, ensuring correct duplication.


217-230: Equal method on Discount
Checks discount type upfront, then defers to the respective sub-discount equality. Logical and concise.


232-241: Validate method
Delegates validation to the embedded discount. Straightforward.


243-252: ValidateForPrice method
Similarly delegates for price-based checks. Clean design.


254-256: Type method
Exposes discount’s underlying type. No issues found.


258-268: AsPercentage method
Provides typed access to a PercentageDiscount. Error handling for mismatches is appropriate.


270-280: AsUsage method
Mirrors the percentage logic. No concerns here.


282-293: WithCorrelationID
Creates a clone and sets the correlation ID on the correct sub-discount variant. Simple and effective.


295-307: Discounts type and Clone method
Slices the underlying discount array and clones each item. Implementation is robust.


309-319: ValidateForPrice on a slice of Discounts
Aggregates errors from each discount's validation. Clear approach to collecting all error messages.

@turip
turip force-pushed the feat/discount-groups branch from 5e40940 to 095ed01 Compare April 9, 2025 13:20

@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

♻️ Duplicate comments (2)
openmeter/ent/db/billinginvoicelinediscount_update.go (2)

223-224: Consistent parameter transition to billing.Discount.
This update from productcatalog.Discount to billing.Discount aligns with the broader discount-correlation refactor.


652-653: Aligning single-entity update with new discount type.
The signature change to accept a *billing.Discount is consistent with the new discount correlation ID approach.

🧹 Nitpick comments (2)
openmeter/billing/discount.go (2)

24-28: Consider validation or enforcement of CorrelationID format.
While defining CorrelationID at the struct level is useful, consider whether you want to verify that it's a valid ULID or a non-empty string to ensure data consistency if correlation tracing is critical.


283-294: Validate correlation ID upon assignment if desired.
WithCorrelationID sets the correlation ID without checks. If correlation validity is a concern, consider returning an error or logging a warning for invalid IDs.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e40940 and 095ed01.

📒 Files selected for processing (36)
  • api/client/javascript/src/client/schemas.ts (4 hunks)
  • api/convert.gen.go (1 hunks)
  • api/convert.go (1 hunks)
  • api/openapi.cloud.yaml (3 hunks)
  • api/openapi.yaml (3 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (3 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/adapter/invoicelines.go (1 hunks)
  • openmeter/billing/discount.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (4 hunks)
  • openmeter/billing/httpdriver/discounts.go (1 hunks)
  • openmeter/billing/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/discounts.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (3 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (4 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (6 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline_create.go (4 hunks)
  • openmeter/ent/db/billinginvoiceline_update.go (2 hunks)
  • openmeter/ent/db/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_create.go (4 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_update.go (2 hunks)
  • openmeter/ent/db/mutation.go (8 hunks)
  • openmeter/ent/db/runtime.go (3 hunks)
  • openmeter/ent/db/setorclear.go (2 hunks)
  • openmeter/ent/schema/billing.go (3 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • test/billing/adapter_test.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (24)
  • openmeter/billing/invoicelinediscount.go
  • openmeter/ent/db/billinginvoiceline.go
  • api/convert.gen.go
  • test/billing/adapter_test.go
  • api/spec/src/billing/invoices/invoice.tsp
  • openmeter/ent/schema/billing.go
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • openmeter/billing/service/lineservice/usagebasedline_test.go
  • api/convert.go
  • openmeter/ent/db/billinginvoicelinediscount.go
  • api/spec/src/billing/invoices/discounts.tsp
  • test/billing/discount_test.go
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go
  • openmeter/billing/adapter/invoicelines.go
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go
  • openmeter/billing/service/lineservice/discountpercentage.go
  • api/openapi.yaml
  • openmeter/ent/db/billinginvoiceline_update.go
  • openmeter/billing/httpdriver/discounts.go
  • openmeter/ent/db/setorclear.go
  • openmeter/billing/adapter/invoice.go
  • openmeter/ent/db/mutation.go
  • openmeter/ent/db/billinginvoiceline_create.go
🧰 Additional context used
🧬 Code Graph Analysis (7)
openmeter/billing/service/discounts.go (3)
openmeter/billing/discount.go (2)
  • Discount (94-99)
  • NewDiscountFrom (101-134)
pkg/slicesx/map.go (1)
  • MapWithErr (23-47)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
openmeter/billing/service/lineservice/priceunit_test.go (2)
openmeter/billing/discount.go (3)
  • NewDiscountFrom (101-134)
  • PercentageDiscount (24-28)
  • Discount (94-99)
openmeter/billing/invoicelinediscount.go (2)
  • AmountLineDiscount (100-108)
  • LineDiscountBase (62-69)
openmeter/billing/httpdriver/deprecations.go (2)
openmeter/billing/discount.go (3)
  • Discounts (296-296)
  • Discount (94-99)
  • NewDiscountFrom (101-134)
openmeter/billing/httpdriver/discounts.go (2)
  • AsPercentageDiscount (15-20)
  • AsDiscounts (36-64)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (3)
  • BillingDiscount (1080-1082)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
api/client/go/client.gen.go (3)
  • BillingDiscount (972-974)
  • BillingDiscountPercentage (977-990)
  • BillingDiscountUsage (996-1011)
openmeter/ent/db/runtime.go (4)
openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)
  • ValueScanner (240-242)
openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1)
  • ValueScanner (105-107)
openmeter/billing/discount.go (2)
  • Discounts (296-296)
  • Discount (94-99)
openmeter/productcatalog/discount.go (2)
  • Discounts (346-346)
  • Discount (54-58)
openmeter/billing/invoiceline.go (6)
api/api.gen.go (1)
  • TaxConfig (5924-5933)
api/client/go/client.gen.go (1)
  • TaxConfig (5570-5579)
openmeter/productcatalog/tax.go (1)
  • TaxConfig (36-39)
openmeter/billing/tax.go (1)
  • TaxConfig (7-7)
openmeter/billing/discount.go (1)
  • Discounts (296-296)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/discount.go (6)
pkg/models/clonable.go (1)
  • Clonable (3-5)
api/api.gen.go (3)
  • Discount (1981-1983)
  • DiscountType (1998-1998)
  • Price (4942-4944)
api/client/go/client.gen.go (1)
  • Discount (1846-1848)
openmeter/billing/invoiceline.go (1)
  • Price (701-701)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
pkg/models/validator.go (1)
  • Validate (16-26)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: E2E
  • GitHub Check: Lint
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (37)
openmeter/ent/db/runtime.go (3)

8-8: Addition of billing package import is appropriate

This import is necessary to access the new discount-related types from the billing package, supporting the transition from productcatalog to billing for discount management.


488-488: Type change reflects the migration of discount logic to billing package

Changing the ValueScanner type from *productcatalog.Discounts to *billing.Discounts aligns with the PR objective of introducing discount correlation IDs. This represents a shift in ownership of discount-related functionality from the product catalog layer to the billing layer.


518-518: Consistent type migration for discount handling

Similar to the previous change, this updates the ValueScanner type from *productcatalog.Discount to *billing.Discount, completing the migration of discount-related types to the billing package. This change is consistent with the introduction of the discount correlation ID feature.

openmeter/billing/service/discounts.go (1)

13-52: Well-structured implementation of discount correlation ID generation

The generateDiscountCorrelationIDs function provides a robust mechanism for ensuring each discount has a valid correlation ID. It correctly handles both percentage and usage discount types, generating a new ULID when needed or validating existing ones.

The error handling is comprehensive, with specific error messages for each failure case.

openmeter/billing/invoiceline.go (2)

155-156: Type change aligns with new billing discount architecture

Changing RateCardDiscounts to use the more generic Discounts type is consistent with the broader refactoring of discount handling within the codebase.


332-335: Good addition of helper method for line hierarchy management

The WithoutProgressiveLineHierarchy method provides a clean way to remove the progressive line hierarchy from a Line instance. This enhances the functionality of the Line struct and follows the same pattern as other similar methods like WithoutDBState.

openmeter/productcatalog/http/mapping.go (2)

618-624: Good refactoring to use helper function for discount processing

Replacing direct parsing with a call to the new AsUsageDiscount helper function improves code organization and maintainability.


639-648: Well-implemented helper function for usage discount conversion

The new AsUsageDiscount function properly encapsulates the logic for converting a DiscountUsage to a UsageDiscount, improving code reusability and error handling.

openmeter/billing/service/lineservice/priceunit_test.go (6)

206-209: Good transition to use discount correlation IDs in tests

Tests now use the new billing discount structures with correlation IDs, which aligns with the broader discount correlation ID feature implementation.


227-229: Updated discount array type to match new implementation

The type change from productcatalog.Discount to billing.Discount correctly aligns the test with the updated discount handling architecture.


247-248: Effective correlation ID reference in child unique reference ID

Using a formatted string that includes the correlation ID in the ChildUniqueReferenceID provides clear traceability between the discount and its effects.


268-276: Good implementation of multiple discounts with unique correlation IDs

Creating multiple discount instances with distinct correlation IDs demonstrates the feature's capability to track individual discounts even when multiple are applied to the same line item.


287-291: Correct usage of billing discount variables in test case

The test correctly uses the refactored discount variables with their unique correlation IDs in the test case definition.


307-310: Consistent application of correlation ID references across multiple discounts

Each discount's child unique reference ID correctly incorporates its specific correlation ID, ensuring proper tracking through the discount lifecycle.

Also applies to: 315-318, 324-327

openmeter/billing/service/lineservice/feeline_test.go (4)

22-27: Refactored discount initialization.
Switching from productcatalog.PercentageDiscount to billing.PercentageDiscount and adding the correlation ID field is consistent with the new discount-correlation flow.


39-45: Creating nested billing discount with correlation ID.
Wrapping the productcatalog.PercentageDiscount inside billing.PercentageDiscount via billing.NewDiscountFrom and personalizing ChildUniqueReferenceID with the correlation ID is a clean approach.


55-55: Transition to []billing.PercentageDiscount.
Changing the RateCardDiscounts array type ensures consistency with the rest of the refactor.


68-70: Mapping discounts with billing.NewDiscountFrom.
Using lo.Map to convert each PercentageDiscount into a billing.Discount is correct and streamlined.

openmeter/billing/httpdriver/deprecations.go (3)

101-101: Field type migrated to billing.Discounts.
This replacement of productcatalog.Discounts with billing.Discounts is consistent with the new discount architecture.


169-172: Mapping BillingDiscountPercentage into billing.Discount.
Introducing a local discounts variable and converting the slice with billing.NewDiscountFrom simplifies usage and ensures correct correlation ID handling.


298-300: Consolidated multi-discount parsing.
Defining discounts and using AsDiscounts to parse complex discount inputs unifies discount handling logic.

api/openapi.cloud.yaml (3)

10741-10817: Introduce new billing discount schemas with correlation ID support
This hunk correctly defines the new discount schemas—BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage—using a oneOf construct along with a discriminator based on the type property. The inclusion of the correlationId field—with its regex pattern and supporting description—is in line with the objective of tracking discounts across invoices. Please ensure that any upstream or downstream components that interact with discount objects have been updated to handle these new definitions.


14602-14606: Update InvoiceFlatFeeRateCard discounts field to use BillingDiscountPercentage
The modifications update the discounts property for InvoiceFlatFeeRateCard to reference the new BillingDiscountPercentage schema. This change aligns with the overall refactoring to support discount correlation IDs and provides more structured discount information.


15735-15740: Update InvoiceUsageBasedRateCard discounts field to support unified BillingDiscount types
By changing the reference to BillingDiscount for the discounts array in InvoiceUsageBasedRateCard, this hunk now supports a polymorphic discount structure that can encompass both percentage and usage discounts. This change not only enables multi-line discount scenarios in the future but also facilitates the proper tracking of discount correlation IDs.

openmeter/ent/db/billinginvoicelinediscount_create.go (5)

180-182: Type changed from productcatalog.Discount to billing.Discount

This change is part of the broader refactoring to use the new BillingDiscount type with correlation ID support. The method signature update ensures that the discount correlation ID will be properly carried throughout the invoicing lifecycle.


659-662: Type updated in BillingInvoiceLineDiscountUpsert

Consistent type update from productcatalog.Discount to billing.Discount for the upsert operation, maintaining type consistency across all discount-related operations.


952-956: Type updated in BillingInvoiceLineDiscountUpsertOne

The type change here maintains consistency with the other discount-related methods, ensuring that the correlation ID is preserved during single-record upsert operations.


1421-1425: Type updated in BillingInvoiceLineDiscountUpsertBulk

This completes the type changes across all discount-related bulk operations, providing a consistent interface for handling the new discount structure with correlation ID support.


308-312:

Details

❓ Verification inconclusive

Ensure the Validate method compatibility

The code calls Validate() on the source_discount field. Verify that the new billing.Discount type implements this method with the same validation semantics as the previous productcatalog.Discount type.


🏁 Script executed:

#!/bin/bash
# Check the Validate method implementation in billing.Discount
echo "Checking implementation of Validate() method in billing.Discount"
rg -A 5 "func \(\*?Discount\) Validate\(\) error" --type go openmeter/billing/

Length of output: 219


I'm not seeing evidence for a billing.Discount.Validate() implementation with the previous command. To gather more clarity, please run the following additional verification scripts:

Once we have the output, we can determine if the new billing.Discount type implements Validate() with the correct semantics.


🏁 Script executed:

#!/bin/bash
echo "Searching for any Validate method implementations related to billing.Discount in the billing package..."
rg "func\s+\(.*Discount\).*Validate\(" --type go openmeter/billing/ -n

echo "Searching for the billing.Discount type declaration..."
rg -A 10 "type\s+Discount\s+struct" --type go openmeter/billing/ -n

Length of output: 1547


Validate Method Compatibility Check

The call to Validate() on the source_discount field now invokes the implementation defined at openmeter/billing/discount.go:233. Please ensure that the validation logic (checks, error wrapping, etc.) in the new billing.Discount implementation fully aligns with the semantics of the previous productcatalog.Discount.Validate() method. Manual verification is recommended to compare the business logic and error handling details if automated inspection isn’t sufficient.

  • Verify the implementation in openmeter/billing/discount.go (around line 233) against the previous productcatalog.Discount.Validate().
  • Ensure that any changes in validation behavior (if any) are intentional and properly documented.
api/client/javascript/src/client/schemas.ts (4)

2318-2368: Well-structured discount types with correlation ID support

The new BillingDiscount union type and its variants (BillingDiscountPercentage and BillingDiscountUsage) are well-defined with appropriate documentation. The optional correlationId field in both discount types implements the core feature of this PR - tracking discounts across their lifecycle.

The auto-generation note for correlationId aligns with the PR objective of automatically assigning ULIDs to discounts, and the example ULID provided (01G65Z755AFWAKHE12NY0CQ9FH) follows the expected format.


5149-5150: Fixed discount type for flat fee rate cards

The update restricts the discounts for invoice flat fee rate cards to percentage-based discounts only (BillingDiscountPercentage). This makes sense for flat fee pricing models where percentage discounts are most applicable.


5894-5895: Flexible discount types for usage-based rate cards

Usage-based rate cards now support both discount types (percentage and usage-based) through the BillingDiscount union type. This provides more flexibility and aligns with the PR objectives of supporting both unit (percentage) and amount (usage) discounts.


9222-9225: Appropriate type exports for better accessibility

These type exports make the new discount types easily accessible throughout the codebase, which is good practice for TypeScript projects.

openmeter/billing/discount.go (4)

14-18: Well-structured interface.
Defining a generic interface discountType[T] that composes Clonable, Equaler, and Validator is a clean approach to enforcing consistent behavior across discount types.


30-35: Good clone method implementation.
This succinctly preserves the original data. If you anticipate concurrent modifications, you might explore more defensive copying or concurrency controls, but for most use cases, this approach is sufficient.


37-47: Equality logic is coherent.
Comparing both the underlying discount hash and correlation ID is a reliable way to ensure two PercentageDiscount instances are equivalent.


296-321: Checks for aggregated discounts look solid.
The Discounts slice cloning and validation logic is straightforward and should handle multiple discounts gracefully.

Comment thread openmeter/billing/discount.go Resolved
@turip
turip force-pushed the feat/discount-groups branch from 095ed01 to 5507a83 Compare April 9, 2025 14:33

@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

♻️ Duplicate comments (2)
openmeter/billing/discount.go (2)

101-134: ** Return an error instead of an empty discount.**

This logic still returns an empty Discount in the default case. This can obscure real issues where an unrecognized type is passed. Consider returning an explicit error:

 default:
-   return Discount{}
+   return Discount{}, fmt.Errorf("unrecognized discount type: %T", in)

201-216: 🛠️ Refactor suggestion

Handle unknown discount types instead of producing an empty discount.

When cloning an unrecognized discount type, the code silently returns an empty Discount. This might lead to silent data corruption. A more explicit error handling or panic could aid debugging and prevent hidden data mismatches.

-case productcatalog.UsageDiscountType:
-   return Discount{
-       t:     d.t,
-       usage: lo.ToPtr(d.usage.Clone()),
-   }
-}
-return Discount{}
+default:
+   panic(fmt.Sprintf("unknown discount type in Clone(): %s", d.t))
🧹 Nitpick comments (4)
openmeter/billing/httpdriver/discounts.go (1)

1-2: Consider adding more descriptive documentation for the code generation directive.

The comment indicates code generation using goverter, but there's no context about what's being generated. A more descriptive comment would improve maintainability.

-//go:generate go run github.com/jmattheis/goverter/cmd/goverter gen ./
+//go:generate go run github.com/jmattheis/goverter/cmd/goverter gen ./
+// This generates converter functions between API and internal billing discount types
api/openapi.cloud.yaml (2)

10741-10815: Review new BillingDiscount schemas and correlationId usage.
The new BillingDiscount definition along with its BillingDiscountPercentage and BillingDiscountUsage variants are clearly structured. The use of a discriminator on the type property is appropriate, and the correlation ID is validated using a regex pattern to match ULID expectations.

Suggestions:

  • Consider explicitly noting in the description that the correlationId follows the ULID format for clarity.
  • Verify that the enum values for type in the sub-schemas align perfectly with the mapping values in the discriminator.

14592-14607: Review InvoiceFlatFeeRateCard discount reference update.
The discounts property for InvoiceFlatFeeRateCard is updated to reference BillingDiscountPercentage instead of the older discount schema. This change is consistent with supporting percentage discounts via the new structure.

Consideration:

  • Confirm that flat fee rate cards are intended to exclusively use percentage discounts. If there’s future potential for including other discount types on flat fee rate cards, you may want to consider referencing the broader BillingDiscount union instead.
openmeter/billing/discount.go (1)

296-321: Add dedicated test coverage for Discounts.

Discounts includes essential logic to clone and validate multiple discounts. Ensure you have unit tests verifying each discount type’s behavior to avoid regressions.

Would you like help generating a test suite to cover bulk discount management, including multi-line scenarios and correlation ID checks?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 095ed01 and 5507a83.

📒 Files selected for processing (36)
  • api/client/javascript/src/client/schemas.ts (4 hunks)
  • api/convert.gen.go (1 hunks)
  • api/convert.go (1 hunks)
  • api/openapi.cloud.yaml (3 hunks)
  • api/openapi.yaml (3 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (3 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/adapter/invoicelines.go (1 hunks)
  • openmeter/billing/discount.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (4 hunks)
  • openmeter/billing/httpdriver/discounts.go (1 hunks)
  • openmeter/billing/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/discounts.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (3 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (4 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (6 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline_create.go (4 hunks)
  • openmeter/ent/db/billinginvoiceline_update.go (2 hunks)
  • openmeter/ent/db/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_create.go (4 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_update.go (2 hunks)
  • openmeter/ent/db/mutation.go (8 hunks)
  • openmeter/ent/db/runtime.go (3 hunks)
  • openmeter/ent/db/setorclear.go (2 hunks)
  • openmeter/ent/schema/billing.go (3 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • test/billing/adapter_test.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (26)
  • openmeter/billing/adapter/invoice.go
  • openmeter/billing/invoicelinediscount.go
  • openmeter/billing/service/lineservice/usagebasedline_test.go
  • openmeter/ent/db/billinginvoicelinediscount.go
  • api/convert.go
  • api/convert.gen.go
  • openmeter/billing/adapter/invoicelines.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • test/billing/adapter_test.go
  • api/spec/src/billing/invoices/invoice.tsp
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/service/lineservice/priceunit_test.go
  • openmeter/billing/service/lineservice/feeline_test.go
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go
  • api/spec/src/billing/invoices/discounts.tsp
  • openmeter/ent/db/billinginvoiceline.go
  • openmeter/ent/db/setorclear.go
  • openmeter/ent/schema/billing.go
  • openmeter/ent/db/runtime.go
  • openmeter/ent/db/billinginvoiceline_update.go
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go
  • openmeter/billing/service/lineservice/discountpercentage.go
  • openmeter/ent/db/billinginvoicelinediscount_update.go
  • api/openapi.yaml
  • openmeter/ent/db/mutation.go
  • openmeter/ent/db/billinginvoiceline_create.go
🧰 Additional context used
🧬 Code Graph Analysis (7)
openmeter/billing/service/discounts.go (3)
openmeter/billing/discount.go (2)
  • Discount (94-99)
  • NewDiscountFrom (101-134)
pkg/slicesx/map.go (1)
  • MapWithErr (23-47)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
openmeter/billing/invoiceline.go (6)
api/api.gen.go (1)
  • TaxConfig (5924-5933)
api/client/go/client.gen.go (1)
  • TaxConfig (5570-5579)
openmeter/productcatalog/tax.go (1)
  • TaxConfig (36-39)
openmeter/billing/tax.go (1)
  • TaxConfig (7-7)
openmeter/billing/discount.go (1)
  • Discounts (296-296)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/httpdriver/deprecations.go (2)
openmeter/billing/discount.go (3)
  • Discounts (296-296)
  • Discount (94-99)
  • NewDiscountFrom (101-134)
openmeter/billing/httpdriver/discounts.go (2)
  • AsPercentageDiscount (15-20)
  • AsDiscounts (36-64)
openmeter/billing/httpdriver/discounts.go (4)
openmeter/productcatalog/http/mapping.go (2)
  • AsPercentageDiscount (645-649)
  • AsUsageDiscount (634-643)
api/api.gen.go (3)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
  • BillingDiscount (1080-1082)
openmeter/billing/discount.go (3)
  • PercentageDiscount (24-28)
  • UsageDiscount (49-53)
  • NewDiscountFrom (101-134)
api/convert.go (2)
  • FromBillingDiscountPercentageToDiscountPercentage (14-14)
  • FromBillingDiscountUsageToDiscountUsage (15-15)
test/billing/discount_test.go (3)
test/billing/profile.go (1)
  • MinimalCreateProfileInputTemplate (12-49)
openmeter/billing/invoiceline.go (6)
  • CreateInvoiceLinesInput (761-764)
  • LineWithCustomer (782-786)
  • Line (279-293)
  • LineBase (128-162)
  • Period (83-86)
  • UsageBasedLine (703-713)
openmeter/billing/discount.go (4)
  • Discounts (296-296)
  • NewDiscountFrom (101-134)
  • PercentageDiscount (24-28)
  • Discount (94-99)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (3)
  • BillingDiscount (1080-1082)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
api/client/go/client.gen.go (3)
  • BillingDiscount (972-974)
  • BillingDiscountPercentage (977-990)
  • BillingDiscountUsage (996-1011)
openmeter/billing/discount.go (3)
pkg/models/clonable.go (1)
  • Clonable (3-5)
openmeter/billing/invoiceline.go (1)
  • Price (701-701)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Test
  • GitHub Check: Lint
  • GitHub Check: Build
  • GitHub Check: Analyze (go)
🔇 Additional comments (27)
openmeter/billing/httpdriver/deprecations.go (3)

101-101: Field type update to support discount correlation ID

The Discounts field type has been changed from productcatalog.Discounts to billing.Discounts to support the new discount correlation ID functionality.


169-173: Updated discount handling to use new discount types

The discount mapping logic has been updated to use the new api.BillingDiscountPercentage type and billing.NewDiscountFrom function with AsPercentageDiscount, which preserves correlation IDs during the mapping process.


298-301: Simplified discount processing for usage-based rate cards

The usage-based discount processing has been refactored to use AsDiscounts directly, which handles the conversion of the entire discount collection including correlation IDs.

openmeter/billing/service/discounts.go (1)

13-52: Well-implemented correlation ID generation for discounts

This function properly handles the generation and validation of correlation IDs for both percentage and usage discounts. It:

  1. Uses ULID for generating unique, sortable identifiers
  2. Preserves existing correlation IDs
  3. Validates the format of existing correlation IDs
  4. Properly handles different discount types
  5. Utilizes the slicesx.MapWithErr helper for clean error propagation

The implementation aligns well with the PR's objective to introduce a discount correlation ID that persists throughout the lifecycle of a line item.

openmeter/billing/invoiceline.go (2)

155-156: Updated RateCardDiscounts field type to support correlation IDs

The RateCardDiscounts field type has been updated from productcatalog.Discounts to Discounts to support the new discount correlation ID feature.


332-335: Added utility method for removing progressive line hierarchy

This new method WithoutProgressiveLineHierarchy provides a convenient way to set the ProgressiveLineHierarchy field to nil and return a pointer to the modified Line instance.

While not directly related to the discount correlation ID feature, this helper method will be useful for operations that need to manipulate the line hierarchy, particularly during line splitting events mentioned in the PR objectives.

openmeter/productcatalog/http/mapping.go (2)

613-619: Improved code structure by extracting discount usage conversion logic

The discount usage conversion logic has been extracted into a dedicated helper function, which improves code organization and reusability. The error message has been updated to be more specific about the issue.


634-643: Well-implemented usage discount conversion helper

This new AsUsageDiscount function cleanly encapsulates the logic for converting an api.DiscountUsage to a productcatalog.UsageDiscount, including proper error handling for the quantity parsing.

The function follows the pattern established by AsPercentageDiscount, providing consistency in the codebase.

openmeter/billing/httpdriver/discounts.go (2)

15-20: Solid implementation of discount percentage conversion.

The AsPercentageDiscount function correctly transforms an API discount percentage into the billing package's representation, properly handling the correlation ID field.


36-64: Comprehensive implementation of discount type conversion.

The AsDiscounts function properly handles the conversion of multiple discount types, with appropriate error handling for both invalid discount types and conversion failures.

test/billing/discount_test.go (4)

31-139: Well-structured test for correlation ID assignment to new discounts.

The test correctly verifies that correlation IDs are automatically assigned to discounts when creating new pending invoice lines, and confirms that these IDs are valid ULIDs.


141-175: Good verification of correlation ID retention in progressive billing.

This portion of the test properly checks that correlation IDs are preserved when pending lines are invoiced in a progressive billing setup, including verification across parent and child lines.


177-199: Complete testing of correlation ID generation for new discounts.

This test correctly verifies that adding a new discount to an existing invoice generates a new, distinct correlation ID, while preserving the original discount's correlation ID.


202-211: Clean helper function for extracting correlation IDs.

The getDiscountCorrelationID function efficiently extracts correlation IDs based on discount type, making the test code more readable and maintainable.

api/openapi.cloud.yaml (1)

15735-15741: Review InvoiceUsageBasedRateCard discount reference update.
The discounts property for InvoiceUsageBasedRateCard now uses the union type BillingDiscount, which appropriately allows for both percentage and usage discounts. This update should facilitate the intended support for multi-type and potentially multi-line discounts.

Recommendation:

  • Ensure that any conversion functions or backend logic that process these discounts are updated to handle the union type and discriminator logic correctly.
openmeter/ent/db/billinginvoicelinediscount_create.go (6)

179-182: Confirmed type change from productcatalog.Discount to billing.Discount

The SetSourceDiscount method signature has been updated to use the *billing.Discount type instead of *productcatalog.Discount. This change aligns with the PR objective of enhancing the discount management system by centralizing discount functionality within the billing package.


658-662: Consistent type change in Upsert functionality

The parameter type for SetSourceDiscount in the BillingInvoiceLineDiscountUpsert struct has been properly updated to match the type change in the Create struct.


951-956: Consistent type propagation in UpsertOne

The type change has been consistently applied to the BillingInvoiceLineDiscountUpsertOne struct's SetSourceDiscount method. This ensures type consistency throughout the invoice line discount operations.


1420-1425: Complete type migration in bulk operations

The SetSourceDiscount method in the BillingInvoiceLineDiscountUpsertBulk struct has been updated to use *billing.Discount, completing the type transition across all relevant structs in this file. This systematic approach ensures consistency throughout the codebase.


16-19: Package import alignment with new discount type

The imports have been properly updated to include the billing package while removing the now unused productcatalog import. This change supports the migration of discount functionality from productcatalog to billing package.


308-312: Validation check maintained for new type

The code correctly maintains the validation check for the source_discount field. This ensures that the new billing.Discount type is validated before being stored, maintaining data integrity while transitioning to the new discount model.

api/client/javascript/src/client/schemas.ts (4)

2318-2368: Well-structured discount types with clear documentation

The addition of BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage interfaces matches the Go implementation from the relevant code snippets. The JSDoc comments provide comprehensive documentation, especially for the correlationId field which clearly explains its purpose for linking discounts across invoices during progressive billing.

The union type approach for BillingDiscount allows for flexibility in discount types while maintaining type safety. The example ULID provided for correlationId (01G65Z755AFWAKHE12NY0CQ9FH) is helpful for developers implementing this feature.


5149-5150: Appropriate type update for flat fee rate card discounts

Changing the discounts property to use BillingDiscountPercentage[] is appropriate for flat fee rate cards, which typically only support percentage-based discounts. This aligns with the PR objective of introducing discount correlation IDs while maintaining type specificity.


5894-5895: Good use of union type for usage-based rate card discounts

Using the more general BillingDiscount[] union type here is appropriate for usage-based rate cards, as they may support both percentage-based and usage-based discounts. This enables the future support for multiple discount types as mentioned in the PR objectives.


9222-9225: Exports properly expose new discount types

These export statements make the new types available for external consumption, which is necessary for client code to properly use the new discount structures. All three types are correctly exported.

openmeter/billing/discount.go (2)

14-18: Interface definition looks well-structured.

The discountType[T any] interface enforces crucial contracts (cloning, equality, validation) clearly. This makes each discount type consistently implemented and easy to extend.


24-74:

Details

❓ Verification inconclusive

Ensure the hash method accurately represents all fields for equality checks.

Both PercentageDiscount and UsageDiscount rely on Hash() for equality, then comparing CorrelationID. Confirm the Hash() function from productcatalog logic thoroughly accounts for all relevant fields (e.g., rates, thresholds) so there’s no collision risk.

Run the following shell script to locate and review the Hash() method within productcatalog for completeness:


🏁 Script executed:

#!/bin/bash
# Searching for the Hash() method definition within productcatalog
ast-grep --pattern $'func ($_*).Hash() $_* { $$$ }'

Length of output: 52


Below is an updated verification script to more specifically search for any definitions of a Hash() method within the productcatalog package. Please run it and verify that the implementation indeed accounts for all the relevant fields (such as rates, thresholds, etc.) needed for accurate equality checking:

#!/bin/bash
# Searching specifically within the productcatalog directory for any Hash() method definitions
rg -n 'func\s+.*\.Hash\s*\(' productcatalog/

If this search still yields no results, please manually verify (or provide guidance) that the productcatalog package indeed implements the Hash() method correctly.

chrisgacsal
chrisgacsal previously approved these changes Apr 9, 2025
@turip
turip force-pushed the feat/discount-groups branch from 6969b17 to b9aad73 Compare April 9, 2025 15:23

@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 (1)
api/openapi.cloud.yaml (1)

14602-14606: Ensure Consistency for Flat Fee Rate Card Discounts
In the InvoiceFlatFeeRateCard schema, the discounts property now strictly references BillingDiscountPercentage. Confirm that this constraint is intentional—particularly as the overall design supports a union type for discounts. If there is a future plan to include other discount types (such as unit or amount discounts) for flat fee scenarios, consider aligning this property with the union type (BillingDiscount) or document the limitation clearly.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5507a83 and b9aad73.

📒 Files selected for processing (36)
  • api/client/javascript/src/client/schemas.ts (4 hunks)
  • api/convert.gen.go (1 hunks)
  • api/convert.go (1 hunks)
  • api/openapi.cloud.yaml (3 hunks)
  • api/openapi.yaml (3 hunks)
  • api/spec/src/billing/invoices/discounts.tsp (1 hunks)
  • api/spec/src/billing/invoices/invoice.tsp (3 hunks)
  • openmeter/billing/adapter/invoice.go (1 hunks)
  • openmeter/billing/adapter/invoicelines.go (1 hunks)
  • openmeter/billing/discount.go (1 hunks)
  • openmeter/billing/httpdriver/deprecations.go (4 hunks)
  • openmeter/billing/httpdriver/discounts.go (1 hunks)
  • openmeter/billing/invoiceline.go (2 hunks)
  • openmeter/billing/invoicelinediscount.go (1 hunks)
  • openmeter/billing/service/discounts.go (1 hunks)
  • openmeter/billing/service/invoiceline.go (1 hunks)
  • openmeter/billing/service/lineservice/discountpercentage.go (3 hunks)
  • openmeter/billing/service/lineservice/feeline_test.go (4 hunks)
  • openmeter/billing/service/lineservice/priceunit_test.go (6 hunks)
  • openmeter/billing/service/lineservice/usagebasedline.go (1 hunks)
  • openmeter/billing/service/lineservice/usagebasedline_test.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1 hunks)
  • openmeter/ent/db/billinginvoiceline_create.go (4 hunks)
  • openmeter/ent/db/billinginvoiceline_update.go (2 hunks)
  • openmeter/ent/db/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go (1 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_create.go (4 hunks)
  • openmeter/ent/db/billinginvoicelinediscount_update.go (2 hunks)
  • openmeter/ent/db/mutation.go (8 hunks)
  • openmeter/ent/db/runtime.go (3 hunks)
  • openmeter/ent/db/setorclear.go (2 hunks)
  • openmeter/ent/schema/billing.go (3 hunks)
  • openmeter/productcatalog/http/mapping.go (2 hunks)
  • test/billing/adapter_test.go (2 hunks)
  • test/billing/discount_test.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (28)
  • openmeter/billing/service/lineservice/usagebasedline_test.go
  • openmeter/billing/service/discounts.go
  • test/billing/adapter_test.go
  • openmeter/billing/adapter/invoice.go
  • openmeter/billing/service/lineservice/usagebasedline.go
  • openmeter/ent/db/billinginvoiceline.go
  • api/convert.gen.go
  • openmeter/ent/db/billinginvoicelinediscount.go
  • openmeter/billing/service/invoiceline.go
  • openmeter/billing/adapter/invoicelines.go
  • api/convert.go
  • openmeter/ent/db/billinginvoicelinediscount/billinginvoicelinediscount.go
  • openmeter/ent/db/billinginvoicelinediscount_update.go
  • api/spec/src/billing/invoices/discounts.tsp
  • openmeter/billing/service/lineservice/priceunit_test.go
  • openmeter/ent/schema/billing.go
  • api/spec/src/billing/invoices/invoice.tsp
  • openmeter/billing/invoicelinediscount.go
  • openmeter/ent/db/billinginvoicelinediscount_create.go
  • api/openapi.yaml
  • openmeter/billing/httpdriver/discounts.go
  • openmeter/billing/httpdriver/deprecations.go
  • openmeter/ent/db/billinginvoiceline_update.go
  • openmeter/billing/service/lineservice/discountpercentage.go
  • openmeter/ent/db/setorclear.go
  • openmeter/ent/db/mutation.go
  • openmeter/ent/db/billinginvoiceline_create.go
  • openmeter/billing/discount.go
🧰 Additional context used
🧬 Code Graph Analysis (5)
openmeter/productcatalog/http/mapping.go (5)
openmeter/billing/httpdriver/discounts.go (1)
  • AsUsageDiscount (22-34)
openmeter/billing/discount.go (2)
  • NewDiscountFrom (101-134)
  • UsageDiscount (49-53)
openmeter/productcatalog/discount.go (2)
  • NewDiscountFrom (234-247)
  • UsageDiscount (294-296)
api/api.gen.go (1)
  • DiscountUsage (2005-2013)
api/client/go/client.gen.go (1)
  • DiscountUsage (1867-1875)
openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (2)
openmeter/billing/discount.go (1)
  • Discounts (296-296)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
openmeter/billing/invoiceline.go (6)
api/api.gen.go (1)
  • TaxConfig (5924-5933)
api/client/go/client.gen.go (1)
  • TaxConfig (5570-5579)
openmeter/productcatalog/tax.go (1)
  • TaxConfig (36-39)
openmeter/billing/tax.go (1)
  • TaxConfig (7-7)
openmeter/billing/discount.go (1)
  • Discounts (296-296)
openmeter/productcatalog/discount.go (1)
  • Discounts (346-346)
test/billing/discount_test.go (5)
test/billing/profile.go (1)
  • MinimalCreateProfileInputTemplate (12-49)
openmeter/billing/invoiceline.go (6)
  • CreateInvoiceLinesInput (761-764)
  • LineWithCustomer (782-786)
  • Line (279-293)
  • LineBase (128-162)
  • Period (83-86)
  • UsageBasedLine (703-713)
openmeter/billing/discount.go (4)
  • Discounts (296-296)
  • NewDiscountFrom (101-134)
  • PercentageDiscount (24-28)
  • Discount (94-99)
openmeter/billing/invoicelinediscount.go (1)
  • LineDiscountReasonRatecardDiscount (28-28)
openmeter/productcatalog/discount.go (2)
  • PercentageDiscountType (16-16)
  • UsageDiscountType (17-17)
api/client/javascript/src/client/schemas.ts (2)
api/api.gen.go (3)
  • BillingDiscount (1080-1082)
  • BillingDiscountPercentage (1085-1098)
  • BillingDiscountUsage (1104-1119)
api/client/go/client.gen.go (3)
  • BillingDiscount (972-974)
  • BillingDiscountPercentage (977-990)
  • BillingDiscountUsage (996-1011)
⏰ Context from checks skipped due to timeout of 90000ms (7)
  • GitHub Check: E2E
  • GitHub Check: CI
  • GitHub Check: Quickstart
  • GitHub Check: Test
  • GitHub Check: Developer environment
  • GitHub Check: Commit hooks
  • GitHub Check: Analyze (go)
🔇 Additional comments (23)
openmeter/ent/db/runtime.go (3)

8-8: Added billing package import to support new discount types.

The addition of this import is necessary to support the new billing-specific discount types that have been migrated from the productcatalog package.


492-492: Changed RatecardDiscounts value scanner type from productcatalog to billing package.

This change correctly updates the ValueScanner type for RatecardDiscounts to use the new discount types from the billing package instead of the productcatalog package. This aligns with the PR objective of enhancing discount management capabilities.


522-522: Changed SourceDiscount value scanner type from productcatalog to billing package.

This change correctly updates the ValueScanner type for SourceDiscount to use the new discount types from the billing package instead of the productcatalog package. This is consistent with the migration of discount types to support the correlation ID feature.

openmeter/ent/db/billinginvoiceline/billinginvoiceline.go (1)

241-241:

Details

✅ Verification successful

Migration from productcatalog.Discounts to billing.Discounts

The change correctly updates the RatecardDiscounts field type from field.TypeValueScanner[*productcatalog.Discounts] to field.TypeValueScanner[*billing.Discounts], aligning with the PR objective of introducing a discount correlation ID. This structural change moves discount management from the product catalog domain to the billing domain.

Since this is generated code (as noted in line 1), run this script to verify all occurrences have been updated consistently:


🏁 Script executed:

#!/bin/bash
# Description: Verify that all references to productcatalog.Discounts have been updated

# Search for any remaining references to productcatalog.Discounts
echo "Checking for remaining references to productcatalog.Discounts:"
rg "productcatalog\.Discounts" -t go

# Check for methods that might need updates due to the type change
echo -e "\nChecking for methods using RatecardDiscounts:"
rg "RatecardDiscounts" -t go

Length of output: 21072


BillingInvoiceLine Discounts Migration Verified

  • The change in openmeter/ent/db/billinginvoiceline/billinginvoiceline.go correctly updates the RatecardDiscounts field—from using *productcatalog.Discounts to *billing.Discounts.
  • The verification script confirms that within this file, all references have been updated to use billing.Discounts.
  • Note that several other files still reference productcatalog.Discounts (in modules like subscription, addon ratecard, plan ratecard, etc.). If this migration is meant to be scoped only to the billing domain, these remaining references are expected; otherwise, a broader update might be required.
openmeter/billing/invoiceline.go (2)

155-156: RateCardDiscounts type updated to use local package type.

The RateCardDiscounts field has been updated to use the local Discounts type rather than productcatalog.Discounts. This change is part of a larger refactoring effort to move discount-related functionality from the productcatalog package to the billing package.


332-335: LGTM: Added new utility method for removing progressive line hierarchy.

The new WithoutProgressiveLineHierarchy() method provides a clean way to set the ProgressiveLineHierarchy field to nil and return a pointer to the modified Line instance. This method follows the same pattern as the existing WithoutDBState() method, maintaining consistency in the codebase.

openmeter/productcatalog/http/mapping.go (2)

613-618: Refactored to use the new AsUsageDiscount helper function.

The implementation now uses the new AsUsageDiscount helper function to convert a DiscountUsage to a UsageDiscount. This refactoring improves code organization by extracting the conversion logic to a dedicated function.


634-643: LGTM: Added a new helper function for discount type conversion.

The new AsUsageDiscount function encapsulates the logic for converting an api.DiscountUsage to a productcatalog.UsageDiscount. This function handles parsing the quantity string to a decimal value and returns appropriate error messages if the parsing fails. The extraction of this logic into a separate function improves code maintainability and reusability.

test/billing/discount_test.go (5)

23-29: LGTM: New test suite for discount correlation ID functionality.

This test suite is well-structured and extends the BaseSuite for testing the new discount correlation ID feature.


31-140: Comprehensive tests for correlation ID handling.

The test verifies that:

  1. Correlation IDs are automatically assigned when creating new pending invoice lines with discounts
  2. The assigned correlation ID is a valid ULID
  3. The correlation ID is properly retained when invoicing pending lines in a progressive billing setup

This test coverage is essential for ensuring that the new correlation ID feature works correctly.


141-176: Well-structured test for progressive billing correlation ID retention.

This test verifies that correlation IDs are retained properly between split lines when using progressive billing. It checks that both the root line and its children maintain the same correlation ID for the discount, and that amount discounts generated during this process retain the original correlation ID.


177-200: LGTM: Test for new discount correlation ID generation.

This test confirms that editing an invoice to add a new discount generates a new correlation ID that is distinct from the original discount's correlation ID, ensuring proper isolation between different discounts.


202-211: Well-implemented helper function for extracting correlation IDs.

The getDiscountCorrelationID function provides a clean way to extract the correlation ID from different types of discounts. It properly handles the discount type variants and uses pattern matching to extract the correlation ID.

openmeter/billing/service/lineservice/feeline_test.go (4)

22-28: Updated to use billing.PercentageDiscount with correlation ID.

The test now uses billing.PercentageDiscount which wraps the original productcatalog.PercentageDiscount and adds a CorrelationID field. This aligns with the new discount correlation ID feature.


39-46: Updated source discount and reference ID to use correlation ID.

The test has been updated to:

  1. Use billing.NewDiscountFrom with the new discount structure
  2. Include the correlation ID in the discount
  3. Generate a child unique reference ID that incorporates the correlation ID

This ensures that the test accurately reflects the new discount correlation ID functionality.


55-55: Updated type of RateCardDiscounts in test input struct.

The RateCardDiscounts field type has been changed from []productcatalog.PercentageDiscount to []billing.PercentageDiscount to align with the broader refactoring of discount types in the codebase.


68-70: Updated discount initialization to use billing.NewDiscountFrom.

The code now properly initializes the RateCardDiscounts field by mapping each billing.PercentageDiscount to a billing.Discount using billing.NewDiscountFrom. This change is consistent with the new discount hierarchy.

api/openapi.cloud.yaml (2)

10741-10808: Define and Validate New Discount Types
The introduction of BillingDiscount, BillingDiscountPercentage, and BillingDiscountUsage provides a clear and flexible structure for representing billing discounts. The use of oneOf along with a discriminator by the type property is well implemented. Please verify that the regular expression used for correlationId accurately reflects the ULID format expected across your system.


15735-15738: Comprehensive Support for Usage-Based Rate Card Discounts
The update in the InvoiceUsageBasedRateCard schema to reference the union type BillingDiscount (which accommodates both percentage and usage discounts) is appropriate. Please ensure that downstream consumers can correctly process the discriminator-based union type. This design supports future flexibility as additional discount types may be introduced.

api/client/javascript/src/client/schemas.ts (4)

2318-2368: Well-structured discount types with correlation ID support

The new discount types are well-defined and properly documented. The optional correlationId field aligns with the PR objective of tracking discounts across line items. The hierarchical structure with a union type is clean and allows for future extensibility.


5894-5895: Appropriate use of union discount type

Using the union type BillingDiscount[] here is appropriate, allowing both percentage and usage-based discounts to be applied to usage-based rate cards, which supports the PR's goal of handling different discount types.


9222-9225: Good practice with type exports

Exporting these types as aliases improves code readability and maintainability by providing direct access to these types without having to reference the nested components structure.


5149-5150:

Details

❓ Verification inconclusive

Verify intended discount type restriction

This field is restricted to percentage-based discounts only (BillingDiscountPercentage[]), while other parts of the schema use the union type that includes both percentage and usage discounts. Is this restriction intentional for flat fee rate cards?


🏁 Script executed:

#!/bin/bash
# Check if other flat fee related schemas also restrict to percentage discounts
echo "Searching for flat fee discount usage patterns..."
rg -A 10 -B 5 "FlatPriceWithPaymentTerm" --include "*.yaml" --include "*.ts" --include "*.go"

Length of output: 644


Here's a revised review comment that reflects the current uncertainties:

Verify discount type consistency for flat fee rate cards
In the file api/client/javascript/src/client/schemas.ts (lines 5149–5150), the discounts field is typed exclusively as BillingDiscountPercentage[], whereas elsewhere in the schema a union type (including both percentage- and usage-based discounts) is used. This raises the question of whether restricting discounts to percentage values for flat fee rate cards is intentional. Since our initial search for instances of flat fee discount usage (via the pattern "FlatPriceWithPaymentTerm") didn’t return any reliable results due to a flag issue with the command, could you please verify manually that this discount type restriction is indeed correct and consistent with the overall design? It might also be helpful to re-run the search using corrected file inclusion flags (for example, using -g instead of --include) to ensure no related cases were overlooked.

@turip
turip merged commit c126d0d into main Apr 9, 2025
@turip
turip deleted the feat/discount-groups branch April 9, 2025 15:46
turip added a commit that referenced this pull request Apr 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area/billing release-note/feature Release note: Exciting New Features

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants