Repository navigation
feat: usage discounts - #2634
Conversation
📝 WalkthroughWalkthroughThis pull request introduces multiple changes to the billing system. A new error is added for handling updates to usage discounts on partially invoiced lines, along with validation logic in invoice line processing. The management of discounts is enhanced through the implementation of cloning and merging methods. Various pricing functions are refactored to utilize new getters for usage data, and new pre-calculation mutators are integrated into the pricing flow. Additionally, one method is removed, and a test is added to verify unit discount behavior under progressive billing scenarios. 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 (
|
fefc04f to
23ec5ca
Compare
095ed01 to
5507a83
Compare
7005b61 to
b954137
Compare
6969b17 to
b9aad73
Compare
4a5b2c0 to
344d466
Compare
4aaedc7 to
24d4f51
Compare
24d4f51 to
37dfe26
Compare
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (5)
openmeter/billing/service/lineservice/pricemutate.go (3)
6-6: Add a short doc comment for thePreCalculationfield.It's beneficial to clearly describe when and how the
PreCalculationmutators should be used. This helps future maintainers understand its purpose within the struct.
15-17: Document thePreCalculationMutatorinterface.Providing a brief doc comment for the newly introduced interface clarifies the contract and expectations for any future implementations.
22-30: Consider customized error handling or rollback logic for partial failures.Currently, if any mutator in the loop fails, the entire calculation returns immediately. Depending on business requirements, you may want to roll back changes from previously successful mutators or allow partial application. Ensure this approach aligns with the desired user experience.
openmeter/billing/service/lineservice/discountusage.go (2)
17-19: Be mindful of non-idempotent mutation logic.
Since this mutator directly manipulates the usage-based line rather than derived lines, multiple calls could result in inconsistent states if the function is incorrectly re-invoked. Consider clarifying usage patterns or providing safeguards to avoid repeated mutation calls.
58-60: Handle overcommitted usage discounts more gracefully.
Currently, the function returns an error if the discount is overcommitted. Depending on business requirements, you may want to provide a fallback, such as automatically removing or reducing the discount instead of failing outright.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
openmeter/billing/errors.go(1 hunks)openmeter/billing/httpdriver/invoiceline.go(2 hunks)openmeter/billing/invoicelinediscount.go(1 hunks)openmeter/billing/invoicelineprogressive.go(3 hunks)openmeter/billing/service/lineservice/commitments.go(1 hunks)openmeter/billing/service/lineservice/discountusage.go(1 hunks)openmeter/billing/service/lineservice/meteredquantity.go(1 hunks)openmeter/billing/service/lineservice/pricedynamic.go(1 hunks)openmeter/billing/service/lineservice/pricegraduatedtiered.go(2 hunks)openmeter/billing/service/lineservice/pricemutate.go(2 hunks)openmeter/billing/service/lineservice/pricepackage.go(1 hunks)openmeter/billing/service/lineservice/pricer.go(2 hunks)openmeter/billing/service/lineservice/priceunit.go(1 hunks)openmeter/billing/service/lineservice/pricevolumetiered.go(2 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)test/billing/discount_test.go(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (11)
openmeter/billing/service/lineservice/commitments.go (1)
openmeter/billing/invoiceline.go (1)
Period(83-86)
openmeter/billing/errors.go (1)
openmeter/billing/validationissue.go (1)
NewValidationError(75-81)
openmeter/billing/service/lineservice/pricemutate.go (1)
openmeter/billing/service/lineservice/pricer.go (2)
PricerCalculateInput(17-17)Pricer(45-51)
openmeter/billing/httpdriver/invoiceline.go (3)
openmeter/billing/discount.go (1)
Discounts(78-81)pkg/equal/equal.go (1)
PtrEqual(13-23)openmeter/billing/errors.go (2)
ValidationError(117-117)ErrInvoiceLineProgressiveBillingUsageDiscountUpdateForbidden(50-50)
openmeter/billing/invoicelineprogressive.go (2)
openmeter/billing/invoiceline.go (2)
Line(279-293)Period(83-86)openmeter/billing/totals.go (1)
Totals(9-26)
openmeter/billing/service/lineservice/meteredquantity.go (3)
openmeter/billing/service/lineservice/pricemutate.go (1)
PreCalculationMutator(15-17)openmeter/billing/service/lineservice/pricer.go (1)
PricerCalculateInput(17-17)openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (2)
MeteredPreLinePeriodQuantity(83-85)MeteredQuantity(88-90)
openmeter/billing/service/lineservice/usagebasedline.go (2)
openmeter/billing/service/lineservice/pricemutate.go (1)
PreCalculationMutator(15-17)openmeter/billing/service/lineservice/pricer.go (1)
PricerCalculateInput(17-17)
test/billing/discount_test.go (3)
openmeter/billing/invoiceline.go (5)
Line(279-293)LineBase(128-162)Period(83-86)UsageBasedLine(703-716)Price(701-701)openmeter/billing/discount.go (2)
Discounts(78-81)UsageDiscount(49-53)openmeter/billing/invoice.go (1)
InvoicePendingLinesInput(761-766)
openmeter/billing/service/lineservice/discountusage.go (5)
openmeter/billing/service/lineservice/pricemutate.go (1)
PreCalculationMutator(15-17)openmeter/billing/service/lineservice/pricer.go (1)
PricerCalculateInput(17-17)openmeter/billing/invoicelinediscount.go (3)
UsageLineDiscountManaged(254-257)UsageLineDiscount(205-210)LineDiscountBase(22-27)openmeter/billing/discount.go (1)
RatecardUsageDiscountReason(133-133)openmeter/billing/service/lineservice/usagebasedline.go (1)
RateCardDiscountChildUniqueReferenceID(38-38)
openmeter/billing/service/lineservice/pricevolumetiered.go (2)
openmeter/billing/errors.go (1)
ErrInvoiceLineVolumeSplitNotSupported(45-45)openmeter/productcatalog/price.go (1)
UnitPrice(426-431)
openmeter/billing/invoicelinediscount.go (2)
pkg/models/clonable.go (1)
Clonable(3-5)pkg/models/model.go (2)
ManagedModelWithID(155-158)ManagedModel(107-113)
⏰ Context from checks skipped due to timeout of 90000ms (9)
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Lint
- GitHub Check: Test
- GitHub Check: Build
- GitHub Check: Analyze (go)
🔇 Additional comments (37)
openmeter/billing/service/lineservice/commitments.go (1)
104-104: Parameter name change aligns with broader refactoring.The parameter rename from
UpTotoPeriodEndLTEin theSumNetAmountInputstruct enhances clarity and aligns with similar changes elsewhere in the codebase. This standardization improves code consistency in how billing periods are handled.openmeter/billing/service/lineservice/priceunit.go (2)
21-24: Good addition of usage data retrieval with error handling.Retrieving usage data through
GetUsage()with proper error handling improves robustness and follows good software engineering practices. This encapsulation allows for better data access control and validation.
26-26: Consistent usage of the retrieved usage object.The implementation correctly uses the obtained usage data for calculations, replacing direct access to line quantities with structured usage properties. This change is consistent with the other pricer implementations in the codebase.
Also applies to: 30-30
openmeter/billing/service/lineservice/pricepackage.go (2)
18-21: Improved error handling with GetUsage() implementation.The addition of proper error handling when retrieving usage data follows good practices. This approach consistently handles potential errors that might occur during usage data retrieval, enhancing the robustness of the package pricer.
28-28: Consistent usage of encapsulated usage data.The implementation correctly transitions from direct access to properly using the encapsulated usage data properties. This maintains the same calculation logic while improving the overall architecture.
Also applies to: 30-30
openmeter/billing/errors.go (1)
50-50: New error for usage discount updates on progressively billed lines.This new error definition properly implements the requirement to prevent usage discount changes on partially invoiced lines. It follows the established error pattern in the codebase and provides a clear, specific error message to end users.
The error is appropriately integrated into the validation framework and supports the PR objective of implementing usage discounts with restrictions on progressively billed lines.
openmeter/billing/httpdriver/invoiceline.go (1)
17-17: Import usage looks correct.The
equalpackage is referenced below for pointer equality checks, aligning with the new discount validation logic. No issues here.openmeter/billing/service/lineservice/pricedynamic.go (2)
18-21: Check for unexpectednilor zero usage cases.While retrieving usage data here is correct, consider verifying upstream that the usage will not be nil or otherwise invalid. If usage retrieval can fail in other ways, adding more specific error handling might improve debuggability.
28-30: Logic to calculate amounts based on usage data looks good.Switching to
usage.LinePeriodQuantityfor the main calculation aligns well with usage-based pricing. This improves clarity concerning how the system determines the relevant quantity.openmeter/billing/service/lineservice/pricegraduatedtiered.go (2)
19-22: Enhanced error handling with GetUsageThe addition of the usage retrieval step improves the code by centralizing access to usage data and providing immediate error handling.
37-38: Consistent usage data access patternThese changes ensure quantities are properly sourced from the usage object, making the calculation more accurate and maintainable by using a consistent data access pattern.
openmeter/billing/service/lineservice/meteredquantity.go (2)
9-14: Well-documented mutator purposeThe comment clearly explains the purpose of the mutator - to reset quantities to metered values before discount application, which helps maintain code clarity.
15-35: Thorough validation in Mutate methodThe implementation correctly validates all required fields before performing updates and provides clear error messages that include the specific line ID for easier debugging.
The approach of copying decimal values with
.Copy()rather than direct assignment prevents potential issues with shared references.openmeter/billing/service/lineservice/pricevolumetiered.go (3)
33-37: Proper usage data retrieval and error handlingThe addition of usage data retrieval with immediate error propagation improves error handling and maintains consistency with other pricing implementations.
38-41: Important validation check preservedThe condition checking has been migrated to use the new usage object while maintaining the critical validation that prevents inappropriate use of progressive billing with volume tiered pricing.
45-45: Consistent usage of retrieved quantitiesThese line changes ensure that all quantity references throughout the pricer use the same source of truth from the usage object, maintaining consistency across the calculation flow.
Also applies to: 65-65, 68-68
test/billing/discount_test.go (6)
205-228: Comprehensive test scenario descriptionThe test header provides a clear explanation of the scenario and expected outcomes for each of the three invoices, making the test purpose and validation criteria easy to understand.
229-282: Well-structured test setupThe test preparation is thorough, creating all necessary prerequisites including a billing profile with progressive billing enabled, a test customer, and appropriate meter setup with the correct feature configuration.
283-326: Proper discount initializationThis section correctly sets up the initial state with a usage discount of 110 units and verifies that the system generates a correlation ID as expected.
327-366: First invoice validationThe first test case correctly validates:
- The metered quantity of 50 vs quantity of 0
- The usage discount application with quantity 50
- The correlation ID preservation
- The absence of child lines when no billable usage exists
This is a critical test case that verifies the initial discount behavior.
368-410: Second invoice progressive validationThis test case thoroughly verifies the correct handling of accumulated usage across invoices:
- The metered quantity of 75 vs billable quantity of 15
- The usage discount with correct quantity (60) and proper tracking of pre-period quantity (50)
- The preservation of the original discount amount (110) in the correlation metadata
- The existence of a child line with the correct quantity (15)
This properly tests the progressive nature of the discount application.
412-442: Final invoice exhaust-discount validationThe final test case correctly validates the exhaustion of the discount:
- The metered quantity equals the billable quantity (30)
- The absence of any usage discount (fully consumed by previous invoices)
- The proper tracking of pre-period quantities
- The child line with correct quantity (30)
This scenario completes the end-to-end testing of the discount lifecycle.
openmeter/billing/service/lineservice/usagebasedline.go (2)
256-259: Added new pre-calculation mutators for better discount handlingThe addition of
discountUsageMutatorto the PreCalculation mutators enhances the pricing flow by allowing usage discounts to be applied systematically. This is a good architectural approach that maintains separation of concerns and makes the discount logic more maintainable.
275-275: Simplified calculation input by using direct type conversionThe code now uses
PricerCalculateInput(l)directly instead of calling the previously existingasPricerCalculateInput()method. This simplification is possible due to the type alias definition in pricer.go, making the code more concise while maintaining functionality.Let's verify that this change maintains all the validation logic that was previously in the
asPricerCalculateInput()method:#!/bin/bash # Search for any validation logic in the removed asPricerCalculateInput method rg -A 10 -B 10 "func \(l usageBasedLine\) asPricerCalculateInput\(\)"openmeter/billing/service/lineservice/pricer.go (4)
17-17: Changed PricerCalculateInput to a type alias for better encapsulationConverting
PricerCalculateInputfrom a struct to a type alias forusageBasedLinesimplifies the code by removing duplication and improving maintainability. This change enables direct type conversion in the calculateDetailedLines method.
19-22: Added new usage struct to encapsulate quantity dataThe new
usagestruct provides better encapsulation of quantity-related data, making the code more maintainable and the data structure clearer.
24-39: Added GetUsage method with proper validationThis method provides robust validation for quantity data, ensuring both
QuantityandPreLinePeriodQuantityare properly set before calculations proceed. The error messages are clear and include the line ID for easier debugging.
41-43: Added convenience method for accessing LinePeriodQuantityThis helper method provides a cleaner way to access the line period quantity directly, which improves code readability in places where only this value is needed without full validation.
openmeter/billing/invoicelinediscount.go (3)
303-303: Added type assertion for Clonable interface implementationThis explicit type assertion ensures that
UsageLineDiscountsManagedproperly implements themodels.Clonableinterface, which is good practice for maintaining type safety.
307-311: Implemented Clone method for UsageLineDiscountsManagedThe Clone method creates a proper deep copy of the discount collection, which is essential for preserving data integrity when manipulating discounts.
313-343: Added MergeDiscountsByChildUniqueReferenceID for discount managementThis method implements a sophisticated discount merging strategy that maintains entity identity while updating content. The approach ensures:
- Existing discounts are preserved with their ID and creation timestamp
- New discounts are properly integrated
- Discounts are matched by their unique reference ID
- Soft-deletion flags aren't carried over
This is critical functionality for handling usage discounts in the context of progressive billing.
Let's verify the implementation with a test case:
#!/bin/bash # Check for test coverage of the new merging functionality rg -A 5 -B 5 "TestUnitDiscountProgressiveBilling"openmeter/billing/invoicelineprogressive.go (4)
37-37: Renamed field to PeriodEndLTE for better semantic clarityRenaming
UpTotoPeriodEndLTEimproves the clarity of the API by making it explicit that the comparison uses less than or equal to logic on the period end time.
47-61: Refactored SumNetAmount to use ForEachChild patternThis refactoring improves code organization by delegating the child iteration logic to a specialized method. The callback pattern used here makes the code more maintainable and enables future enhancements without changing the core traversal logic.
63-66: Added ForEachChildInput struct for callback-based processingThis new struct provides a clear contract for iterating over children with callbacks, promoting better code reusability and maintainability.
68-91: Implemented ForEachChild to standardize child line iterationThis method centralizes the logic for filtering and processing child lines based on specific criteria. It handles:
- Period end time filtering
- Skipping deleted lines
- Skipping lines from deleted invoices
- Applying the provided callback to valid lines
This is an excellent refactoring that follows the Single Responsibility Principle and will reduce code duplication across the codebase.
openmeter/billing/service/lineservice/discountusage.go (2)
79-91: Usage discount merge logic appears correct.
Quality merging of usage discounts by child unique reference ID. This ensures the discount is neatly tracked and combined. No additional concerns here.
128-140: Progressive line hierarchy traversal is well-structured.
The method correctly iterates over child lines, checks for discount correlation, and aggregates used quantities. The approach appears robust for identifying partial usage in previously billed lines.
37dfe26 to
353682c
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
openmeter/billing/invoicelineprogressive.go (1)
68-91: Well-implemented child iteration methodThe
ForEachChildmethod properly filters child lines based on the provided criteria and handles errors appropriately. This abstraction will make it easier to perform various operations on filtered child lines.Note that line 71 now uses
PeriodEndLTEinstead ofUpTo(as mentioned in the method's documentation on line 42), which is consistent with the rename in theSumNetAmountInputstruct.The documentation comment for
SumNetAmount(lines 41-43) still referencesin.UpToand should be updated to referencePeriodEndLTEfor consistency:// SumNetAmount returns the sum of the net amount (pre-tax) of the progressive billed line and its children - // containing the values for all lines whose period's end is <= in.UpTo and are not deleted or not part of + // containing the values for all lines whose period's end is <= in.PeriodEndLTE and are not deleted or not part of // an invoice that has been deleted.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
openmeter/billing/errors.go(1 hunks)openmeter/billing/httpdriver/invoiceline.go(2 hunks)openmeter/billing/invoicelinediscount.go(1 hunks)openmeter/billing/invoicelineprogressive.go(3 hunks)openmeter/billing/service/lineservice/commitments.go(1 hunks)openmeter/billing/service/lineservice/discountusage.go(1 hunks)openmeter/billing/service/lineservice/meteredquantity.go(1 hunks)openmeter/billing/service/lineservice/pricedynamic.go(1 hunks)openmeter/billing/service/lineservice/pricegraduatedtiered.go(2 hunks)openmeter/billing/service/lineservice/pricemutate.go(2 hunks)openmeter/billing/service/lineservice/pricepackage.go(1 hunks)openmeter/billing/service/lineservice/pricer.go(2 hunks)openmeter/billing/service/lineservice/priceunit.go(1 hunks)openmeter/billing/service/lineservice/pricevolumetiered.go(2 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)test/billing/discount_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (10)
- openmeter/billing/service/lineservice/commitments.go
- openmeter/billing/service/lineservice/priceunit.go
- openmeter/billing/service/lineservice/pricedynamic.go
- openmeter/billing/service/lineservice/pricepackage.go
- openmeter/billing/httpdriver/invoiceline.go
- openmeter/billing/service/lineservice/pricevolumetiered.go
- openmeter/billing/service/lineservice/pricemutate.go
- openmeter/billing/service/lineservice/pricegraduatedtiered.go
- openmeter/billing/service/lineservice/pricer.go
- openmeter/billing/service/lineservice/discountusage.go
🧰 Additional context used
🧬 Code Graph Analysis (6)
openmeter/billing/errors.go (1)
openmeter/billing/validationissue.go (1)
NewValidationError(75-81)
test/billing/discount_test.go (4)
openmeter/billing/profile.go (1)
WorkflowConfig(36-40)openmeter/billing/invoiceline.go (3)
Line(279-293)LineBase(128-162)UsageBasedLine(703-716)openmeter/billing/discount.go (2)
Discounts(78-81)UsageDiscount(49-53)openmeter/billing/invoice.go (1)
InvoicePendingLinesInput(761-766)
openmeter/billing/service/lineservice/usagebasedline.go (2)
openmeter/billing/service/lineservice/pricemutate.go (1)
PreCalculationMutator(15-17)openmeter/billing/service/lineservice/pricer.go (1)
PricerCalculateInput(17-17)
openmeter/billing/invoicelineprogressive.go (2)
openmeter/billing/invoiceline.go (2)
Line(279-293)Period(83-86)openmeter/billing/totals.go (1)
Totals(9-26)
openmeter/billing/service/lineservice/meteredquantity.go (3)
openmeter/billing/service/lineservice/pricemutate.go (1)
PreCalculationMutator(15-17)openmeter/billing/service/lineservice/pricer.go (1)
PricerCalculateInput(17-17)openmeter/ent/db/billinginvoiceusagebasedlineconfig/where.go (2)
MeteredPreLinePeriodQuantity(83-85)MeteredQuantity(88-90)
openmeter/billing/invoicelinediscount.go (2)
pkg/models/clonable.go (1)
Clonable(3-5)pkg/models/model.go (2)
ManagedModelWithID(155-158)ManagedModel(107-113)
⏰ Context from checks skipped due to timeout of 90000ms (12)
- GitHub Check: Artifacts / Container image
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Quickstart
- GitHub Check: Developer environment
- GitHub Check: Commit hooks
- GitHub Check: Test
- GitHub Check: Migration Checks
- GitHub Check: Analyze (javascript)
- GitHub Check: Build
- GitHub Check: Lint
- GitHub Check: Analyze (go)
🔇 Additional comments (11)
openmeter/billing/errors.go (1)
50-50: Added new validation error for usage discount updates.This error prevents updates to usage discounts on partially invoiced lines, which aligns with the PR objective of ensuring that usage discounts cannot be modified once progressive billing has begun.
test/billing/discount_test.go (1)
205-443: Comprehensive test for unit discount behavior in progressive billing.This test thoroughly validates the behavior of unit discounts through three stages of progressive billing:
- First invoice with 50 units usage (fully discounted)
- Second invoice with 75 units usage (partially discounted)
- Final invoice with 30 units usage (no discount remaining)
The test verifies that the discount is correctly applied across invoices and that the correlation ID remains consistent.
openmeter/billing/service/lineservice/meteredquantity.go (1)
9-35: New mutator to reset quantity to metered quantity before discount application.This mutator ensures that discounts are applied to the metered quantity rather than the original quantity, which is critical for correct pricing calculations with usage discounts. The implementation includes proper error handling for missing quantities and preserves value integrity through copying.
openmeter/billing/service/lineservice/usagebasedline.go (2)
256-259: Added pre-calculation mutators to the pricing flow.The code now includes both
setQuantityToMeteredQuantityanddiscountUsageMutatorin the pre-calculation step, ensuring that quantities are properly reset to metered values and usage discounts are correctly applied before price calculations.
275-275: Simplified calculateDetailedLines method.The previous
asPricerCalculateInputmethod call has been replaced with a direct type conversion, making the code more straightforward.openmeter/billing/invoicelinediscount.go (3)
303-303: Type assertion ensures interface complianceGood practice using the type assertion to ensure
UsageLineDiscountsManagedimplements themodels.Clonableinterface at compile time.
307-311: Clone implementation looks goodThe implementation properly creates a deep copy of the slice by cloning each item, following Go best practices.
313-343: Merge implementation is well-structuredThe method correctly handles the merging logic based on
ChildUniqueReferenceID. When updating an existing discount, it preserves the original ID and creation timestamp while updating the content. This aligns with the PR objective of supporting usage discounts.One consideration: when merging, if an existing discount is found, the method replaces it entirely with the new discount (except for ID and creation timestamp). Be aware that any other fields present in the old discount that aren't in the new discount will be lost.
Make sure this complete replacement behavior is intended rather than selectively updating fields. If you need more selective updates, consider modifying the implementation.
openmeter/billing/invoicelineprogressive.go (3)
37-37: Improved field naming for clarityChanging from
UpTotoPeriodEndLTEis a good improvement as it more clearly communicates that the field is used to filter lines whose period end is less than or equal to the specified time.
44-61: Good refactoring to callback-based approachRefactoring
SumNetAmountto use a callback-based approach with the newForEachChildmethod improves code organization and separation of concerns. This makes the code more maintainable and extensible.
63-66: Well-structured input structThe
ForEachChildInputstruct is cleanly designed for its purpose, making the API clear and self-documenting.
353682c to
f76e5cd
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
🧹 Nitpick comments (1)
openmeter/billing/service/lineservice/discountusage.go (1)
126-129: Typo in documentation commentThere's a minor typo in the documentation comment.
// calculateUsedQtyByCorrelationID calculates the used quantity by correlation ID for the previously billed lines // by checking the UBP line's discounts. This works because usage discounts are presisted to the UBP line's discounts -// by checking the UBP line's discounts. This works because usage discounts are presisted to the UBP line's discounts +// by checking the UBP line's discounts. This works because usage discounts are persisted to the UBP line's discounts // as they are affecting all the detailed lines.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (16)
openmeter/billing/errors.go(1 hunks)openmeter/billing/httpdriver/invoiceline.go(2 hunks)openmeter/billing/invoicelinediscount.go(1 hunks)openmeter/billing/invoicelineprogressive.go(3 hunks)openmeter/billing/service/lineservice/commitments.go(1 hunks)openmeter/billing/service/lineservice/discountusage.go(1 hunks)openmeter/billing/service/lineservice/meteredquantity.go(1 hunks)openmeter/billing/service/lineservice/pricedynamic.go(1 hunks)openmeter/billing/service/lineservice/pricegraduatedtiered.go(2 hunks)openmeter/billing/service/lineservice/pricemutate.go(2 hunks)openmeter/billing/service/lineservice/pricepackage.go(1 hunks)openmeter/billing/service/lineservice/pricer.go(2 hunks)openmeter/billing/service/lineservice/priceunit.go(1 hunks)openmeter/billing/service/lineservice/pricevolumetiered.go(2 hunks)openmeter/billing/service/lineservice/usagebasedline.go(2 hunks)test/billing/discount_test.go(1 hunks)
🚧 Files skipped from review as they are similar to previous changes (15)
- openmeter/billing/service/lineservice/pricedynamic.go
- openmeter/billing/errors.go
- openmeter/billing/service/lineservice/pricepackage.go
- openmeter/billing/service/lineservice/pricegraduatedtiered.go
- openmeter/billing/service/lineservice/commitments.go
- openmeter/billing/service/lineservice/pricevolumetiered.go
- openmeter/billing/service/lineservice/pricer.go
- openmeter/billing/httpdriver/invoiceline.go
- openmeter/billing/service/lineservice/pricemutate.go
- openmeter/billing/invoicelinediscount.go
- openmeter/billing/service/lineservice/priceunit.go
- openmeter/billing/service/lineservice/usagebasedline.go
- test/billing/discount_test.go
- openmeter/billing/invoicelineprogressive.go
- openmeter/billing/service/lineservice/meteredquantity.go
⏰ Context from checks skipped due to timeout of 90000ms (13)
- GitHub Check: Artifacts / Container image
- GitHub Check: Artifacts / Benthos Collector Container image
- GitHub Check: Quickstart
- GitHub Check: E2E
- GitHub Check: CI
- GitHub Check: Lint
- GitHub Check: Developer environment
- GitHub Check: Test
- GitHub Check: Commit hooks
- GitHub Check: Migration Checks
- GitHub Check: Build
- GitHub Check: Analyze (javascript)
- GitHub Check: Analyze (go)
🔇 Additional comments (9)
openmeter/billing/service/lineservice/discountusage.go (9)
17-23: Good warning comment about non-idempotenceThe comment clearly explains that this mutator modifies the usage based line directly rather than the detailed lines. This is important for maintainers to understand the behavior and potential side effects.
34-38: Good defensive programming for null usage discount caseProperly handling the case when no usage discount is intended by removing any existing usage discounts ensures consistency in the billing system.
40-59: Clear error handling for overcommitted discount quantitiesThe code properly calculates used discount quantities for progressive billing scenarios and provides a clear error message when the discount is overcommitted. This prevents inconsistent billing states.
61-75: Robust discount quantity calculation logicThe implementation correctly handles edge cases:
- Applying the full discount quantity when possible
- Applying partial discount when remaining amount is less than needed
- Removing discount entirely when no quantity is available
- Maintaining consistent state with pre-line period quantities
This ensures correct discount application in all scenarios.
77-91: Clean implementation of discount merging and quantity updatesThe code efficiently:
- Merges discounts by child reference ID
- Sets up the proper discount structure with reason and quantities
- Updates the line quantities to reflect the applied discount
This maintains consistency between discount records and actual billing quantities.
96-102: Efficient usage discount removal logicThe use of
lo.Filterwith a type-based condition makes for clean, maintainable code when removing usage discounts.
116-118: Good validation for missing correlation IDsValidating that correlation IDs exist before proceeding prevents potential data inconsistencies later in the process.
136-165: Thorough child line processing for discount calculationsThe implementation correctly:
- Iterates through child lines in the progressive billing hierarchy
- Filters discounts by type and correlation ID
- Validates discount consistency through child unique reference IDs
- Accumulates used quantities
This ensures accurate tracking of discount usage across billing periods.
150-158: Comprehensive validation for discount correlation consistencyThe code includes important validation to ensure that:
- Correlation IDs exist and match the expected value
- Child unique reference IDs are consistent with the source discount
This helps maintain data integrity and prevent subtle billing errors.
Overview
This patch implements the usage discount support.
If a line is progressive billed (e.g. there's already a line split happened) we are not allowing to change the usage discount for consistency purposes.
Summary by CodeRabbit
New Features
Refactor
Tests