Repository navigation
feat: discount correlation ID - #2636
Conversation
📝 WalkthroughWalkthroughThis 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
Possibly related PRs
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 golangci-lint (1.64.8)Error: you are using a configuration file for golangci-lint v2 with golangci-lint v1: please use golangci-lint v2 ✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
404fb0d to
5e40940
Compare
There was a problem hiding this comment.
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:
- Auto-generated correlation IDs (when none is provided)
- Multiple discounts with different correlation IDs
- Edge cases like empty correlation IDs
openmeter/billing/discount.go (1)
29-46:PercentageDiscountmethods:CloneandEqual
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
📒 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 settingsThis 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 IDChanging the
discountsfield type from[]productcatalog.Discountto[]billing.Discountaligns 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 handlingThe change from
*productcatalog.Discountsto*billing.Discountsis 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 trackingChanging
SourceDiscountfrom*productcatalog.Discountto*billing.Discountcompletes 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
RateCardDiscountChildUniqueReferenceIDhas 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.Discountto*billing.Discount.The
SourceDiscountfield type has been updated to reference thebillingpackage instead ofproductcatalog. 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
RateCardDiscountsfield type has been changed toDiscounts(from what was likelyproductcatalog.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 existingWithoutDBState()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_discountsfield is now using the billing package'sDiscountstype 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_discountfield is now using the billing package'sDiscounttype 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 creationThis change introduces a call to
generateDiscountCorrelationIDsthat 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 fieldThe
SourceDiscountfield type has been changed from*productcatalog.Discountto*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 concernsThe discount conversion logic has been refactored to use the new
AsUsageDiscounthelper 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 conversionA new
AsUsageDiscountfunction 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 propertiesThe
discountsfield has been removed from the required properties in theInvoiceUsageBasedRateCardmodel, 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 typeA new optional
discountsproperty has been added to theInvoiceUsageBasedRateCardmodel using theBillingDiscount[]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 cardSimilar to the usage-based rate card change, the
discountsfield has been removed from the required properties in theInvoiceFlatFeeRateCardmodel.This aligns with the pattern of making discounts optional across rate card types.
791-796: Added optional discounts property with BillingDiscountPercentage typeA new optional
discountsproperty has been added to theInvoiceFlatFeeRateCardmodel using theBillingDiscountPercentage[]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.DiscountsThe field type has been updated from
field.TypeValueScanner[*productcatalog.Discounts]tofield.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 handlingThe restructuring of the
fetchLinesmethod 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 IDThe 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 typeThe slice type has been properly changed to
[]billing.Discountto match the new implementation.
247-248: LGTM: Child discount references correlation IDThe
ChildUniqueReferenceIDnow correctly includes the correlation ID in the formatrateCardDiscount/correlationID=discount-50pct, enabling proper tracking of discounts.
268-275: LGTM: Consistent implementation for multiple discountsThe 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 resultsThe 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.DiscountsMethod signature for
SetRatecardDiscountshas been properly updated to use the new*billing.Discountstype, consistent with the migration from product catalog to billing package for discount management.
1473-1477: LGTM: Consistent update to BillingInvoiceLineUpdateOneThe corresponding method in
BillingInvoiceLineUpdateOnehas 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.BillingDiscountPercentagetobilling.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
BillingDiscountunion 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
BillingDiscountMetadataprovide 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
RateCardDiscountsfield 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
RatecardDiscountsfield scanner now uses*billing.Discountsinstead of*productcatalog.Discounts, enabling the correlation ID tracking capability for discount groups.
518-518: Updated scanner type to support discount correlation IDs.The
SourceDiscountfield scanner now uses*billing.Discountinstead 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
Discountsfield type fromproductcatalog.Discountstobilling.Discountsto 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:
- Uses the new
billing.Discountstype- Takes
api.BillingDiscountPercentageinstead ofapi.DiscountPercentage- Calls
AsPercentageDiscountwhich preserves the correlation IDThis ensures that correlation IDs are properly maintained when processing flat fee rate card discounts.
256-256: Updated discount type to support correlation IDs.Changed
Discountsfield type fromproductcatalog.Discountstobilling.Discountsto 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
AsDiscountsdirectly, 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:
- Creates a billing profile with progressive billing enabled
- Creates a test customer
- Sets up a meter for usage tracking
- Registers usage events
- 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:
- New discounts automatically get assigned a correlation ID
- 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:
- Correlation IDs persist when pending lines are converted to invoice lines
- In progressive billing scenarios, the correlation ID is preserved across all split lines
- 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
getDiscountCorrelationIDfunction 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
SetSourceDiscountmethod now accepts*billing.Discountinstead 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
SetSourceDiscountmethod in the upsert operation now accepts*billing.Discountinstead of*productcatalog.Discount, maintaining consistent type usage across different database operations.
1421-1424: Updated parameter type to support discount correlation IDs.The
SetSourceDiscountmethod in bulk upsert operations now accepts*billing.Discountinstead 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 TypesThe addition of the
BillingDiscount,BillingDiscountPercentage, andBillingDiscountUsageobjects is well-structured. The use ofoneOfwith a discriminator (based on thetypeproperty) clearly differentiates between the percentage and usage discount variants. The defined properties—including the ULID-compatiblecorrelationIdwith 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 DiscountsIn the
InvoiceFlatFeeRateCarddefinition, thediscountsproperty is now defined as an array of items referencingBillingDiscountPercentage. 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 DiscountsThe
discountsproperty for theInvoiceUsageBasedRateCardhas been updated to reference the union typeBillingDiscount. 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, andBillingDiscountUsageobjects are defined clearly. The use ofoneOfalong with the discriminator on thetypeproperty ensures that consumers of the API can correctly determine which subtype they are working with. The pattern forcorrelationIdis 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
discountsproperty for the flat fee rate card has been updated to use an array ofBillingDiscountPercentage. 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 broaderBillingDiscountunion 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 packageThe
discountWithChildReferenceIDstruct now embedsbilling.PercentageDiscountinstead ofproductcatalog.PercentageDiscount, properly aligning with the new discount correlation ID feature.
57-57: Updated parameter type to use billing packageFunction signature now uses
billing.Discountsinstead ofproductcatalog.Discounts, maintaining consistency with the package transition for discount handling.
59-62: Improved loop iteration approachChanged 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 IDImportant 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 IDChanged 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 packageChanged from
productcatalog.NewDiscountFromtobilling.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 typesThe
SetOrClearRatecardDiscountsmethod signatures now accept**billing.Discountsinstead of**productcatalog.Discounts, maintaining consistency with the package transition for discount handling.
1248-1260: Updated method signature to use billing package typesThe
SetOrClearSourceDiscountmethod signatures now accept**billing.Discountinstead 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 typesThe 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 referenceThe discounts field is properly updated to use the new BillingDiscountPercentage type, maintaining consistency with the newly introduced types.
5894-5895: Correctly updated discount type referenceThe 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 addedThe 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 fieldsThe field type is being updated from
**productcatalog.Discountsto**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 typeThe parameter type has been updated from
*productcatalog.Discountsto*billing.Discountsto align with the field type change, while preserving the same implementation pattern.
16432-16435: Updated getter method to match new discount typeReturn type has been updated from
*productcatalog.Discountsto*billing.Discountsto align with the field type change, maintaining functional consistency.
16443-16446: Updated method for retrieving old discount valueReturn type has been updated from
*productcatalog.Discountsto*billing.Discountswhile preserving the operation validation logic.
17564-17567: Updated type assertion for dynamic field settingType check has been updated from
*productcatalog.Discountsto*billing.Discountsto ensure type safety when dynamically setting the field value.
18096-18096: Type migration for source discount fieldSimilarly updating the field type from
**productcatalog.Discountto**billing.Discountfor consistency with the new billing discount structure.
18770-18772: Updated setter method for source discountThe parameter type has been updated from
*productcatalog.Discountto*billing.Discountfor consistency with the field type change.
18775-18778: Updated getter method for source discountReturn type has been updated from
*productcatalog.Discountto*billing.Discountto align with the field type change.
18786-18789: Updated method for retrieving old source discount valueReturn type has been updated from
*productcatalog.Discountto*billing.Discountwhile preserving the operation validation logic.
19165-19168: Updated type assertion for source discount fieldType check has been updated from
*productcatalog.Discountto*billing.Discountto 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
productcatalogpackage types tobillingpackage 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.Discounttype 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
productcatalogdiscount types to the newbillingdiscount types to enable correlation IDs during line splitting events. However, our automated search for thebilling.Discountandproductcatalog.Discountdefinitions did not return any output, so we can’t confirm from the repository that thebilling.Discounttype includes the new correlation ID (or that it is directly compatible with the previous type). Please manually verify that:
- The
billing.Discountstructure is defined as expected and includes a field for the correlation ID.- All relevant code paths (including those in file
openmeter/ent/db/mutation.goaround lines 15314-19168) consistently use the newbilling.Discounttype instead of the oldproductcatalog.Discounttype.Thanks for confirming these details.
openmeter/ent/db/billinginvoiceline_create.go (4)
243-245: Adoptedbilling.Discountsparameter successfully.
Switching the parameter type to*billing.Discountsaligns with the updated discount model and appears straightforward with no immediate issues. Good job!
1229-1233: Consistent update forSetRatecardDiscountsin Upsert.
Ensuring parity with the create logic by using*billing.Discountsmaintains consistency across different creation/upsert flows.
1752-1756: Delegate approach withinSetRatecardDiscountsfor single upsert.
The pattern of callingUpdateto 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 newbilling.Discountsstructure. 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:discountTypeinterface
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:PercentageDiscountstruct
Extendsproductcatalog.PercentageDiscountand adds aCorrelationID. Straightforward design.
48-52:UsageDiscountstruct
Mirrors the percentage discount approach with aCorrelationID. No issues spotted.
54-73:UsageDiscountmethods:CloneandEqual
Builds on the same pattern asPercentageDiscount. Implementation looks consistent.
75-90:discounterinterface
Combines JSON (un)marshaling, cloning, equality, validation, and typed discount methods. This abstraction is well-structured.
91-98:Discountstruct
Holds union-like references with a sub-discount pointer. This is a robust approach, though ensure partial states (e.g., bothpercentageandusagenil) are handled gracefully.
100-133:NewDiscountFromfunction
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:Clonemethod onDiscount
Clones the underlying struct vialo.ToPtr, ensuring correct duplication.
217-230:Equalmethod onDiscount
Checks discount type upfront, then defers to the respective sub-discount equality. Logical and concise.
232-241:Validatemethod
Delegates validation to the embedded discount. Straightforward.
243-252:ValidateForPricemethod
Similarly delegates for price-based checks. Clean design.
254-256:Typemethod
Exposes discount’s underlying type. No issues found.
258-268:AsPercentagemethod
Provides typed access to aPercentageDiscount. Error handling for mismatches is appropriate.
270-280:AsUsagemethod
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:Discountstype andClonemethod
Slices the underlying discount array and clones each item. Implementation is robust.
309-319:ValidateForPriceon a slice of Discounts
Aggregates errors from each discount's validation. Clear approach to collecting all error messages.
5e40940 to
095ed01
Compare
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
openmeter/ent/db/billinginvoicelinediscount_update.go (2)
223-224: Consistent parameter transition tobilling.Discount.
This update fromproductcatalog.Discounttobilling.Discountaligns with the broader discount-correlation refactor.
652-653: Aligning single-entity update with new discount type.
The signature change to accept a*billing.Discountis 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 definingCorrelationIDat 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.
WithCorrelationIDsets 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
📒 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 appropriateThis 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 packageChanging the ValueScanner type from
*productcatalog.Discountsto*billing.Discountsaligns 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 handlingSimilar to the previous change, this updates the ValueScanner type from
*productcatalog.Discountto*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 generationThe
generateDiscountCorrelationIDsfunction 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 architectureChanging
RateCardDiscountsto use the more genericDiscountstype is consistent with the broader refactoring of discount handling within the codebase.
332-335: Good addition of helper method for line hierarchy managementThe
WithoutProgressiveLineHierarchymethod provides a clean way to remove the progressive line hierarchy from aLineinstance. This enhances the functionality of theLinestruct and follows the same pattern as other similar methods likeWithoutDBState.openmeter/productcatalog/http/mapping.go (2)
618-624: Good refactoring to use helper function for discount processingReplacing direct parsing with a call to the new
AsUsageDiscounthelper function improves code organization and maintainability.
639-648: Well-implemented helper function for usage discount conversionThe new
AsUsageDiscountfunction properly encapsulates the logic for converting aDiscountUsageto aUsageDiscount, improving code reusability and error handling.openmeter/billing/service/lineservice/priceunit_test.go (6)
206-209: Good transition to use discount correlation IDs in testsTests 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 implementationThe type change from
productcatalog.Discounttobilling.Discountcorrectly aligns the test with the updated discount handling architecture.
247-248: Effective correlation ID reference in child unique reference IDUsing a formatted string that includes the correlation ID in the
ChildUniqueReferenceIDprovides clear traceability between the discount and its effects.
268-276: Good implementation of multiple discounts with unique correlation IDsCreating 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 caseThe 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 discountsEach 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 fromproductcatalog.PercentageDiscounttobilling.PercentageDiscountand adding the correlation ID field is consistent with the new discount-correlation flow.
39-45: Creating nested billing discount with correlation ID.
Wrapping theproductcatalog.PercentageDiscountinsidebilling.PercentageDiscountviabilling.NewDiscountFromand personalizingChildUniqueReferenceIDwith the correlation ID is a clean approach.
55-55: Transition to[]billing.PercentageDiscount.
Changing theRateCardDiscountsarray type ensures consistency with the rest of the refactor.
68-70: Mapping discounts withbilling.NewDiscountFrom.
Usinglo.Mapto convert eachPercentageDiscountinto abilling.Discountis correct and streamlined.openmeter/billing/httpdriver/deprecations.go (3)
101-101: Field type migrated tobilling.Discounts.
This replacement ofproductcatalog.Discountswithbilling.Discountsis consistent with the new discount architecture.
169-172: MappingBillingDiscountPercentageintobilling.Discount.
Introducing a localdiscountsvariable and converting the slice withbilling.NewDiscountFromsimplifies usage and ensures correct correlation ID handling.
298-300: Consolidated multi-discount parsing.
Definingdiscountsand usingAsDiscountsto 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 aoneOfconstruct along with a discriminator based on thetypeproperty. The inclusion of thecorrelationIdfield—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 thediscountsproperty 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 thediscountsarray 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.DiscountThis 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 BillingInvoiceLineDiscountUpsertConsistent 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 BillingInvoiceLineDiscountUpsertOneThe 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 BillingInvoiceLineDiscountUpsertBulkThis 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/ -nLength of output: 1547
Validate Method Compatibility Check
The call to
Validate()on the source_discount field now invokes the implementation defined atopenmeter/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 previousproductcatalog.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 previousproductcatalog.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 supportThe new
BillingDiscountunion type and its variants (BillingDiscountPercentageandBillingDiscountUsage) are well-defined with appropriate documentation. The optionalcorrelationIdfield in both discount types implements the core feature of this PR - tracking discounts across their lifecycle.The auto-generation note for
correlationIdaligns 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 cardsThe 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 cardsUsage-based rate cards now support both discount types (percentage and usage-based) through the
BillingDiscountunion 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 accessibilityThese 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 interfacediscountType[T]that composesClonable,Equaler, andValidatoris 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 twoPercentageDiscountinstances are equivalent.
296-321: Checks for aggregated discounts look solid.
TheDiscountsslice cloning and validation logic is straightforward and should handle multiple discounts gracefully.
095ed01 to
5507a83
Compare
There was a problem hiding this comment.
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
Discountin 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 suggestionHandle 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 typesapi/openapi.cloud.yaml (2)
10741-10815: Review new BillingDiscount schemas and correlationId usage.
The newBillingDiscountdefinition along with itsBillingDiscountPercentageandBillingDiscountUsagevariants are clearly structured. The use of a discriminator on thetypeproperty 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
correlationIdfollows the ULID format for clarity.- Verify that the enum values for
typein the sub-schemas align perfectly with the mapping values in the discriminator.
14592-14607: Review InvoiceFlatFeeRateCard discount reference update.
Thediscountsproperty forInvoiceFlatFeeRateCardis updated to referenceBillingDiscountPercentageinstead 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
BillingDiscountunion instead.openmeter/billing/discount.go (1)
296-321: Add dedicated test coverage forDiscounts.
Discountsincludes 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
📒 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 IDThe
Discountsfield type has been changed fromproductcatalog.Discountstobilling.Discountsto support the new discount correlation ID functionality.
169-173: Updated discount handling to use new discount typesThe discount mapping logic has been updated to use the new
api.BillingDiscountPercentagetype andbilling.NewDiscountFromfunction withAsPercentageDiscount, which preserves correlation IDs during the mapping process.
298-301: Simplified discount processing for usage-based rate cardsThe usage-based discount processing has been refactored to use
AsDiscountsdirectly, 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 discountsThis function properly handles the generation and validation of correlation IDs for both percentage and usage discounts. It:
- Uses ULID for generating unique, sortable identifiers
- Preserves existing correlation IDs
- Validates the format of existing correlation IDs
- Properly handles different discount types
- Utilizes the
slicesx.MapWithErrhelper for clean error propagationThe 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 IDsThe
RateCardDiscountsfield type has been updated fromproductcatalog.DiscountstoDiscountsto support the new discount correlation ID feature.
332-335: Added utility method for removing progressive line hierarchyThis new method
WithoutProgressiveLineHierarchyprovides a convenient way to set theProgressiveLineHierarchyfield toniland return a pointer to the modifiedLineinstance.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 logicThe 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 helperThis new
AsUsageDiscountfunction cleanly encapsulates the logic for converting anapi.DiscountUsageto aproductcatalog.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
AsPercentageDiscountfunction 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
AsDiscountsfunction 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
getDiscountCorrelationIDfunction 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.
Thediscountsproperty forInvoiceUsageBasedRateCardnow uses the union typeBillingDiscount, 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.DiscountThe
SetSourceDiscountmethod signature has been updated to use the*billing.Discounttype 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 functionalityThe parameter type for
SetSourceDiscountin theBillingInvoiceLineDiscountUpsertstruct has been properly updated to match the type change in the Create struct.
951-956: Consistent type propagation in UpsertOneThe type change has been consistently applied to the
BillingInvoiceLineDiscountUpsertOnestruct'sSetSourceDiscountmethod. This ensures type consistency throughout the invoice line discount operations.
1420-1425: Complete type migration in bulk operationsThe
SetSourceDiscountmethod in theBillingInvoiceLineDiscountUpsertBulkstruct 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 typeThe 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 typeThe 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 documentationThe addition of
BillingDiscount,BillingDiscountPercentage, andBillingDiscountUsageinterfaces 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
BillingDiscountallows 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 discountsChanging 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 discountsUsing 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 typesThese 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
PercentageDiscountandUsageDiscountrely onHash()for equality, then comparingCorrelationID. Confirm theHash()function fromproductcataloglogic 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 withinproductcatalogfor 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 theproductcatalogpackage. 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
productcatalogpackage indeed implements theHash()method correctly.
6969b17 to
b9aad73
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
api/openapi.cloud.yaml (1)
14602-14606: Ensure Consistency for Flat Fee Rate Card Discounts
In theInvoiceFlatFeeRateCardschema, thediscountsproperty now strictly referencesBillingDiscountPercentage. 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
📒 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]tofield.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 goLength of output: 21072
BillingInvoiceLine Discounts Migration Verified
- The change in openmeter/ent/db/billinginvoiceline/billinginvoiceline.go correctly updates the
RatecardDiscountsfield—from using*productcatalog.Discountsto*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
RateCardDiscountsfield has been updated to use the localDiscountstype rather thanproductcatalog.Discounts. This change is part of a larger refactoring effort to move discount-related functionality from theproductcatalogpackage to thebillingpackage.
332-335: LGTM: Added new utility method for removing progressive line hierarchy.The new
WithoutProgressiveLineHierarchy()method provides a clean way to set theProgressiveLineHierarchyfield to nil and return a pointer to the modifiedLineinstance. This method follows the same pattern as the existingWithoutDBState()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
AsUsageDiscounthelper function to convert aDiscountUsageto aUsageDiscount. 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
AsUsageDiscountfunction encapsulates the logic for converting anapi.DiscountUsageto aproductcatalog.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:
- Correlation IDs are automatically assigned when creating new pending invoice lines with discounts
- The assigned correlation ID is a valid ULID
- 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
getDiscountCorrelationIDfunction 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.PercentageDiscountwhich wraps the originalproductcatalog.PercentageDiscountand adds aCorrelationIDfield. 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:
- Use
billing.NewDiscountFromwith the new discount structure- Include the correlation ID in the discount
- 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
RateCardDiscountsfield type has been changed from[]productcatalog.PercentageDiscountto[]billing.PercentageDiscountto 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
RateCardDiscountsfield by mapping eachbilling.PercentageDiscountto abilling.Discountusingbilling.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 ofBillingDiscount,BillingDiscountPercentage, andBillingDiscountUsageprovides a clear and flexible structure for representing billing discounts. The use ofoneOfalong with a discriminator by thetypeproperty is well implemented. Please verify that the regular expression used forcorrelationIdaccurately reflects the ULID format expected across your system.
15735-15738: Comprehensive Support for Usage-Based Rate Card Discounts
The update in theInvoiceUsageBasedRateCardschema to reference the union typeBillingDiscount(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 supportThe new discount types are well-defined and properly documented. The optional
correlationIdfield 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 typeUsing 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 exportsExporting 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 fileapi/client/javascript/src/client/schemas.ts(lines 5149–5150), thediscountsfield is typed exclusively asBillingDiscountPercentage[], 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-ginstead of--include) to ensure no related cases were overlooked.
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:
This approach can unlock multi-line discounts if we ever need them.
Summary by CodeRabbit
New Features
BillingDiscount,BillingDiscountPercentage, andBillingDiscountUsage.Improvements